authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-12-13 15:19:51-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-01-01 17:51:19-07:00
logbc4d2b646d5d09ecb86a3806886fed37e522fdc9
treeb476088e3785c0f2820a5fc1fee3bc880310bc71
parent1642c003b4bab4a53b6094b42d10f6934896801e

compiler: update references to target


10 files changed, 326 insertions(+), 283 deletions(-)

src/Compilation.zig+13-14
...@@ -1915,9 +1915,8 @@ pub fn create(gpa: Allocator, options: InitOptions) !*Compilation {...@@ -1915,9 +1915,8 @@ pub fn create(gpa: Allocator, options: InitOptions) !*Compilation {
1915}1915}
19161916
1917pub fn destroy(self: *Compilation) void {1917pub fn destroy(self: *Compilation) void {
1918 const optional_module = self.module;1918 if (self.bin_file) |lf| lf.destroy();
1919 self.bin_file.destroy();1919 if (self.module) |zcu| zcu.deinit();
1920 if (optional_module) |module| module.deinit();
19211920
1922 const gpa = self.gpa;1921 const gpa = self.gpa;
1923 self.work_queue.deinit();1922 self.work_queue.deinit();
...@@ -2059,9 +2058,9 @@ pub fn update(comp: *Compilation, main_progress_node: *std.Progress.Node) !void...@@ -2059,9 +2058,9 @@ pub fn update(comp: *Compilation, main_progress_node: *std.Progress.Node) !void
20592058
2060 // If using the whole caching strategy, we check for *everything* up front, including2059 // If using the whole caching strategy, we check for *everything* up front, including
2061 // C source files.2060 // C source files.
2062 if (comp.bin_file.options.cache_mode == .whole) {2061 if (comp.cache_mode == .whole) {
2063 // We are about to obtain this lock, so here we give other processes a chance first.2062 // We are about to obtain this lock, so here we give other processes a chance first.
2064 comp.bin_file.releaseLock();2063 if (comp.bin_file) |lf| lf.releaseLock();
20652064
2066 man = comp.cache_parent.obtain();2065 man = comp.cache_parent.obtain();
2067 comp.whole_cache_manifest = &man;2066 comp.whole_cache_manifest = &man;
...@@ -5948,14 +5947,14 @@ pub fn get_libc_crt_file(comp: *Compilation, arena: Allocator, basename: []const...@@ -5948,14 +5947,14 @@ pub fn get_libc_crt_file(comp: *Compilation, arena: Allocator, basename: []const
5948}5947}
59495948
5950fn wantBuildLibCFromSource(comp: Compilation) bool {5949fn wantBuildLibCFromSource(comp: Compilation) bool {
5951 const is_exe_or_dyn_lib = switch (comp.bin_file.options.output_mode) {5950 const is_exe_or_dyn_lib = switch (comp.config.output_mode) {
5952 .Obj => false,5951 .Obj => false,
5953 .Lib => comp.bin_file.options.link_mode == .Dynamic,5952 .Lib => comp.config.link_mode == .Dynamic,
5954 .Exe => true,5953 .Exe => true,
5955 };5954 };
5955 const ofmt = comp.root_mod.resolved_target.result.ofmt;
5956 return comp.config.link_libc and is_exe_or_dyn_lib and5956 return comp.config.link_libc and is_exe_or_dyn_lib and
5957 comp.bin_file.options.libc_installation == null and5957 comp.libc_installation == null and ofmt != .c;
5958 comp.bin_file.options.target.ofmt != .c;
5959}5958}
59605959
5961fn wantBuildGLibCFromSource(comp: Compilation) bool {5960fn wantBuildGLibCFromSource(comp: Compilation) bool {
...@@ -5977,13 +5976,13 @@ fn wantBuildMinGWFromSource(comp: Compilation) bool {...@@ -5977,13 +5976,13 @@ fn wantBuildMinGWFromSource(comp: Compilation) bool {
5977}5976}
59785977
5979fn wantBuildLibUnwindFromSource(comp: *Compilation) bool {5978fn wantBuildLibUnwindFromSource(comp: *Compilation) bool {
5980 const is_exe_or_dyn_lib = switch (comp.bin_file.options.output_mode) {5979 const is_exe_or_dyn_lib = switch (comp.config.output_mode) {
5981 .Obj => false,5980 .Obj => false,
5982 .Lib => comp.bin_file.options.link_mode == .Dynamic,5981 .Lib => comp.config.link_mode == .Dynamic,
5983 .Exe => true,5982 .Exe => true,
5984 };5983 };
5985 return is_exe_or_dyn_lib and comp.bin_file.options.link_libunwind and5984 const ofmt = comp.root_mod.resolved_target.result.ofmt;
5986 comp.bin_file.options.target.ofmt != .c;5985 return is_exe_or_dyn_lib and comp.config.link_libunwind and ofmt != .c;
5987}5986}
59885987
5989fn setAllocFailure(comp: *Compilation) void {5988fn setAllocFailure(comp: *Compilation) void {
...@@ -6112,7 +6111,7 @@ fn canBuildZigLibC(target: std.Target, use_llvm: bool) bool {...@@ -6112,7 +6111,7 @@ fn canBuildZigLibC(target: std.Target, use_llvm: bool) bool {
6112}6111}
61136112
6114pub fn getZigBackend(comp: Compilation) std.builtin.CompilerBackend {6113pub fn getZigBackend(comp: Compilation) std.builtin.CompilerBackend {
6115 const target = comp.bin_file.options.target;6114 const target = comp.root_mod.resolved_target.result;
6116 return target_util.zigBackend(target, comp.bin_file.options.use_llvm);6115 return target_util.zigBackend(target, comp.bin_file.options.use_llvm);
6117}6116}
61186117
src/Module.zig+24-18
...@@ -623,7 +623,8 @@ pub const Decl = struct {...@@ -623,7 +623,8 @@ pub const Decl = struct {
623 // Sanitize the name for nvptx which is more restrictive.623 // Sanitize the name for nvptx which is more restrictive.
624 // TODO This should be handled by the backend, not the frontend. Have a624 // TODO This should be handled by the backend, not the frontend. Have a
625 // look at how the C backend does it for inspiration.625 // look at how the C backend does it for inspiration.
626 if (mod.comp.bin_file.options.target.cpu.arch.isNvptx()) {626 const cpu_arch = mod.root_mod.resolved_target.cpu.arch;
627 if (cpu_arch.isNvptx()) {
627 for (ip.string_bytes.items[start..]) |*byte| switch (byte.*) {628 for (ip.string_bytes.items[start..]) |*byte| switch (byte.*) {
628 '{', '}', '*', '[', ']', '(', ')', ',', ' ', '\'' => byte.* = '_',629 '{', '}', '*', '[', ']', '(', ')', ',', ' ', '\'' => byte.* = '_',
629 else => {},630 else => {},
...@@ -4873,12 +4874,18 @@ pub fn errNoteNonLazy(...@@ -4873,12 +4874,18 @@ pub fn errNoteNonLazy(
4873 };4874 };
4874}4875}
48754876
4876pub fn getTarget(mod: Module) Target {4877/// Deprecated. There is no global target for a Zig Compilation Unit. Instead,
4877 return mod.comp.bin_file.options.target;4878/// look up the target based on the Module that contains the source code being
4879/// analyzed.
4880pub fn getTarget(zcu: Module) Target {
4881 return zcu.root_mod.resolved_target.result;
4878}4882}
48794883
4880pub fn optimizeMode(mod: Module) std.builtin.OptimizeMode {4884/// Deprecated. There is no global optimization mode for a Zig Compilation
4881 return mod.comp.bin_file.options.optimize_mode;4885/// Unit. Instead, look up the optimization mode based on the Module that
4886/// contains the source code being analyzed.
4887pub fn optimizeMode(zcu: Module) std.builtin.OptimizeMode {
4888 return zcu.root_mod.optimize_mode;
4882}4889}
48834890
4884fn lockAndClearFileCompileError(mod: *Module, file: *File) void {4891fn lockAndClearFileCompileError(mod: *Module, file: *File) void {
...@@ -5620,20 +5627,19 @@ pub const Feature = enum {...@@ -5620,20 +5627,19 @@ pub const Feature = enum {
5620 safety_checked_instructions,5627 safety_checked_instructions,
5621};5628};
56225629
5623pub fn backendSupportsFeature(mod: Module, feature: Feature) bool {5630pub fn backendSupportsFeature(zcu: Module, feature: Feature) bool {
5631 const cpu_arch = zcu.root_mod.resolved_target.cpu.arch;
5632 const ofmt = zcu.root_mod.resolved_target.ofmt;
5633 const use_llvm = zcu.comp.config.use_llvm;
5624 return switch (feature) {5634 return switch (feature) {
5625 .panic_fn => mod.comp.bin_file.options.target.ofmt == .c or5635 .panic_fn => ofmt == .c or use_llvm or cpu_arch == .x86_64,
5626 mod.comp.bin_file.options.use_llvm or5636 .panic_unwrap_error => ofmt == .c or use_llvm,
5627 mod.comp.bin_file.options.target.cpu.arch == .x86_64,5637 .safety_check_formatted => ofmt == .c or use_llvm,
5628 .panic_unwrap_error => mod.comp.bin_file.options.target.ofmt == .c or5638 .error_return_trace => use_llvm,
5629 mod.comp.bin_file.options.use_llvm,5639 .is_named_enum_value => use_llvm,
5630 .safety_check_formatted => mod.comp.bin_file.options.target.ofmt == .c or5640 .error_set_has_value => use_llvm or cpu_arch.isWasm(),
5631 mod.comp.bin_file.options.use_llvm,5641 .field_reordering => use_llvm,
5632 .error_return_trace => mod.comp.bin_file.options.use_llvm,5642 .safety_checked_instructions => use_llvm,
5633 .is_named_enum_value => mod.comp.bin_file.options.use_llvm,
5634 .error_set_has_value => mod.comp.bin_file.options.use_llvm or mod.comp.bin_file.options.target.isWasm(),
5635 .field_reordering => mod.comp.bin_file.options.use_llvm,
5636 .safety_checked_instructions => mod.comp.bin_file.options.use_llvm,
5637 };5643 };
5638}5644}
56395645
src/arch/aarch64/CodeGen.zig+22-23
...@@ -329,7 +329,7 @@ const BigTomb = struct {...@@ -329,7 +329,7 @@ const BigTomb = struct {
329const Self = @This();329const Self = @This();
330330
331pub fn generate(331pub fn generate(
332 bin_file: *link.File,332 lf: *link.File,
333 src_loc: Module.SrcLoc,333 src_loc: Module.SrcLoc,
334 func_index: InternPool.Index,334 func_index: InternPool.Index,
335 air: Air,335 air: Air,
...@@ -337,31 +337,30 @@ pub fn generate(...@@ -337,31 +337,30 @@ pub fn generate(
337 code: *std.ArrayList(u8),337 code: *std.ArrayList(u8),
338 debug_output: DebugInfoOutput,338 debug_output: DebugInfoOutput,
339) CodeGenError!Result {339) CodeGenError!Result {
340 if (build_options.skip_non_native and builtin.cpu.arch != bin_file.options.target.cpu.arch) {340 const gpa = lf.comp.gpa;
341 @panic("Attempted to compile for architecture that was disabled by build configuration");341 const zcu = lf.comp.module.?;
342 }342 const func = zcu.funcInfo(func_index);
343343 const fn_owner_decl = zcu.declPtr(func.owner_decl);
344 const mod = bin_file.comp.module.?;
345 const func = mod.funcInfo(func_index);
346 const fn_owner_decl = mod.declPtr(func.owner_decl);
347 assert(fn_owner_decl.has_tv);344 assert(fn_owner_decl.has_tv);
348 const fn_type = fn_owner_decl.ty;345 const fn_type = fn_owner_decl.ty;
346 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
347 const target = &namespace.file_scope.mod.target;
349348
350 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);349 var branch_stack = std.ArrayList(Branch).init(gpa);
351 defer {350 defer {
352 assert(branch_stack.items.len == 1);351 assert(branch_stack.items.len == 1);
353 branch_stack.items[0].deinit(bin_file.allocator);352 branch_stack.items[0].deinit(gpa);
354 branch_stack.deinit();353 branch_stack.deinit();
355 }354 }
356 try branch_stack.append(.{});355 try branch_stack.append(.{});
357356
358 var function = Self{357 var function = Self{
359 .gpa = bin_file.allocator,358 .gpa = gpa,
360 .air = air,359 .air = air,
361 .liveness = liveness,360 .liveness = liveness,
362 .debug_output = debug_output,361 .debug_output = debug_output,
363 .target = &bin_file.options.target,362 .target = target,
364 .bin_file = bin_file,363 .bin_file = lf,
365 .func_index = func_index,364 .func_index = func_index,
366 .owner_decl = func.owner_decl,365 .owner_decl = func.owner_decl,
367 .err_msg = null,366 .err_msg = null,
...@@ -375,15 +374,15 @@ pub fn generate(...@@ -375,15 +374,15 @@ pub fn generate(
375 .end_di_line = func.rbrace_line,374 .end_di_line = func.rbrace_line,
376 .end_di_column = func.rbrace_column,375 .end_di_column = func.rbrace_column,
377 };376 };
378 defer function.stack.deinit(bin_file.allocator);377 defer function.stack.deinit(gpa);
379 defer function.blocks.deinit(bin_file.allocator);378 defer function.blocks.deinit(gpa);
380 defer function.exitlude_jump_relocs.deinit(bin_file.allocator);379 defer function.exitlude_jump_relocs.deinit(gpa);
381 defer function.dbg_info_relocs.deinit(bin_file.allocator);380 defer function.dbg_info_relocs.deinit(gpa);
382381
383 var call_info = function.resolveCallingConventionValues(fn_type) catch |err| switch (err) {382 var call_info = function.resolveCallingConventionValues(fn_type) catch |err| switch (err) {
384 error.CodegenFail => return Result{ .fail = function.err_msg.? },383 error.CodegenFail => return Result{ .fail = function.err_msg.? },
385 error.OutOfRegisters => return Result{384 error.OutOfRegisters => return Result{
386 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),385 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
387 },386 },
388 else => |e| return e,387 else => |e| return e,
389 };388 };
...@@ -397,7 +396,7 @@ pub fn generate(...@@ -397,7 +396,7 @@ pub fn generate(
397 function.gen() catch |err| switch (err) {396 function.gen() catch |err| switch (err) {
398 error.CodegenFail => return Result{ .fail = function.err_msg.? },397 error.CodegenFail => return Result{ .fail = function.err_msg.? },
399 error.OutOfRegisters => return Result{398 error.OutOfRegisters => return Result{
400 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),399 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
401 },400 },
402 else => |e| return e,401 else => |e| return e,
403 };402 };
...@@ -408,15 +407,15 @@ pub fn generate(...@@ -408,15 +407,15 @@ pub fn generate(
408407
409 var mir = Mir{408 var mir = Mir{
410 .instructions = function.mir_instructions.toOwnedSlice(),409 .instructions = function.mir_instructions.toOwnedSlice(),
411 .extra = try function.mir_extra.toOwnedSlice(bin_file.allocator),410 .extra = try function.mir_extra.toOwnedSlice(gpa),
412 };411 };
413 defer mir.deinit(bin_file.allocator);412 defer mir.deinit(gpa);
414413
415 var emit = Emit{414 var emit = Emit{
416 .mir = mir,415 .mir = mir,
417 .bin_file = bin_file,416 .bin_file = lf,
418 .debug_output = debug_output,417 .debug_output = debug_output,
419 .target = &bin_file.options.target,418 .target = target,
420 .src_loc = src_loc,419 .src_loc = src_loc,
421 .code = code,420 .code = code,
422 .prev_di_pc = 0,421 .prev_di_pc = 0,
src/arch/arm/CodeGen.zig+23-24
...@@ -336,7 +336,7 @@ const DbgInfoReloc = struct {...@@ -336,7 +336,7 @@ const DbgInfoReloc = struct {
336const Self = @This();336const Self = @This();
337337
338pub fn generate(338pub fn generate(
339 bin_file: *link.File,339 lf: *link.File,
340 src_loc: Module.SrcLoc,340 src_loc: Module.SrcLoc,
341 func_index: InternPool.Index,341 func_index: InternPool.Index,
342 air: Air,342 air: Air,
...@@ -344,30 +344,29 @@ pub fn generate(...@@ -344,30 +344,29 @@ pub fn generate(
344 code: *std.ArrayList(u8),344 code: *std.ArrayList(u8),
345 debug_output: DebugInfoOutput,345 debug_output: DebugInfoOutput,
346) CodeGenError!Result {346) CodeGenError!Result {
347 if (build_options.skip_non_native and builtin.cpu.arch != bin_file.options.target.cpu.arch) {347 const gpa = lf.comp.gpa;
348 @panic("Attempted to compile for architecture that was disabled by build configuration");348 const zcu = lf.comp.module.?;
349 }349 const func = zcu.funcInfo(func_index);
350350 const fn_owner_decl = zcu.declPtr(func.owner_decl);
351 const mod = bin_file.comp.module.?;
352 const func = mod.funcInfo(func_index);
353 const fn_owner_decl = mod.declPtr(func.owner_decl);
354 assert(fn_owner_decl.has_tv);351 assert(fn_owner_decl.has_tv);
355 const fn_type = fn_owner_decl.ty;352 const fn_type = fn_owner_decl.ty;
353 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
354 const target = &namespace.file_scope.mod.target;
356355
357 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);356 var branch_stack = std.ArrayList(Branch).init(gpa);
358 defer {357 defer {
359 assert(branch_stack.items.len == 1);358 assert(branch_stack.items.len == 1);
360 branch_stack.items[0].deinit(bin_file.allocator);359 branch_stack.items[0].deinit(gpa);
361 branch_stack.deinit();360 branch_stack.deinit();
362 }361 }
363 try branch_stack.append(.{});362 try branch_stack.append(.{});
364363
365 var function = Self{364 var function: Self = .{
366 .gpa = bin_file.allocator,365 .gpa = gpa,
367 .air = air,366 .air = air,
368 .liveness = liveness,367 .liveness = liveness,
369 .target = &bin_file.options.target,368 .target = target,
370 .bin_file = bin_file,369 .bin_file = lf,
371 .debug_output = debug_output,370 .debug_output = debug_output,
372 .func_index = func_index,371 .func_index = func_index,
373 .err_msg = null,372 .err_msg = null,
...@@ -381,15 +380,15 @@ pub fn generate(...@@ -381,15 +380,15 @@ pub fn generate(
381 .end_di_line = func.rbrace_line,380 .end_di_line = func.rbrace_line,
382 .end_di_column = func.rbrace_column,381 .end_di_column = func.rbrace_column,
383 };382 };
384 defer function.stack.deinit(bin_file.allocator);383 defer function.stack.deinit(gpa);
385 defer function.blocks.deinit(bin_file.allocator);384 defer function.blocks.deinit(gpa);
386 defer function.exitlude_jump_relocs.deinit(bin_file.allocator);385 defer function.exitlude_jump_relocs.deinit(gpa);
387 defer function.dbg_info_relocs.deinit(bin_file.allocator);386 defer function.dbg_info_relocs.deinit(gpa);
388387
389 var call_info = function.resolveCallingConventionValues(fn_type) catch |err| switch (err) {388 var call_info = function.resolveCallingConventionValues(fn_type) catch |err| switch (err) {
390 error.CodegenFail => return Result{ .fail = function.err_msg.? },389 error.CodegenFail => return Result{ .fail = function.err_msg.? },
391 error.OutOfRegisters => return Result{390 error.OutOfRegisters => return Result{
392 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),391 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
393 },392 },
394 else => |e| return e,393 else => |e| return e,
395 };394 };
...@@ -403,7 +402,7 @@ pub fn generate(...@@ -403,7 +402,7 @@ pub fn generate(
403 function.gen() catch |err| switch (err) {402 function.gen() catch |err| switch (err) {
404 error.CodegenFail => return Result{ .fail = function.err_msg.? },403 error.CodegenFail => return Result{ .fail = function.err_msg.? },
405 error.OutOfRegisters => return Result{404 error.OutOfRegisters => return Result{
406 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),405 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
407 },406 },
408 else => |e| return e,407 else => |e| return e,
409 };408 };
...@@ -414,15 +413,15 @@ pub fn generate(...@@ -414,15 +413,15 @@ pub fn generate(
414413
415 var mir = Mir{414 var mir = Mir{
416 .instructions = function.mir_instructions.toOwnedSlice(),415 .instructions = function.mir_instructions.toOwnedSlice(),
417 .extra = try function.mir_extra.toOwnedSlice(bin_file.allocator),416 .extra = try function.mir_extra.toOwnedSlice(gpa),
418 };417 };
419 defer mir.deinit(bin_file.allocator);418 defer mir.deinit(gpa);
420419
421 var emit = Emit{420 var emit = Emit{
422 .mir = mir,421 .mir = mir,
423 .bin_file = bin_file,422 .bin_file = lf,
424 .debug_output = debug_output,423 .debug_output = debug_output,
425 .target = &bin_file.options.target,424 .target = target,
426 .src_loc = src_loc,425 .src_loc = src_loc,
427 .code = code,426 .code = code,
428 .prev_di_pc = 0,427 .prev_di_pc = 0,
src/arch/riscv64/CodeGen.zig+21-22
...@@ -217,7 +217,7 @@ const BigTomb = struct {...@@ -217,7 +217,7 @@ const BigTomb = struct {
217const Self = @This();217const Self = @This();
218218
219pub fn generate(219pub fn generate(
220 bin_file: *link.File,220 lf: *link.File,
221 src_loc: Module.SrcLoc,221 src_loc: Module.SrcLoc,
222 func_index: InternPool.Index,222 func_index: InternPool.Index,
223 air: Air,223 air: Air,
...@@ -225,30 +225,29 @@ pub fn generate(...@@ -225,30 +225,29 @@ pub fn generate(
225 code: *std.ArrayList(u8),225 code: *std.ArrayList(u8),
226 debug_output: DebugInfoOutput,226 debug_output: DebugInfoOutput,
227) CodeGenError!Result {227) CodeGenError!Result {
228 if (build_options.skip_non_native and builtin.cpu.arch != bin_file.options.target.cpu.arch) {228 const gpa = lf.comp.gpa;
229 @panic("Attempted to compile for architecture that was disabled by build configuration");229 const zcu = lf.comp.module.?;
230 }230 const func = zcu.funcInfo(func_index);
231231 const fn_owner_decl = zcu.declPtr(func.owner_decl);
232 const mod = bin_file.comp.module.?;
233 const func = mod.funcInfo(func_index);
234 const fn_owner_decl = mod.declPtr(func.owner_decl);
235 assert(fn_owner_decl.has_tv);232 assert(fn_owner_decl.has_tv);
236 const fn_type = fn_owner_decl.ty;233 const fn_type = fn_owner_decl.ty;
234 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
235 const target = &namespace.file_scope.mod.target;
237236
238 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);237 var branch_stack = std.ArrayList(Branch).init(gpa);
239 defer {238 defer {
240 assert(branch_stack.items.len == 1);239 assert(branch_stack.items.len == 1);
241 branch_stack.items[0].deinit(bin_file.allocator);240 branch_stack.items[0].deinit(gpa);
242 branch_stack.deinit();241 branch_stack.deinit();
243 }242 }
244 try branch_stack.append(.{});243 try branch_stack.append(.{});
245244
246 var function = Self{245 var function = Self{
247 .gpa = bin_file.allocator,246 .gpa = gpa,
248 .air = air,247 .air = air,
249 .liveness = liveness,248 .liveness = liveness,
250 .target = &bin_file.options.target,249 .target = target,
251 .bin_file = bin_file,250 .bin_file = lf,
252 .func_index = func_index,251 .func_index = func_index,
253 .code = code,252 .code = code,
254 .debug_output = debug_output,253 .debug_output = debug_output,
...@@ -263,14 +262,14 @@ pub fn generate(...@@ -263,14 +262,14 @@ pub fn generate(
263 .end_di_line = func.rbrace_line,262 .end_di_line = func.rbrace_line,
264 .end_di_column = func.rbrace_column,263 .end_di_column = func.rbrace_column,
265 };264 };
266 defer function.stack.deinit(bin_file.allocator);265 defer function.stack.deinit(gpa);
267 defer function.blocks.deinit(bin_file.allocator);266 defer function.blocks.deinit(gpa);
268 defer function.exitlude_jump_relocs.deinit(bin_file.allocator);267 defer function.exitlude_jump_relocs.deinit(gpa);
269268
270 var call_info = function.resolveCallingConventionValues(fn_type) catch |err| switch (err) {269 var call_info = function.resolveCallingConventionValues(fn_type) catch |err| switch (err) {
271 error.CodegenFail => return Result{ .fail = function.err_msg.? },270 error.CodegenFail => return Result{ .fail = function.err_msg.? },
272 error.OutOfRegisters => return Result{271 error.OutOfRegisters => return Result{
273 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),272 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
274 },273 },
275 else => |e| return e,274 else => |e| return e,
276 };275 };
...@@ -284,22 +283,22 @@ pub fn generate(...@@ -284,22 +283,22 @@ pub fn generate(
284 function.gen() catch |err| switch (err) {283 function.gen() catch |err| switch (err) {
285 error.CodegenFail => return Result{ .fail = function.err_msg.? },284 error.CodegenFail => return Result{ .fail = function.err_msg.? },
286 error.OutOfRegisters => return Result{285 error.OutOfRegisters => return Result{
287 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),286 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
288 },287 },
289 else => |e| return e,288 else => |e| return e,
290 };289 };
291290
292 var mir = Mir{291 var mir = Mir{
293 .instructions = function.mir_instructions.toOwnedSlice(),292 .instructions = function.mir_instructions.toOwnedSlice(),
294 .extra = try function.mir_extra.toOwnedSlice(bin_file.allocator),293 .extra = try function.mir_extra.toOwnedSlice(gpa),
295 };294 };
296 defer mir.deinit(bin_file.allocator);295 defer mir.deinit(gpa);
297296
298 var emit = Emit{297 var emit = Emit{
299 .mir = mir,298 .mir = mir,
300 .bin_file = bin_file,299 .bin_file = lf,
301 .debug_output = debug_output,300 .debug_output = debug_output,
302 .target = &bin_file.options.target,301 .target = target,
303 .src_loc = src_loc,302 .src_loc = src_loc,
304 .code = code,303 .code = code,
305 .prev_di_pc = 0,304 .prev_di_pc = 0,
src/arch/sparc64/CodeGen.zig+21-22
...@@ -260,7 +260,7 @@ const BigTomb = struct {...@@ -260,7 +260,7 @@ const BigTomb = struct {
260};260};
261261
262pub fn generate(262pub fn generate(
263 bin_file: *link.File,263 lf: *link.File,
264 src_loc: Module.SrcLoc,264 src_loc: Module.SrcLoc,
265 func_index: InternPool.Index,265 func_index: InternPool.Index,
266 air: Air,266 air: Air,
...@@ -268,31 +268,30 @@ pub fn generate(...@@ -268,31 +268,30 @@ pub fn generate(
268 code: *std.ArrayList(u8),268 code: *std.ArrayList(u8),
269 debug_output: DebugInfoOutput,269 debug_output: DebugInfoOutput,
270) CodeGenError!Result {270) CodeGenError!Result {
271 if (build_options.skip_non_native and builtin.cpu.arch != bin_file.options.target.cpu.arch) {271 const gpa = lf.comp.gpa;
272 @panic("Attempted to compile for architecture that was disabled by build configuration");272 const zcu = lf.comp.module.?;
273 }273 const func = zcu.funcInfo(func_index);
274274 const fn_owner_decl = zcu.declPtr(func.owner_decl);
275 const mod = bin_file.comp.module.?;
276 const func = mod.funcInfo(func_index);
277 const fn_owner_decl = mod.declPtr(func.owner_decl);
278 assert(fn_owner_decl.has_tv);275 assert(fn_owner_decl.has_tv);
279 const fn_type = fn_owner_decl.ty;276 const fn_type = fn_owner_decl.ty;
277 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
278 const target = &namespace.file_scope.mod.target;
280279
281 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);280 var branch_stack = std.ArrayList(Branch).init(gpa);
282 defer {281 defer {
283 assert(branch_stack.items.len == 1);282 assert(branch_stack.items.len == 1);
284 branch_stack.items[0].deinit(bin_file.allocator);283 branch_stack.items[0].deinit(gpa);
285 branch_stack.deinit();284 branch_stack.deinit();
286 }285 }
287 try branch_stack.append(.{});286 try branch_stack.append(.{});
288287
289 var function = Self{288 var function = Self{
290 .gpa = bin_file.allocator,289 .gpa = gpa,
291 .air = air,290 .air = air,
292 .liveness = liveness,291 .liveness = liveness,
293 .target = &bin_file.options.target,292 .target = target,
294 .func_index = func_index,293 .func_index = func_index,
295 .bin_file = bin_file,294 .bin_file = lf,
296 .code = code,295 .code = code,
297 .debug_output = debug_output,296 .debug_output = debug_output,
298 .err_msg = null,297 .err_msg = null,
...@@ -306,14 +305,14 @@ pub fn generate(...@@ -306,14 +305,14 @@ pub fn generate(
306 .end_di_line = func.rbrace_line,305 .end_di_line = func.rbrace_line,
307 .end_di_column = func.rbrace_column,306 .end_di_column = func.rbrace_column,
308 };307 };
309 defer function.stack.deinit(bin_file.allocator);308 defer function.stack.deinit(gpa);
310 defer function.blocks.deinit(bin_file.allocator);309 defer function.blocks.deinit(gpa);
311 defer function.exitlude_jump_relocs.deinit(bin_file.allocator);310 defer function.exitlude_jump_relocs.deinit(gpa);
312311
313 var call_info = function.resolveCallingConventionValues(fn_type, .callee) catch |err| switch (err) {312 var call_info = function.resolveCallingConventionValues(fn_type, .callee) catch |err| switch (err) {
314 error.CodegenFail => return Result{ .fail = function.err_msg.? },313 error.CodegenFail => return Result{ .fail = function.err_msg.? },
315 error.OutOfRegisters => return Result{314 error.OutOfRegisters => return Result{
316 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),315 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
317 },316 },
318 else => |e| return e,317 else => |e| return e,
319 };318 };
...@@ -327,22 +326,22 @@ pub fn generate(...@@ -327,22 +326,22 @@ pub fn generate(
327 function.gen() catch |err| switch (err) {326 function.gen() catch |err| switch (err) {
328 error.CodegenFail => return Result{ .fail = function.err_msg.? },327 error.CodegenFail => return Result{ .fail = function.err_msg.? },
329 error.OutOfRegisters => return Result{328 error.OutOfRegisters => return Result{
330 .fail = try ErrorMsg.create(bin_file.allocator, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),329 .fail = try ErrorMsg.create(gpa, src_loc, "CodeGen ran out of registers. This is a bug in the Zig compiler.", .{}),
331 },330 },
332 else => |e| return e,331 else => |e| return e,
333 };332 };
334333
335 var mir = Mir{334 var mir = Mir{
336 .instructions = function.mir_instructions.toOwnedSlice(),335 .instructions = function.mir_instructions.toOwnedSlice(),
337 .extra = try function.mir_extra.toOwnedSlice(bin_file.allocator),336 .extra = try function.mir_extra.toOwnedSlice(gpa),
338 };337 };
339 defer mir.deinit(bin_file.allocator);338 defer mir.deinit(gpa);
340339
341 var emit = Emit{340 var emit = Emit{
342 .mir = mir,341 .mir = mir,
343 .bin_file = bin_file,342 .bin_file = lf,
344 .debug_output = debug_output,343 .debug_output = debug_output,
345 .target = &bin_file.options.target,344 .target = target,
346 .src_loc = src_loc,345 .src_loc = src_loc,
347 .code = code,346 .code = code,
348 .prev_di_pc = 0,347 .prev_di_pc = 0,
src/arch/wasm/CodeGen.zig+5-2
...@@ -1212,16 +1212,19 @@ pub fn generate(...@@ -1212,16 +1212,19 @@ pub fn generate(
1212 _ = src_loc;1212 _ = src_loc;
1213 const mod = bin_file.comp.module.?;1213 const mod = bin_file.comp.module.?;
1214 const func = mod.funcInfo(func_index);1214 const func = mod.funcInfo(func_index);
1215 const decl = mod.declPtr(func.owner_decl);
1216 const namespace = mod.namespacePtr(decl.src_namespace);
1217 const target = namespace.file_scope.mod.target;
1215 var code_gen: CodeGen = .{1218 var code_gen: CodeGen = .{
1216 .gpa = bin_file.allocator,1219 .gpa = bin_file.allocator,
1217 .air = air,1220 .air = air,
1218 .liveness = liveness,1221 .liveness = liveness,
1219 .code = code,1222 .code = code,
1220 .decl_index = func.owner_decl,1223 .decl_index = func.owner_decl,
1221 .decl = mod.declPtr(func.owner_decl),1224 .decl = decl,
1222 .err_msg = undefined,1225 .err_msg = undefined,
1223 .locals = .{},1226 .locals = .{},
1224 .target = bin_file.options.target,1227 .target = target,
1225 .bin_file = bin_file.cast(link.File.Wasm).?,1228 .bin_file = bin_file.cast(link.File.Wasm).?,
1226 .debug_output = debug_output,1229 .debug_output = debug_output,
1227 .func_index = func_index,1230 .func_index = func_index,
src/arch/x86_64/CodeGen.zig+10-7
...@@ -795,22 +795,20 @@ pub fn generate(...@@ -795,22 +795,20 @@ pub fn generate(
795 code: *std.ArrayList(u8),795 code: *std.ArrayList(u8),
796 debug_output: DebugInfoOutput,796 debug_output: DebugInfoOutput,
797) CodeGenError!Result {797) CodeGenError!Result {
798 if (build_options.skip_non_native and builtin.cpu.arch != bin_file.options.target.cpu.arch) {
799 @panic("Attempted to compile for architecture that was disabled by build configuration");
800 }
801
802 const mod = bin_file.comp.module.?;798 const mod = bin_file.comp.module.?;
803 const func = mod.funcInfo(func_index);799 const func = mod.funcInfo(func_index);
804 const fn_owner_decl = mod.declPtr(func.owner_decl);800 const fn_owner_decl = mod.declPtr(func.owner_decl);
805 assert(fn_owner_decl.has_tv);801 assert(fn_owner_decl.has_tv);
806 const fn_type = fn_owner_decl.ty;802 const fn_type = fn_owner_decl.ty;
803 const namespace = mod.namespacePtr(fn_owner_decl.src_namespace);
804 const target = namespace.file_scope.mod.target;
807805
808 const gpa = bin_file.allocator;806 const gpa = bin_file.allocator;
809 var function = Self{807 var function = Self{
810 .gpa = gpa,808 .gpa = gpa,
811 .air = air,809 .air = air,
812 .liveness = liveness,810 .liveness = liveness,
813 .target = &bin_file.options.target,811 .target = target,
814 .bin_file = bin_file,812 .bin_file = bin_file,
815 .debug_output = debug_output,813 .debug_output = debug_output,
816 .owner = .{ .func_index = func_index },814 .owner = .{ .func_index = func_index },
...@@ -882,7 +880,7 @@ pub fn generate(...@@ -882,7 +880,7 @@ pub fn generate(
882 .size = Type.usize.abiSize(mod),880 .size = Type.usize.abiSize(mod),
883 .alignment = Alignment.min(881 .alignment = Alignment.min(
884 call_info.stack_align,882 call_info.stack_align,
885 Alignment.fromNonzeroByteUnits(bin_file.options.target.stackAlignment()),883 Alignment.fromNonzeroByteUnits(target.stackAlignment()),
886 ),884 ),
887 }));885 }));
888 function.frame_allocs.set(886 function.frame_allocs.set(
...@@ -967,11 +965,16 @@ pub fn generateLazy(...@@ -967,11 +965,16 @@ pub fn generateLazy(
967 debug_output: DebugInfoOutput,965 debug_output: DebugInfoOutput,
968) CodeGenError!Result {966) CodeGenError!Result {
969 const gpa = bin_file.allocator;967 const gpa = bin_file.allocator;
968 const zcu = bin_file.comp.module.?;
969 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);
970 const decl = zcu.declPtr(decl_index);
971 const namespace = zcu.namespacePtr(decl.src_namespace);
972 const target = namespace.file_scope.mod.target;
970 var function = Self{973 var function = Self{
971 .gpa = gpa,974 .gpa = gpa,
972 .air = undefined,975 .air = undefined,
973 .liveness = undefined,976 .liveness = undefined,
974 .target = &bin_file.options.target,977 .target = target,
975 .bin_file = bin_file,978 .bin_file = bin_file,
976 .debug_output = debug_output,979 .debug_output = debug_output,
977 .owner = .{ .lazy_sym = lazy_sym },980 .owner = .{ .lazy_sym = lazy_sym },
src/codegen.zig+153-129
...@@ -45,7 +45,7 @@ pub const DebugInfoOutput = union(enum) {...@@ -45,7 +45,7 @@ pub const DebugInfoOutput = union(enum) {
45};45};
4646
47pub fn generateFunction(47pub fn generateFunction(
48 bin_file: *link.File,48 lf: *link.File,
49 src_loc: Module.SrcLoc,49 src_loc: Module.SrcLoc,
50 func_index: InternPool.Index,50 func_index: InternPool.Index,
51 air: Air,51 air: Air,
...@@ -53,33 +53,43 @@ pub fn generateFunction(...@@ -53,33 +53,43 @@ pub fn generateFunction(
53 code: *std.ArrayList(u8),53 code: *std.ArrayList(u8),
54 debug_output: DebugInfoOutput,54 debug_output: DebugInfoOutput,
55) CodeGenError!Result {55) CodeGenError!Result {
56 switch (bin_file.options.target.cpu.arch) {56 const zcu = lf.comp.module.?;
57 const func = zcu.funcInfo(func_index);
58 const decl = zcu.declPtr(func.owner_decl);
59 const namespace = zcu.namespacePtr(decl.src_namespace);
60 const target = namespace.file_scope.mod.target;
61 switch (target.cpu.arch) {
57 .arm,62 .arm,
58 .armeb,63 .armeb,
59 => return @import("arch/arm/CodeGen.zig").generate(bin_file, src_loc, func_index, air, liveness, code, debug_output),64 => return @import("arch/arm/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
60 .aarch64,65 .aarch64,
61 .aarch64_be,66 .aarch64_be,
62 .aarch64_32,67 .aarch64_32,
63 => return @import("arch/aarch64/CodeGen.zig").generate(bin_file, src_loc, func_index, air, liveness, code, debug_output),68 => return @import("arch/aarch64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
64 .riscv64 => return @import("arch/riscv64/CodeGen.zig").generate(bin_file, src_loc, func_index, air, liveness, code, debug_output),69 .riscv64 => return @import("arch/riscv64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
65 .sparc64 => return @import("arch/sparc64/CodeGen.zig").generate(bin_file, src_loc, func_index, air, liveness, code, debug_output),70 .sparc64 => return @import("arch/sparc64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
66 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generate(bin_file, src_loc, func_index, air, liveness, code, debug_output),71 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
67 .wasm32,72 .wasm32,
68 .wasm64,73 .wasm64,
69 => return @import("arch/wasm/CodeGen.zig").generate(bin_file, src_loc, func_index, air, liveness, code, debug_output),74 => return @import("arch/wasm/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
70 else => unreachable,75 else => unreachable,
71 }76 }
72}77}
7378
74pub fn generateLazyFunction(79pub fn generateLazyFunction(
75 bin_file: *link.File,80 lf: *link.File,
76 src_loc: Module.SrcLoc,81 src_loc: Module.SrcLoc,
77 lazy_sym: link.File.LazySymbol,82 lazy_sym: link.File.LazySymbol,
78 code: *std.ArrayList(u8),83 code: *std.ArrayList(u8),
79 debug_output: DebugInfoOutput,84 debug_output: DebugInfoOutput,
80) CodeGenError!Result {85) CodeGenError!Result {
81 switch (bin_file.options.target.cpu.arch) {86 const zcu = lf.comp.module.?;
82 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(bin_file, src_loc, lazy_sym, code, debug_output),87 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);
88 const decl = zcu.declPtr(decl_index);
89 const namespace = zcu.namespacePtr(decl.src_namespace);
90 const target = namespace.file_scope.mod.target;
91 switch (target.cpu.arch) {
92 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, src_loc, lazy_sym, code, debug_output),
83 else => unreachable,93 else => unreachable,
84 }94 }
85}95}
...@@ -107,13 +117,16 @@ pub fn generateLazySymbol(...@@ -107,13 +117,16 @@ pub fn generateLazySymbol(
107 const tracy = trace(@src());117 const tracy = trace(@src());
108 defer tracy.end();118 defer tracy.end();
109119
110 const target = bin_file.options.target;120 const zcu = bin_file.comp.module.?;
121 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);
122 const decl = zcu.declPtr(decl_index);
123 const namespace = zcu.namespacePtr(decl.src_namespace);
124 const target = namespace.file_scope.mod.target;
111 const endian = target.cpu.arch.endian();125 const endian = target.cpu.arch.endian();
112126
113 const mod = bin_file.comp.module.?;
114 log.debug("generateLazySymbol: kind = {s}, ty = {}", .{127 log.debug("generateLazySymbol: kind = {s}, ty = {}", .{
115 @tagName(lazy_sym.kind),128 @tagName(lazy_sym.kind),
116 lazy_sym.ty.fmt(mod),129 lazy_sym.ty.fmt(zcu),
117 });130 });
118131
119 if (lazy_sym.kind == .code) {132 if (lazy_sym.kind == .code) {
...@@ -121,14 +134,14 @@ pub fn generateLazySymbol(...@@ -121,14 +134,14 @@ pub fn generateLazySymbol(
121 return generateLazyFunction(bin_file, src_loc, lazy_sym, code, debug_output);134 return generateLazyFunction(bin_file, src_loc, lazy_sym, code, debug_output);
122 }135 }
123136
124 if (lazy_sym.ty.isAnyError(mod)) {137 if (lazy_sym.ty.isAnyError(zcu)) {
125 alignment.* = .@"4";138 alignment.* = .@"4";
126 const err_names = mod.global_error_set.keys();139 const err_names = zcu.global_error_set.keys();
127 mem.writeInt(u32, try code.addManyAsArray(4), @as(u32, @intCast(err_names.len)), endian);140 mem.writeInt(u32, try code.addManyAsArray(4), @as(u32, @intCast(err_names.len)), endian);
128 var offset = code.items.len;141 var offset = code.items.len;
129 try code.resize((1 + err_names.len + 1) * 4);142 try code.resize((1 + err_names.len + 1) * 4);
130 for (err_names) |err_name_nts| {143 for (err_names) |err_name_nts| {
131 const err_name = mod.intern_pool.stringToSlice(err_name_nts);144 const err_name = zcu.intern_pool.stringToSlice(err_name_nts);
132 mem.writeInt(u32, code.items[offset..][0..4], @as(u32, @intCast(code.items.len)), endian);145 mem.writeInt(u32, code.items[offset..][0..4], @as(u32, @intCast(code.items.len)), endian);
133 offset += 4;146 offset += 4;
134 try code.ensureUnusedCapacity(err_name.len + 1);147 try code.ensureUnusedCapacity(err_name.len + 1);
...@@ -137,10 +150,10 @@ pub fn generateLazySymbol(...@@ -137,10 +150,10 @@ pub fn generateLazySymbol(
137 }150 }
138 mem.writeInt(u32, code.items[offset..][0..4], @as(u32, @intCast(code.items.len)), endian);151 mem.writeInt(u32, code.items[offset..][0..4], @as(u32, @intCast(code.items.len)), endian);
139 return Result.ok;152 return Result.ok;
140 } else if (lazy_sym.ty.zigTypeTag(mod) == .Enum) {153 } else if (lazy_sym.ty.zigTypeTag(zcu) == .Enum) {
141 alignment.* = .@"1";154 alignment.* = .@"1";
142 for (lazy_sym.ty.enumFields(mod)) |tag_name_ip| {155 for (lazy_sym.ty.enumFields(zcu)) |tag_name_ip| {
143 const tag_name = mod.intern_pool.stringToSlice(tag_name_ip);156 const tag_name = zcu.intern_pool.stringToSlice(tag_name_ip);
144 try code.ensureUnusedCapacity(tag_name.len + 1);157 try code.ensureUnusedCapacity(tag_name.len + 1);
145 code.appendSliceAssumeCapacity(tag_name);158 code.appendSliceAssumeCapacity(tag_name);
146 code.appendAssumeCapacity(0);159 code.appendAssumeCapacity(0);
...@@ -150,7 +163,7 @@ pub fn generateLazySymbol(...@@ -150,7 +163,7 @@ pub fn generateLazySymbol(
150 bin_file.allocator,163 bin_file.allocator,
151 src_loc,164 src_loc,
152 "TODO implement generateLazySymbol for {s} {}",165 "TODO implement generateLazySymbol for {s} {}",
153 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(mod) },166 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(zcu) },
154 ) };167 ) };
155}168}
156169
...@@ -757,7 +770,7 @@ const RelocInfo = struct {...@@ -757,7 +770,7 @@ const RelocInfo = struct {
757};770};
758771
759fn lowerAnonDeclRef(772fn lowerAnonDeclRef(
760 bin_file: *link.File,773 lf: *link.File,
761 src_loc: Module.SrcLoc,774 src_loc: Module.SrcLoc,
762 anon_decl: InternPool.Key.Ptr.Addr.AnonDecl,775 anon_decl: InternPool.Key.Ptr.Addr.AnonDecl,
763 code: *std.ArrayList(u8),776 code: *std.ArrayList(u8),
...@@ -765,27 +778,27 @@ fn lowerAnonDeclRef(...@@ -765,27 +778,27 @@ fn lowerAnonDeclRef(
765 reloc_info: RelocInfo,778 reloc_info: RelocInfo,
766) CodeGenError!Result {779) CodeGenError!Result {
767 _ = debug_output;780 _ = debug_output;
768 const target = bin_file.options.target;781 const zcu = lf.comp.module.?;
769 const mod = bin_file.comp.module.?;782 const target = lf.comp.root_mod.resolved_target.result;
770783
771 const ptr_width_bytes = @divExact(target.ptrBitWidth(), 8);784 const ptr_width_bytes = @divExact(target.ptrBitWidth(), 8);
772 const decl_val = anon_decl.val;785 const decl_val = anon_decl.val;
773 const decl_ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));786 const decl_ty = Type.fromInterned(zcu.intern_pool.typeOf(decl_val));
774 log.debug("lowerAnonDecl: ty = {}", .{decl_ty.fmt(mod)});787 log.debug("lowerAnonDecl: ty = {}", .{decl_ty.fmt(zcu)});
775 const is_fn_body = decl_ty.zigTypeTag(mod) == .Fn;788 const is_fn_body = decl_ty.zigTypeTag(zcu) == .Fn;
776 if (!is_fn_body and !decl_ty.hasRuntimeBits(mod)) {789 if (!is_fn_body and !decl_ty.hasRuntimeBits(zcu)) {
777 try code.appendNTimes(0xaa, ptr_width_bytes);790 try code.appendNTimes(0xaa, ptr_width_bytes);
778 return Result.ok;791 return Result.ok;
779 }792 }
780793
781 const decl_align = mod.intern_pool.indexToKey(anon_decl.orig_ty).ptr_type.flags.alignment;794 const decl_align = zcu.intern_pool.indexToKey(anon_decl.orig_ty).ptr_type.flags.alignment;
782 const res = try bin_file.lowerAnonDecl(decl_val, decl_align, src_loc);795 const res = try lf.lowerAnonDecl(decl_val, decl_align, src_loc);
783 switch (res) {796 switch (res) {
784 .ok => {},797 .ok => {},
785 .fail => |em| return .{ .fail = em },798 .fail => |em| return .{ .fail = em },
786 }799 }
787800
788 const vaddr = try bin_file.getAnonDeclVAddr(decl_val, .{801 const vaddr = try lf.getAnonDeclVAddr(decl_val, .{
789 .parent_atom_index = reloc_info.parent_atom_index,802 .parent_atom_index = reloc_info.parent_atom_index,
790 .offset = code.items.len,803 .offset = code.items.len,
791 .addend = reloc_info.addend orelse 0,804 .addend = reloc_info.addend orelse 0,
...@@ -802,7 +815,7 @@ fn lowerAnonDeclRef(...@@ -802,7 +815,7 @@ fn lowerAnonDeclRef(
802}815}
803816
804fn lowerDeclRef(817fn lowerDeclRef(
805 bin_file: *link.File,818 lf: *link.File,
806 src_loc: Module.SrcLoc,819 src_loc: Module.SrcLoc,
807 decl_index: InternPool.DeclIndex,820 decl_index: InternPool.DeclIndex,
808 code: *std.ArrayList(u8),821 code: *std.ArrayList(u8),
...@@ -811,20 +824,21 @@ fn lowerDeclRef(...@@ -811,20 +824,21 @@ fn lowerDeclRef(
811) CodeGenError!Result {824) CodeGenError!Result {
812 _ = src_loc;825 _ = src_loc;
813 _ = debug_output;826 _ = debug_output;
814 const target = bin_file.options.target;827 const zcu = lf.comp.module.?;
815 const mod = bin_file.comp.module.?;828 const decl = zcu.declPtr(decl_index);
829 const namespace = zcu.namespacePtr(decl.src_namespace);
830 const target = namespace.file_scope.mod.target;
816831
817 const ptr_width = target.ptrBitWidth();832 const ptr_width = target.ptrBitWidth();
818 const decl = mod.declPtr(decl_index);833 const is_fn_body = decl.ty.zigTypeTag(zcu) == .Fn;
819 const is_fn_body = decl.ty.zigTypeTag(mod) == .Fn;834 if (!is_fn_body and !decl.ty.hasRuntimeBits(zcu)) {
820 if (!is_fn_body and !decl.ty.hasRuntimeBits(mod)) {
821 try code.appendNTimes(0xaa, @divExact(ptr_width, 8));835 try code.appendNTimes(0xaa, @divExact(ptr_width, 8));
822 return Result.ok;836 return Result.ok;
823 }837 }
824838
825 try mod.markDeclAlive(decl);839 try zcu.markDeclAlive(decl);
826840
827 const vaddr = try bin_file.getDeclVAddr(decl_index, .{841 const vaddr = try lf.getDeclVAddr(decl_index, .{
828 .parent_atom_index = reloc_info.parent_atom_index,842 .parent_atom_index = reloc_info.parent_atom_index,
829 .offset = code.items.len,843 .offset = code.items.len,
830 .addend = reloc_info.addend orelse 0,844 .addend = reloc_info.addend orelse 0,
...@@ -897,27 +911,29 @@ pub const GenResult = union(enum) {...@@ -897,27 +911,29 @@ pub const GenResult = union(enum) {
897};911};
898912
899fn genDeclRef(913fn genDeclRef(
900 bin_file: *link.File,914 lf: *link.File,
901 src_loc: Module.SrcLoc,915 src_loc: Module.SrcLoc,
902 tv: TypedValue,916 tv: TypedValue,
903 ptr_decl_index: InternPool.DeclIndex,917 ptr_decl_index: InternPool.DeclIndex,
904) CodeGenError!GenResult {918) CodeGenError!GenResult {
905 const mod = bin_file.comp.module.?;919 const zcu = lf.comp.module.?;
906 log.debug("genDeclRef: ty = {}, val = {}", .{ tv.ty.fmt(mod), tv.val.fmtValue(tv.ty, mod) });920 log.debug("genDeclRef: ty = {}, val = {}", .{ tv.ty.fmt(zcu), tv.val.fmtValue(tv.ty, zcu) });
921
922 const ptr_decl = zcu.declPtr(ptr_decl_index);
923 const namespace = zcu.namespacePtr(ptr_decl.src_namespace);
924 const target = namespace.file_scope.mod.target;
907925
908 const target = bin_file.options.target;
909 const ptr_bits = target.ptrBitWidth();926 const ptr_bits = target.ptrBitWidth();
910 const ptr_bytes: u64 = @divExact(ptr_bits, 8);927 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
911928
912 const ptr_decl = mod.declPtr(ptr_decl_index);929 const decl_index = switch (zcu.intern_pool.indexToKey(try ptr_decl.internValue(zcu))) {
913 const decl_index = switch (mod.intern_pool.indexToKey(try ptr_decl.internValue(mod))) {
914 .func => |func| func.owner_decl,930 .func => |func| func.owner_decl,
915 .extern_func => |extern_func| extern_func.decl,931 .extern_func => |extern_func| extern_func.decl,
916 else => ptr_decl_index,932 else => ptr_decl_index,
917 };933 };
918 const decl = mod.declPtr(decl_index);934 const decl = zcu.declPtr(decl_index);
919935
920 if (!decl.ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {936 if (!decl.ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) {
921 const imm: u64 = switch (ptr_bytes) {937 const imm: u64 = switch (ptr_bytes) {
922 1 => 0xaa,938 1 => 0xaa,
923 2 => 0xaaaa,939 2 => 0xaaaa,
...@@ -929,30 +945,30 @@ fn genDeclRef(...@@ -929,30 +945,30 @@ fn genDeclRef(
929 }945 }
930946
931 // TODO this feels clunky. Perhaps we should check for it in `genTypedValue`?947 // TODO this feels clunky. Perhaps we should check for it in `genTypedValue`?
932 if (tv.ty.castPtrToFn(mod)) |fn_ty| {948 if (tv.ty.castPtrToFn(zcu)) |fn_ty| {
933 if (mod.typeToFunc(fn_ty).?.is_generic) {949 if (zcu.typeToFunc(fn_ty).?.is_generic) {
934 return GenResult.mcv(.{ .immediate = fn_ty.abiAlignment(mod).toByteUnitsOptional().? });950 return GenResult.mcv(.{ .immediate = fn_ty.abiAlignment(zcu).toByteUnitsOptional().? });
935 }951 }
936 } else if (tv.ty.zigTypeTag(mod) == .Pointer) {952 } else if (tv.ty.zigTypeTag(zcu) == .Pointer) {
937 const elem_ty = tv.ty.elemType2(mod);953 const elem_ty = tv.ty.elemType2(zcu);
938 if (!elem_ty.hasRuntimeBits(mod)) {954 if (!elem_ty.hasRuntimeBits(zcu)) {
939 return GenResult.mcv(.{ .immediate = elem_ty.abiAlignment(mod).toByteUnitsOptional().? });955 return GenResult.mcv(.{ .immediate = elem_ty.abiAlignment(zcu).toByteUnitsOptional().? });
940 }956 }
941 }957 }
942958
943 try mod.markDeclAlive(decl);959 try zcu.markDeclAlive(decl);
944960
945 const decl_namespace = mod.namespacePtr(decl.namespace_index);961 const decl_namespace = zcu.namespacePtr(decl.namespace_index);
946 const single_threaded = decl_namespace.file_scope.mod.single_threaded;962 const single_threaded = decl_namespace.file_scope.zcu.single_threaded;
947 const is_threadlocal = tv.val.isPtrToThreadLocal(mod) and !single_threaded;963 const is_threadlocal = tv.val.isPtrToThreadLocal(zcu) and !single_threaded;
948 const is_extern = decl.isExtern(mod);964 const is_extern = decl.isExtern(zcu);
949965
950 if (bin_file.cast(link.File.Elf)) |elf_file| {966 if (lf.cast(link.File.Elf)) |elf_file| {
951 if (is_extern) {967 if (is_extern) {
952 const name = mod.intern_pool.stringToSlice(decl.name);968 const name = zcu.intern_pool.stringToSlice(decl.name);
953 // TODO audit this969 // TODO audit this
954 const lib_name = if (decl.getOwnedVariable(mod)) |ov|970 const lib_name = if (decl.getOwnedVariable(zcu)) |ov|
955 mod.intern_pool.stringToSliceUnwrap(ov.lib_name)971 zcu.intern_pool.stringToSliceUnwrap(ov.lib_name)
956 else972 else
957 null;973 null;
958 const sym_index = try elf_file.getGlobalSymbol(name, lib_name);974 const sym_index = try elf_file.getGlobalSymbol(name, lib_name);
...@@ -965,12 +981,12 @@ fn genDeclRef(...@@ -965,12 +981,12 @@ fn genDeclRef(
965 return GenResult.mcv(.{ .load_tlv = sym.esym_index });981 return GenResult.mcv(.{ .load_tlv = sym.esym_index });
966 }982 }
967 return GenResult.mcv(.{ .load_symbol = sym.esym_index });983 return GenResult.mcv(.{ .load_symbol = sym.esym_index });
968 } else if (bin_file.cast(link.File.MachO)) |macho_file| {984 } else if (lf.cast(link.File.MachO)) |macho_file| {
969 if (is_extern) {985 if (is_extern) {
970 // TODO make this part of getGlobalSymbol986 // TODO make this part of getGlobalSymbol
971 const name = mod.intern_pool.stringToSlice(decl.name);987 const name = zcu.intern_pool.stringToSlice(decl.name);
972 const sym_name = try std.fmt.allocPrint(bin_file.allocator, "_{s}", .{name});988 const sym_name = try std.fmt.allocPrint(lf.allocator, "_{s}", .{name});
973 defer bin_file.allocator.free(sym_name);989 defer lf.allocator.free(sym_name);
974 const global_index = try macho_file.addUndefined(sym_name, .{ .add_got = true });990 const global_index = try macho_file.addUndefined(sym_name, .{ .add_got = true });
975 return GenResult.mcv(.{ .load_got = link.File.MachO.global_symbol_bit | global_index });991 return GenResult.mcv(.{ .load_got = link.File.MachO.global_symbol_bit | global_index });
976 }992 }
...@@ -980,110 +996,118 @@ fn genDeclRef(...@@ -980,110 +996,118 @@ fn genDeclRef(
980 return GenResult.mcv(.{ .load_tlv = sym_index });996 return GenResult.mcv(.{ .load_tlv = sym_index });
981 }997 }
982 return GenResult.mcv(.{ .load_got = sym_index });998 return GenResult.mcv(.{ .load_got = sym_index });
983 } else if (bin_file.cast(link.File.Coff)) |coff_file| {999 } else if (lf.cast(link.File.Coff)) |coff_file| {
984 if (is_extern) {1000 if (is_extern) {
985 const name = mod.intern_pool.stringToSlice(decl.name);1001 const name = zcu.intern_pool.stringToSlice(decl.name);
986 // TODO audit this1002 // TODO audit this
987 const lib_name = if (decl.getOwnedVariable(mod)) |ov|1003 const lib_name = if (decl.getOwnedVariable(zcu)) |ov|
988 mod.intern_pool.stringToSliceUnwrap(ov.lib_name)1004 zcu.intern_pool.stringToSliceUnwrap(ov.lib_name)
989 else1005 else
990 null;1006 null;
991 const global_index = try coff_file.getGlobalSymbol(name, lib_name);1007 const global_index = try coff_file.getGlobalSymbol(name, lib_name);
992 try coff_file.need_got_table.put(bin_file.allocator, global_index, {}); // needs GOT1008 try coff_file.need_got_table.put(lf.allocator, global_index, {}); // needs GOT
993 return GenResult.mcv(.{ .load_got = link.File.Coff.global_symbol_bit | global_index });1009 return GenResult.mcv(.{ .load_got = link.File.Coff.global_symbol_bit | global_index });
994 }1010 }
995 const atom_index = try coff_file.getOrCreateAtomForDecl(decl_index);1011 const atom_index = try coff_file.getOrCreateAtomForDecl(decl_index);
996 const sym_index = coff_file.getAtom(atom_index).getSymbolIndex().?;1012 const sym_index = coff_file.getAtom(atom_index).getSymbolIndex().?;
997 return GenResult.mcv(.{ .load_got = sym_index });1013 return GenResult.mcv(.{ .load_got = sym_index });
998 } else if (bin_file.cast(link.File.Plan9)) |p9| {1014 } else if (lf.cast(link.File.Plan9)) |p9| {
999 const atom_index = try p9.seeDecl(decl_index);1015 const atom_index = try p9.seeDecl(decl_index);
1000 const atom = p9.getAtom(atom_index);1016 const atom = p9.getAtom(atom_index);
1001 return GenResult.mcv(.{ .memory = atom.getOffsetTableAddress(p9) });1017 return GenResult.mcv(.{ .memory = atom.getOffsetTableAddress(p9) });
1002 } else {1018 } else {
1003 return GenResult.fail(bin_file.allocator, src_loc, "TODO genDeclRef for target {}", .{target});1019 return GenResult.fail(lf.allocator, src_loc, "TODO genDeclRef for target {}", .{target});
1004 }1020 }
1005}1021}
10061022
1007fn genUnnamedConst(1023fn genUnnamedConst(
1008 bin_file: *link.File,1024 lf: *link.File,
1009 src_loc: Module.SrcLoc,1025 src_loc: Module.SrcLoc,
1010 tv: TypedValue,1026 tv: TypedValue,
1011 owner_decl_index: InternPool.DeclIndex,1027 owner_decl_index: InternPool.DeclIndex,
1012) CodeGenError!GenResult {1028) CodeGenError!GenResult {
1013 const mod = bin_file.comp.module.?;1029 const zcu = lf.comp.module.?;
1014 log.debug("genUnnamedConst: ty = {}, val = {}", .{ tv.ty.fmt(mod), tv.val.fmtValue(tv.ty, mod) });1030 const gpa = lf.comp.gpa;
1031 log.debug("genUnnamedConst: ty = {}, val = {}", .{ tv.ty.fmt(zcu), tv.val.fmtValue(tv.ty, zcu) });
10151032
1016 const target = bin_file.options.target;1033 const local_sym_index = lf.lowerUnnamedConst(tv, owner_decl_index) catch |err| {
1017 const local_sym_index = bin_file.lowerUnnamedConst(tv, owner_decl_index) catch |err| {1034 return GenResult.fail(gpa, src_loc, "lowering unnamed constant failed: {s}", .{@errorName(err)});
1018 return GenResult.fail(bin_file.allocator, src_loc, "lowering unnamed constant failed: {s}", .{@errorName(err)});
1019 };1035 };
1020 if (bin_file.cast(link.File.Elf)) |elf_file| {1036 switch (lf.tag) {
1021 const local = elf_file.symbol(local_sym_index);1037 .elf => {
1022 return GenResult.mcv(.{ .load_symbol = local.esym_index });1038 const elf_file = lf.cast(link.File.Elf).?;
1023 } else if (bin_file.cast(link.File.MachO)) |_| {1039 const local = elf_file.symbol(local_sym_index);
1024 return GenResult.mcv(.{ .load_direct = local_sym_index });1040 return GenResult.mcv(.{ .load_symbol = local.esym_index });
1025 } else if (bin_file.cast(link.File.Coff)) |_| {1041 },
1026 return GenResult.mcv(.{ .load_direct = local_sym_index });1042 .macho, .coff => {
1027 } else if (bin_file.cast(link.File.Plan9)) |_| {1043 return GenResult.mcv(.{ .load_direct = local_sym_index });
1028 const atom_index = local_sym_index; // plan9 returns the atom_index1044 },
1029 return GenResult.mcv(.{ .load_direct = atom_index });1045 .plan9 => {
1030 } else {1046 const atom_index = local_sym_index; // plan9 returns the atom_index
1031 return GenResult.fail(bin_file.allocator, src_loc, "TODO genUnnamedConst for target {}", .{target});1047 return GenResult.mcv(.{ .load_direct = atom_index });
1048 },
1049
1050 .c => return GenResult.fail(gpa, src_loc, "TODO genUnnamedConst for -ofmt=c", .{}),
1051 .wasm => return GenResult.fail(gpa, src_loc, "TODO genUnnamedConst for wasm", .{}),
1052 .spirv => return GenResult.fail(gpa, src_loc, "TODO genUnnamedConst for spirv", .{}),
1053 .nvptx => return GenResult.fail(gpa, src_loc, "TODO genUnnamedConst for nvptx", .{}),
1032 }1054 }
1033}1055}
10341056
1035pub fn genTypedValue(1057pub fn genTypedValue(
1036 bin_file: *link.File,1058 lf: *link.File,
1037 src_loc: Module.SrcLoc,1059 src_loc: Module.SrcLoc,
1038 arg_tv: TypedValue,1060 arg_tv: TypedValue,
1039 owner_decl_index: InternPool.DeclIndex,1061 owner_decl_index: InternPool.DeclIndex,
1040) CodeGenError!GenResult {1062) CodeGenError!GenResult {
1041 const mod = bin_file.comp.module.?;1063 const zcu = lf.comp.module.?;
1042 const typed_value = arg_tv;1064 const typed_value = arg_tv;
10431065
1044 log.debug("genTypedValue: ty = {}, val = {}", .{1066 log.debug("genTypedValue: ty = {}, val = {}", .{
1045 typed_value.ty.fmt(mod),1067 typed_value.ty.fmt(zcu),
1046 typed_value.val.fmtValue(typed_value.ty, mod),1068 typed_value.val.fmtValue(typed_value.ty, zcu),
1047 });1069 });
10481070
1049 if (typed_value.val.isUndef(mod))1071 if (typed_value.val.isUndef(zcu))
1050 return GenResult.mcv(.undef);1072 return GenResult.mcv(.undef);
10511073
1052 const target = bin_file.options.target;1074 const owner_decl = zcu.declPtr(owner_decl_index);
1075 const namespace = zcu.namespacePtr(owner_decl.src_namespace);
1076 const target = namespace.file_scope.mod.target;
1053 const ptr_bits = target.ptrBitWidth();1077 const ptr_bits = target.ptrBitWidth();
10541078
1055 if (!typed_value.ty.isSlice(mod)) switch (mod.intern_pool.indexToKey(typed_value.val.toIntern())) {1079 if (!typed_value.ty.isSlice(zcu)) switch (zcu.intern_pool.indexToKey(typed_value.val.toIntern())) {
1056 .ptr => |ptr| switch (ptr.addr) {1080 .ptr => |ptr| switch (ptr.addr) {
1057 .decl => |decl| return genDeclRef(bin_file, src_loc, typed_value, decl),1081 .decl => |decl| return genDeclRef(lf, src_loc, typed_value, decl),
1058 .mut_decl => |mut_decl| return genDeclRef(bin_file, src_loc, typed_value, mut_decl.decl),1082 .mut_decl => |mut_decl| return genDeclRef(lf, src_loc, typed_value, mut_decl.decl),
1059 else => {},1083 else => {},
1060 },1084 },
1061 else => {},1085 else => {},
1062 };1086 };
10631087
1064 switch (typed_value.ty.zigTypeTag(mod)) {1088 switch (typed_value.ty.zigTypeTag(zcu)) {
1065 .Void => return GenResult.mcv(.none),1089 .Void => return GenResult.mcv(.none),
1066 .Pointer => switch (typed_value.ty.ptrSize(mod)) {1090 .Pointer => switch (typed_value.ty.ptrSize(zcu)) {
1067 .Slice => {},1091 .Slice => {},
1068 else => switch (typed_value.val.toIntern()) {1092 else => switch (typed_value.val.toIntern()) {
1069 .null_value => {1093 .null_value => {
1070 return GenResult.mcv(.{ .immediate = 0 });1094 return GenResult.mcv(.{ .immediate = 0 });
1071 },1095 },
1072 .none => {},1096 .none => {},
1073 else => switch (mod.intern_pool.indexToKey(typed_value.val.toIntern())) {1097 else => switch (zcu.intern_pool.indexToKey(typed_value.val.toIntern())) {
1074 .int => {1098 .int => {
1075 return GenResult.mcv(.{ .immediate = typed_value.val.toUnsignedInt(mod) });1099 return GenResult.mcv(.{ .immediate = typed_value.val.toUnsignedInt(zcu) });
1076 },1100 },
1077 else => {},1101 else => {},
1078 },1102 },
1079 },1103 },
1080 },1104 },
1081 .Int => {1105 .Int => {
1082 const info = typed_value.ty.intInfo(mod);1106 const info = typed_value.ty.intInfo(zcu);
1083 if (info.bits <= ptr_bits) {1107 if (info.bits <= ptr_bits) {
1084 const unsigned = switch (info.signedness) {1108 const unsigned = switch (info.signedness) {
1085 .signed => @as(u64, @bitCast(typed_value.val.toSignedInt(mod))),1109 .signed => @as(u64, @bitCast(typed_value.val.toSignedInt(zcu))),
1086 .unsigned => typed_value.val.toUnsignedInt(mod),1110 .unsigned => typed_value.val.toUnsignedInt(zcu),
1087 };1111 };
1088 return GenResult.mcv(.{ .immediate = unsigned });1112 return GenResult.mcv(.{ .immediate = unsigned });
1089 }1113 }
...@@ -1092,45 +1116,45 @@ pub fn genTypedValue(...@@ -1092,45 +1116,45 @@ pub fn genTypedValue(
1092 return GenResult.mcv(.{ .immediate = @intFromBool(typed_value.val.toBool()) });1116 return GenResult.mcv(.{ .immediate = @intFromBool(typed_value.val.toBool()) });
1093 },1117 },
1094 .Optional => {1118 .Optional => {
1095 if (typed_value.ty.isPtrLikeOptional(mod)) {1119 if (typed_value.ty.isPtrLikeOptional(zcu)) {
1096 return genTypedValue(bin_file, src_loc, .{1120 return genTypedValue(lf, src_loc, .{
1097 .ty = typed_value.ty.optionalChild(mod),1121 .ty = typed_value.ty.optionalChild(zcu),
1098 .val = typed_value.val.optionalValue(mod) orelse return GenResult.mcv(.{ .immediate = 0 }),1122 .val = typed_value.val.optionalValue(zcu) orelse return GenResult.mcv(.{ .immediate = 0 }),
1099 }, owner_decl_index);1123 }, owner_decl_index);
1100 } else if (typed_value.ty.abiSize(mod) == 1) {1124 } else if (typed_value.ty.abiSize(zcu) == 1) {
1101 return GenResult.mcv(.{ .immediate = @intFromBool(!typed_value.val.isNull(mod)) });1125 return GenResult.mcv(.{ .immediate = @intFromBool(!typed_value.val.isNull(zcu)) });
1102 }1126 }
1103 },1127 },
1104 .Enum => {1128 .Enum => {
1105 const enum_tag = mod.intern_pool.indexToKey(typed_value.val.toIntern()).enum_tag;1129 const enum_tag = zcu.intern_pool.indexToKey(typed_value.val.toIntern()).enum_tag;
1106 const int_tag_ty = mod.intern_pool.typeOf(enum_tag.int);1130 const int_tag_ty = zcu.intern_pool.typeOf(enum_tag.int);
1107 return genTypedValue(bin_file, src_loc, .{1131 return genTypedValue(lf, src_loc, .{
1108 .ty = Type.fromInterned(int_tag_ty),1132 .ty = Type.fromInterned(int_tag_ty),
1109 .val = Value.fromInterned(enum_tag.int),1133 .val = Value.fromInterned(enum_tag.int),
1110 }, owner_decl_index);1134 }, owner_decl_index);
1111 },1135 },
1112 .ErrorSet => {1136 .ErrorSet => {
1113 const err_name = mod.intern_pool.indexToKey(typed_value.val.toIntern()).err.name;1137 const err_name = zcu.intern_pool.indexToKey(typed_value.val.toIntern()).err.name;
1114 const error_index = mod.global_error_set.getIndex(err_name).?;1138 const error_index = zcu.global_error_set.getIndex(err_name).?;
1115 return GenResult.mcv(.{ .immediate = error_index });1139 return GenResult.mcv(.{ .immediate = error_index });
1116 },1140 },
1117 .ErrorUnion => {1141 .ErrorUnion => {
1118 const err_type = typed_value.ty.errorUnionSet(mod);1142 const err_type = typed_value.ty.errorUnionSet(zcu);
1119 const payload_type = typed_value.ty.errorUnionPayload(mod);1143 const payload_type = typed_value.ty.errorUnionPayload(zcu);
1120 if (!payload_type.hasRuntimeBitsIgnoreComptime(mod)) {1144 if (!payload_type.hasRuntimeBitsIgnoreComptime(zcu)) {
1121 // We use the error type directly as the type.1145 // We use the error type directly as the type.
1122 const err_int_ty = try mod.errorIntType();1146 const err_int_ty = try zcu.errorIntType();
1123 switch (mod.intern_pool.indexToKey(typed_value.val.toIntern()).error_union.val) {1147 switch (zcu.intern_pool.indexToKey(typed_value.val.toIntern()).error_union.val) {
1124 .err_name => |err_name| return genTypedValue(bin_file, src_loc, .{1148 .err_name => |err_name| return genTypedValue(lf, src_loc, .{
1125 .ty = err_type,1149 .ty = err_type,
1126 .val = Value.fromInterned((try mod.intern(.{ .err = .{1150 .val = Value.fromInterned((try zcu.intern(.{ .err = .{
1127 .ty = err_type.toIntern(),1151 .ty = err_type.toIntern(),
1128 .name = err_name,1152 .name = err_name,
1129 } }))),1153 } }))),
1130 }, owner_decl_index),1154 }, owner_decl_index),
1131 .payload => return genTypedValue(bin_file, src_loc, .{1155 .payload => return genTypedValue(lf, src_loc, .{
1132 .ty = err_int_ty,1156 .ty = err_int_ty,
1133 .val = try mod.intValue(err_int_ty, 0),1157 .val = try zcu.intValue(err_int_ty, 0),
1134 }, owner_decl_index),1158 }, owner_decl_index),
1135 }1159 }
1136 }1160 }
...@@ -1148,7 +1172,7 @@ pub fn genTypedValue(...@@ -1148,7 +1172,7 @@ pub fn genTypedValue(
1148 else => {},1172 else => {},
1149 }1173 }
11501174
1151 return genUnnamedConst(bin_file, src_loc, typed_value, owner_decl_index);1175 return genUnnamedConst(lf, src_loc, typed_value, owner_decl_index);
1152}1176}
11531177
1154pub fn errUnionPayloadOffset(payload_ty: Type, mod: *Module) u64 {1178pub fn errUnionPayloadOffset(payload_ty: Type, mod: *Module) u64 {
src/link/Dwarf.zig+34-22
...@@ -1192,7 +1192,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde...@@ -1192,7 +1192,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11921192
1193pub fn commitDeclState(1193pub fn commitDeclState(
1194 self: *Dwarf,1194 self: *Dwarf,
1195 mod: *Module,1195 zcu: *Module,
1196 decl_index: InternPool.DeclIndex,1196 decl_index: InternPool.DeclIndex,
1197 sym_addr: u64,1197 sym_addr: u64,
1198 sym_size: u64,1198 sym_size: u64,
...@@ -1202,15 +1202,17 @@ pub fn commitDeclState(...@@ -1202,15 +1202,17 @@ pub fn commitDeclState(
1202 defer tracy.end();1202 defer tracy.end();
12031203
1204 const gpa = self.allocator;1204 const gpa = self.allocator;
1205 const decl = zcu.declPtr(decl_index);
1206 const ip = &zcu.intern_pool;
1207 const namespace = zcu.namespacePtr(decl.src_namespace);
1208 const target = namespace.file_scope.mod.target;
1209 const target_endian = target.cpu.arch.endian();
1210
1205 var dbg_line_buffer = &decl_state.dbg_line;1211 var dbg_line_buffer = &decl_state.dbg_line;
1206 var dbg_info_buffer = &decl_state.dbg_info;1212 var dbg_info_buffer = &decl_state.dbg_info;
1207 const decl = mod.declPtr(decl_index);
1208 const ip = &mod.intern_pool;
1209
1210 const target_endian = self.bin_file.options.target.cpu.arch.endian();
12111213
1212 assert(decl.has_tv);1214 assert(decl.has_tv);
1213 switch (decl.ty.zigTypeTag(mod)) {1215 switch (decl.ty.zigTypeTag(zcu)) {
1214 .Fn => {1216 .Fn => {
1215 try decl_state.setInlineFunc(decl.val.toIntern());1217 try decl_state.setInlineFunc(decl.val.toIntern());
12161218
...@@ -1409,18 +1411,18 @@ pub fn commitDeclState(...@@ -1409,18 +1411,18 @@ pub fn commitDeclState(
1409 if (ip.isErrorSetType(ty.toIntern())) continue;1411 if (ip.isErrorSetType(ty.toIntern())) continue;
14101412
1411 symbol.offset = @intCast(dbg_info_buffer.items.len);1413 symbol.offset = @intCast(dbg_info_buffer.items.len);
1412 try decl_state.addDbgInfoType(mod, di_atom_index, ty);1414 try decl_state.addDbgInfoType(zcu, di_atom_index, ty);
1413 }1415 }
1414 }1416 }
14151417
1416 try self.updateDeclDebugInfoAllocation(di_atom_index, @intCast(dbg_info_buffer.items.len));1418 try self.updateDeclDebugInfoAllocation(di_atom_index, @intCast(dbg_info_buffer.items.len));
14171419
1418 while (decl_state.abbrev_relocs.popOrNull()) |reloc| {1420 while (decl_state.abbrev_relocs.popOrNull()) |reloc| {
1419 if (reloc.target) |target| {1421 if (reloc.target) |reloc_target| {
1420 const symbol = decl_state.abbrev_table.items[target];1422 const symbol = decl_state.abbrev_table.items[reloc_target];
1421 const ty = symbol.type;1423 const ty = symbol.type;
1422 if (ip.isErrorSetType(ty.toIntern())) {1424 if (ip.isErrorSetType(ty.toIntern())) {
1423 log.debug("resolving %{d} deferred until flush", .{target});1425 log.debug("resolving %{d} deferred until flush", .{reloc_target});
1424 try self.global_abbrev_relocs.append(gpa, .{1426 try self.global_abbrev_relocs.append(gpa, .{
1425 .target = null,1427 .target = null,
1426 .offset = reloc.offset,1428 .offset = reloc.offset,
...@@ -1433,8 +1435,8 @@ pub fn commitDeclState(...@@ -1433,8 +1435,8 @@ pub fn commitDeclState(
1433 log.debug("{x}: [() => {x}] (%{d}, '{}')", .{1435 log.debug("{x}: [() => {x}] (%{d}, '{}')", .{
1434 reloc.offset,1436 reloc.offset,
1435 value,1437 value,
1436 target,1438 reloc_target,
1437 ty.fmt(mod),1439 ty.fmt(zcu),
1438 });1440 });
1439 mem.writeInt(1441 mem.writeInt(
1440 u32,1442 u32,
...@@ -1897,7 +1899,7 @@ fn dbgInfoHeaderBytes(self: *Dwarf) usize {...@@ -1897,7 +1899,7 @@ fn dbgInfoHeaderBytes(self: *Dwarf) usize {
1897 return 120;1899 return 120;
1898}1900}
18991901
1900pub fn writeDbgInfoHeader(self: *Dwarf, module: *Module, low_pc: u64, high_pc: u64) !void {1902pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64) !void {
1901 // If this value is null it means there is an error in the module;1903 // If this value is null it means there is an error in the module;
1902 // leave debug_info_header_dirty=true.1904 // leave debug_info_header_dirty=true.
1903 const first_dbg_info_off = self.getDebugInfoOff() orelse return;1905 const first_dbg_info_off = self.getDebugInfoOff() orelse return;
...@@ -1908,7 +1910,9 @@ pub fn writeDbgInfoHeader(self: *Dwarf, module: *Module, low_pc: u64, high_pc: u...@@ -1908,7 +1910,9 @@ pub fn writeDbgInfoHeader(self: *Dwarf, module: *Module, low_pc: u64, high_pc: u
1908 var di_buf = try std.ArrayList(u8).initCapacity(self.allocator, needed_bytes);1910 var di_buf = try std.ArrayList(u8).initCapacity(self.allocator, needed_bytes);
1909 defer di_buf.deinit();1911 defer di_buf.deinit();
19101912
1911 const target_endian = self.bin_file.options.target.cpu.arch.endian();1913 const comp = self.bin_file.comp;
1914 const target = comp.root_mod.resolved_target.result;
1915 const target_endian = target.cpu.arch.endian();
1912 const init_len_size: usize = switch (self.format) {1916 const init_len_size: usize = switch (self.format) {
1913 .dwarf32 => 4,1917 .dwarf32 => 4,
1914 .dwarf64 => 12,1918 .dwarf64 => 12,
...@@ -1931,9 +1935,9 @@ pub fn writeDbgInfoHeader(self: *Dwarf, module: *Module, low_pc: u64, high_pc: u...@@ -1931,9 +1935,9 @@ pub fn writeDbgInfoHeader(self: *Dwarf, module: *Module, low_pc: u64, high_pc: u
1931 di_buf.appendAssumeCapacity(self.ptrWidthBytes()); // address size1935 di_buf.appendAssumeCapacity(self.ptrWidthBytes()); // address size
19321936
1933 // Write the form for the compile unit, which must match the abbrev table above.1937 // Write the form for the compile unit, which must match the abbrev table above.
1934 const name_strp = try self.strtab.insert(self.allocator, module.root_mod.root_src_path);1938 const name_strp = try self.strtab.insert(self.allocator, zcu.root_mod.root_src_path);
1935 var compile_unit_dir_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;1939 var compile_unit_dir_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
1936 const compile_unit_dir = resolveCompilationDir(module, &compile_unit_dir_buffer);1940 const compile_unit_dir = resolveCompilationDir(zcu, &compile_unit_dir_buffer);
1937 const comp_dir_strp = try self.strtab.insert(self.allocator, compile_unit_dir);1941 const comp_dir_strp = try self.strtab.insert(self.allocator, compile_unit_dir);
1938 const producer_strp = try self.strtab.insert(self.allocator, link.producer_string);1942 const producer_strp = try self.strtab.insert(self.allocator, link.producer_string);
19391943
...@@ -1997,7 +2001,9 @@ fn resolveCompilationDir(module: *Module, buffer: *[std.fs.MAX_PATH_BYTES]u8) []...@@ -1997,7 +2001,9 @@ fn resolveCompilationDir(module: *Module, buffer: *[std.fs.MAX_PATH_BYTES]u8) []
1997}2001}
19982002
1999fn writeAddrAssumeCapacity(self: *Dwarf, buf: *std.ArrayList(u8), addr: u64) void {2003fn writeAddrAssumeCapacity(self: *Dwarf, buf: *std.ArrayList(u8), addr: u64) void {
2000 const target_endian = self.bin_file.options.target.cpu.arch.endian();2004 const comp = self.bin_file.comp;
2005 const target = comp.root_mod.resolved_target.result;
2006 const target_endian = target.cpu.arch.endian();
2001 switch (self.ptr_width) {2007 switch (self.ptr_width) {
2002 .p32 => mem.writeInt(u32, buf.addManyAsArrayAssumeCapacity(4), @intCast(addr), target_endian),2008 .p32 => mem.writeInt(u32, buf.addManyAsArrayAssumeCapacity(4), @intCast(addr), target_endian),
2003 .p64 => mem.writeInt(u64, buf.addManyAsArrayAssumeCapacity(8), addr, target_endian),2009 .p64 => mem.writeInt(u64, buf.addManyAsArrayAssumeCapacity(8), addr, target_endian),
...@@ -2005,7 +2011,9 @@ fn writeAddrAssumeCapacity(self: *Dwarf, buf: *std.ArrayList(u8), addr: u64) voi...@@ -2005,7 +2011,9 @@ fn writeAddrAssumeCapacity(self: *Dwarf, buf: *std.ArrayList(u8), addr: u64) voi
2005}2011}
20062012
2007fn writeOffsetAssumeCapacity(self: *Dwarf, buf: *std.ArrayList(u8), off: u64) void {2013fn writeOffsetAssumeCapacity(self: *Dwarf, buf: *std.ArrayList(u8), off: u64) void {
2008 const target_endian = self.bin_file.options.target.cpu.arch.endian();2014 const comp = self.bin_file.comp;
2015 const target = comp.root_mod.resolved_target.result;
2016 const target_endian = target.cpu.arch.endian();
2009 switch (self.format) {2017 switch (self.format) {
2010 .dwarf32 => mem.writeInt(u32, buf.addManyAsArrayAssumeCapacity(4), @intCast(off), target_endian),2018 .dwarf32 => mem.writeInt(u32, buf.addManyAsArrayAssumeCapacity(4), @intCast(off), target_endian),
2011 .dwarf64 => mem.writeInt(u64, buf.addManyAsArrayAssumeCapacity(8), off, target_endian),2019 .dwarf64 => mem.writeInt(u64, buf.addManyAsArrayAssumeCapacity(8), off, target_endian),
...@@ -2227,7 +2235,9 @@ fn writeDbgInfoNopsToArrayList(...@@ -2227,7 +2235,9 @@ fn writeDbgInfoNopsToArrayList(
2227}2235}
22282236
2229pub fn writeDbgAranges(self: *Dwarf, addr: u64, size: u64) !void {2237pub fn writeDbgAranges(self: *Dwarf, addr: u64, size: u64) !void {
2230 const target_endian = self.bin_file.options.target.cpu.arch.endian();2238 const comp = self.bin_file.comp;
2239 const target = comp.root_mod.resolved_target.result;
2240 const target_endian = target.cpu.arch.endian();
2231 const ptr_width_bytes = self.ptrWidthBytes();2241 const ptr_width_bytes = self.ptrWidthBytes();
22322242
2233 // Enough for all the data without resizing. When support for more compilation units2243 // Enough for all the data without resizing. When support for more compilation units
...@@ -2299,9 +2309,10 @@ pub fn writeDbgAranges(self: *Dwarf, addr: u64, size: u64) !void {...@@ -2299,9 +2309,10 @@ pub fn writeDbgAranges(self: *Dwarf, addr: u64, size: u64) !void {
2299}2309}
23002310
2301pub fn writeDbgLineHeader(self: *Dwarf) !void {2311pub fn writeDbgLineHeader(self: *Dwarf) !void {
2312 const comp = self.bin_file.comp;
2302 const gpa = self.allocator;2313 const gpa = self.allocator;
23032314 const target = comp.root_mod.resolved_target.result;
2304 const target_endian = self.bin_file.options.target.cpu.arch.endian();2315 const target_endian = target.cpu.arch.endian();
2305 const init_len_size: usize = switch (self.format) {2316 const init_len_size: usize = switch (self.format) {
2306 .dwarf32 => 4,2317 .dwarf32 => 4,
2307 .dwarf64 => 12,2318 .dwarf64 => 12,
...@@ -2565,7 +2576,8 @@ fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {...@@ -2565,7 +2576,8 @@ fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
2565}2576}
25662577
2567pub fn flushModule(self: *Dwarf, module: *Module) !void {2578pub fn flushModule(self: *Dwarf, module: *Module) !void {
2568 const target = self.bin_file.options.target;2579 const comp = self.bin_file.comp;
2580 const target = comp.root_mod.resolved_target.result;
25692581
2570 if (self.global_abbrev_relocs.items.len > 0) {2582 if (self.global_abbrev_relocs.items.len > 0) {
2571 const gpa = self.allocator;2583 const gpa = self.allocator;