From ebce4c9f21bddfeae475fe537ce015752df1bdee Mon Sep 17 00:00:00 2001 From: Matthew Lugg Date: Fri, 6 Nov 2026 11:11:47 +0000 Subject: [PATCH] llvm: refactor `llvm.Object.emit` to free `llvm.Object` before LLVM emit This is a refactor which I've kind of been thinking of doing for a while anyway. The LLVM backend, which emits LLVM bitcode, is now clearly separated from the libllvm API calls, which process that bitcode into an optimized IR/bitcode file, an assembly file, and/or an object file. The main benefit of this change right now is that in non-incremental compilations which use LLVM, we can now free the `llvm.Object` state after generating bitcode and before calling into libllvm, which can significantly decrease the peak RSS of such compilations. Co-authored-by: Guy Fischman --- src/Compilation.zig | 98 +++-- src/Zcu.zig | 22 +- src/codegen/llvm.zig | 488 ++---------------------- src/codegen/llvm/lib.zig | 416 ++++++++++++++++++++ src/codegen/llvm/{ => lib}/bindings.zig | 0 src/link/Lld.zig | 15 +- src/link/MachO.zig | 4 +- src/main.zig | 12 +- 8 files changed, 566 insertions(+), 489 deletions(-) create mode 100644 src/codegen/llvm/lib.zig rename src/codegen/llvm/{ => lib}/bindings.zig (100%) diff --git a/src/Compilation.zig b/src/Compilation.zig index e9fcf3b953..c40c78db1e 100644 --- a/src/Compilation.zig +++ b/src/Compilation.zig @@ -38,9 +38,10 @@ const c_codegen = @import("codegen/c.zig"); const libtsan = @import("libs/libtsan.zig"); const Zir = std.zig.Zir; const Builtin = @import("Builtin.zig"); -const LlvmObject = @import("codegen/llvm.zig").Object; const dev = @import("dev.zig"); const Module = @import("Module.zig"); +const libllvm = @import("codegen/llvm/lib.zig"); +const debugLogScopeEnabled = @import("main.zig").debugLogScopeEnabled; pub const Config = @import("Compilation/Config.zig"); @@ -2005,6 +2006,7 @@ pub fn create(gpa: Allocator, arena: Allocator, io: Io, diag: *CreateDiagnostic, .gpa = gpa, .comp = comp, .llvm_object = null, + .llvm_object_basename = null, .root_mod = options.root_mod, .main_mod = main_mod, @@ -3227,12 +3229,55 @@ pub fn resolveEmitPathFlush( fn flush(comp: *Compilation, arena: Allocator) (Io.Cancelable || Allocator.Error)!void { const io = comp.io; + const gpa = comp.gpa; const tid: Zcu.PerThread.Id = .acquire(io); defer tid.release(io); if (comp.zcu) |zcu| { if (zcu.llvm_object) |llvm_object| { - // Emit the ZCU object from LLVM now; it's required to flush the output file. - // If there's an output file, it wants to decide where the LLVM object goes! + const want_libllvm_emit: bool = + zcu.llvm_object_basename != null or + comp.emit_asm != null or + comp.emit_llvm_ir != null or + comp.emit_llvm_bc != null or + debugLogScopeEnabled("opt-llvm-ir"); + + // `var` so that we can set it to `&.{}` later if we free the bitcode early. + var llvm_bitcode: []const u32 = bitcode: { + const active = zcu.activate(tid); + defer active.deactivate(); + break :bitcode llvm_object.flush(active.pt, .{ + .ir_out_path = if (comp.getTarget().ofmt == .llvmir) comp.bin_file.?.emit else null, + .bc_out_path = if (comp.getTarget().ofmt == .llvmbc) comp.bin_file.?.emit else null, + .want_bitcode = want_libllvm_emit, + }) catch |err| switch (err) { + error.AlreadyReported => return, + else => |e| return e, + }; + }; + defer gpa.free(llvm_bitcode); + + const llvm_triple: [:0]u8 = triple: { + const slice = llvm_object.builder.target_triple.slice(&llvm_object.builder).?; + break :triple try gpa.dupeSentinel(u8, slice, 0); + }; + defer gpa.free(llvm_triple); + + // At this point we've emitted the IR/bitcode, so unless we're using incremental (where + // we need to preserve state for future updates), we are allowed to free `llvm_object`. + // We want to do this if possible because it can sometimes significantly reduce peak RSS + // during LLVM emit. + if (!comp.config.incremental) { + llvm_object.deinit(); + zcu.llvm_object = null; + } + + if (!want_libllvm_emit) return; + + if (!build_options.have_llvm or !comp.config.use_lib_llvm) { + comp.link_diags.addError("emitting without libllvm not implemented", .{}); + return; + } + const sub_prog_node = comp.link_prog_node.start("LLVM Emit Object", 0); defer sub_prog_node.end(); @@ -3243,18 +3288,30 @@ fn flush(comp: *Compilation, arena: Allocator) (Io.Cancelable || Allocator.Error comp.time_report.?.stats.real_ns_llvm_emit = ns; }; - const zcu_obj_path: ?Cache.Path = switch (comp.getTarget().ofmt) { - .llvmbc, .llvmir => null, - else => if (comp.bin_file != null) - try comp.resolveEmitPathFlush(arena, .temp, llvm_object.out_bin_basename) - else - null, + const llvm_context, const llvm_module = libllvm.loadGeneratedBitcode( + comp, + llvm_bitcode, + ) catch |err| switch (err) { + error.AlreadyReported => return, + else => |e| return e, }; + defer llvm_context.dispose(); - const active = zcu.activate(tid); - defer active.deactivate(); - llvm_object.emit(active.pt, .{ - .bin_path = if (zcu_obj_path) |p| try p.toStringZ(arena) else null, + // At this point we're done with the raw bitcode, so free it now. Like before, we are + // doing this to minimize peak RSS during LLVM emit. + gpa.free(llvm_bitcode); + llvm_bitcode = &.{}; + + const zcu_obj_path: ?Cache.Path = if (zcu.llvm_object_basename) |basename| path: { + break :path try comp.resolveEmitPathFlush(arena, .temp, basename); + } else null; + + libllvm.emit(comp, llvm_context, llvm_module, .{ + .llvm_triple = llvm_triple, + .bin_path = p: { + const p = zcu_obj_path orelse break :p null; + break :p try p.toStringZ(arena); + }, .asm_path = p: { const raw = comp.emit_asm orelse break :p null; const p = try comp.resolveEmitPathFlush(arena, .artifact, raw); @@ -3270,16 +3327,9 @@ fn flush(comp: *Compilation, arena: Allocator) (Io.Cancelable || Allocator.Error const p = try comp.resolveEmitPathFlush(arena, .artifact, raw); break :p try p.toStringZ(arena); }, - - .is_debug = comp.root_mod.optimize_mode == .debug, - .is_small = comp.root_mod.optimize_mode == .small, - .time_report = if (comp.time_report) |*p| p else null, - .sanitize_thread = comp.config.any_sanitize_thread, - .fuzz = comp.config.any_fuzz, - .lto = comp.config.lto, }) catch |err| switch (err) { - error.Canceled, error.OutOfMemory => |e| return e, - error.AlreadyReported => {}, + error.AlreadyReported => return, + else => |e| return e, }; if (zcu_obj_path) |path| { @@ -3291,7 +3341,9 @@ fn flush(comp: *Compilation, arena: Allocator) (Io.Cancelable || Allocator.Error error.Canceled, error.OutOfMemory => |e| return e, error.AlreadyReported => return, }; - } else return; + } else { + return; + } } } if (comp.bin_file) |lf| { diff --git a/src/Zcu.zig b/src/Zcu.zig index f2b0b52709..b76fb45c71 100644 --- a/src/Zcu.zig +++ b/src/Zcu.zig @@ -63,6 +63,12 @@ comp: *Compilation, /// If the ZCU is emitting an LLVM object (i.e. we are using the LLVM backend), then this is the /// `LlvmObject` we are emitting to. llvm_object: ?LlvmObject.Ptr, +/// The basename of the object file which will be emitted by LLVM for the ZCU. Once it is emitted, +/// this object file is passed to the active linker implementation as an ordinary link input. +/// Not part of `llvm_object` because that may have been destroyed by the time the linker runs. +/// +/// For the full path, use `Compilation.resolveEmitPath` with `kind == .temp`. +llvm_object_basename: ?[]const u8, /// Pointer to externally managed resource. root_mod: *Module, @@ -3012,7 +3018,21 @@ pub fn reset(zcu: *Zcu, arena: Allocator) Allocator.Error!void { })) { dev.check(.llvm_backend); - zcu.llvm_object = try .create(if (comp.config.incremental) comp.arena else arena, zcu); + const llvm_arena = if (comp.config.incremental) comp.arena else arena; + zcu.llvm_object = try .create(llvm_arena, zcu); + + const target = zcu.getTarget(); + if (comp.emit_bin != null) switch (target.ofmt) { + .llvmbc, .llvmir => {}, + else => zcu.llvm_object_basename = try std.zig.binNameAlloc(llvm_arena, .{ + .root_name = try std.fmt.allocPrint(llvm_arena, "{s}_zcu", .{comp.root_name}), + .cpu_arch = target.cpu.arch, + .os_tag = target.os.tag, + .ofmt = target.ofmt, + .abi = target.abi, + .output_mode = .Obj, + }), + }; } } diff --git a/src/codegen/llvm.zig b/src/codegen/llvm.zig index 2e1729068b..61a55a36be 100644 --- a/src/codegen/llvm.zig +++ b/src/codegen/llvm.zig @@ -10,7 +10,6 @@ const build_options = @import("build_options"); const Air = @import("../Air.zig"); const codegen = @import("../codegen.zig"); const Compilation = @import("../Compilation.zig"); -const debugLogScopeEnabled = @import("../main.zig").debugLogScopeEnabled; const InternPool = @import("../InternPool.zig"); const link = @import("../link.zig"); const Module = @import("../Module.zig"); @@ -26,10 +25,6 @@ const iterateParamTypes = FuncGen.iterateParamTypes; const ccAbiPromoteInt = FuncGen.ccAbiPromoteInt; const log = std.log.scoped(.codegen); -const bindings = if (build_options.have_llvm) - @import("llvm/bindings.zig") -else - @compileError("LLVM unavailable"); pub fn legalizeFeatures(target: *const std.Target) ?*const Air.Legalize.Features { return switch (target.cpu.arch.endian()) { @@ -56,7 +51,6 @@ pub fn supportsTailCall(target: *const std.Target) bool { }; } -// Avoid depending on `bindings.CodeModel` in the bitcode-only case. const CodeModel = enum { default, tiny, @@ -66,7 +60,7 @@ const CodeModel = enum { large, }; -fn codeModel(model: std.lang.CodeModel, target: *const std.Target) CodeModel { +pub fn codeModel(model: std.lang.CodeModel, target: *const std.Target) CodeModel { // Roughly match Clang's mapping of GCC code models to LLVM code models. return switch (model) { .default => .default, @@ -84,12 +78,6 @@ pub const Object = struct { gpa: Allocator, builder: Builder, - /// The basename of the object file which will emitted by LLVM for the ZCU. Once it it emitted, - /// this object file is passed to the active linker implementation as an ordinary link input. - /// - /// For the full path, use `Compilation.resolveEmitPath` with `kind == .temp`. - out_bin_basename: []const u8, - /// This pool contains only types (and not `@as(type, undefined)`). It has two purposes: /// /// * Lazily tracking ABI alignment of types, so that `@"align"` attributes can be set to a @@ -226,14 +214,6 @@ pub const Object = struct { obj.* = .{ .gpa = gpa, .builder = builder, - .out_bin_basename = try std.zig.binNameAlloc(arena, .{ - .root_name = try std.fmt.allocPrint(arena, "{s}_zcu", .{comp.root_name}), - .cpu_arch = target.cpu.arch, - .os_tag = target.os.tag, - .ofmt = target.ofmt, - .abi = target.abi, - .output_mode = .Obj, - }), .type_pool = .empty, .lazy_abi_aligns = .empty, .debug_compile_unit = debug_compile_unit, @@ -331,23 +311,17 @@ pub const Object = struct { } } - pub const EmitOptions = struct { - bin_path: ?[:0]const u8, - asm_path: ?[:0]const u8, - opt_ir_path: ?[:0]const u8, - opt_bc_path: ?[:0]const u8, - - is_debug: bool, - is_small: bool, - time_report: ?*Compilation.TimeReport, - sanitize_thread: bool, - fuzz: bool, - lto: std.zig.LtoMode, + pub const FlushOptions = struct { + ir_out_path: ?std.Build.Cache.Path, + bc_out_path: ?std.Build.Cache.Path, + want_bitcode: bool, }; - - pub fn emit(o: *Object, pt: Zcu.PerThread, options: EmitOptions) link.Error!void { + /// Returns `&.{}` if `options.want_bitcode` is `false`. Otherwise, the returned bitcode slice + /// is owned by the caller and is allocated using `o.zcu.comp.gpa`. + pub fn flush(o: *Object, pt: Zcu.PerThread, options: FlushOptions) link.Error![]const u32 { const zcu = o.zcu; const comp = zcu.comp; + const gpa = o.gpa; const io = comp.io; const diags = &comp.link_diags; const target = &comp.root_mod.resolved_target.result; @@ -509,216 +483,41 @@ pub const Object = struct { try o.builder.addNamedMetadata(try o.builder.string("llvm.module.flags"), module_flags.items); } - const target_triple_sentinel = - try o.gpa.dupeSentinel(u8, o.builder.target_triple.slice(&o.builder).?, 0); - defer o.gpa.free(target_triple_sentinel); + { + var p: Builder.Print = .{ .name = comp.root_name, .builder = &o.builder, .err = null }; + std.log.scoped(.@"llvm-ir").debug("{f}", .{&p}); + if (p.err) |err| return err; + } - const emit_asm_msg = options.asm_path orelse "(none)"; - const emit_bin_msg = options.bin_path orelse "(none)"; - const opt_llvm_ir_msg = options.opt_ir_path orelse "(none)"; - const opt_llvm_bc_msg = options.opt_bc_path orelse "(none)"; - log.debug("emit LLVM object asm={s} bin={s} ir={s} bc={s}", .{ - emit_asm_msg, emit_bin_msg, opt_llvm_ir_msg, opt_llvm_bc_msg, + if (options.ir_out_path) |path| { + o.builder.printToFilePath(io, path.root_dir.handle, path.sub_path) catch |err| { + return diags.fail("failed emitting LLVM module to {qf}: {t}", .{ path, err }); + }; + } + + if (!options.want_bitcode and options.bc_out_path == null) { + return &.{}; + } + + const bitcode = try o.builder.toBitcode(gpa, .{ + .name = "zig", + .version = build_options.semver, }); - const log_opt_llvm_ir = debugLogScopeEnabled("opt-llvm-ir"); + errdefer gpa.free(bitcode); - const context, const module = emit: { - { - var p: Builder.Print = .{ .name = comp.root_name, .builder = &o.builder, .err = null }; - std.log.scoped(.@"llvm-ir").debug("{f}", .{&p}); - if (p.err) |err| return err; - } - - if (target.ofmt == .llvmir) { - const path = comp.bin_file.?.emit; - o.builder.printToFilePath(io, path.root_dir.handle, path.sub_path) catch |err| { - return diags.fail("failed emitting LLVM module to {qf}: {t}", .{ path, err }); - }; - return; - } - - const bitcode = try o.builder.toBitcode(o.gpa, .{ - .name = "zig", - .version = build_options.semver, - }); - defer o.gpa.free(bitcode); - - if (target.ofmt == .llvmbc) { - const path = comp.bin_file.?.emit; - var file = path.root_dir.handle.createFile(io, path.sub_path, .{}) catch |err| - return diags.fail("failed to create {qf}: {t}", .{ path, err }); - defer file.close(io); - - file.writeStreamingAll(io, @ptrCast(bitcode)) catch |err| - return diags.fail("failed to write to {qf}: {t}", .{ path, err }); - return; - } - - if (options.asm_path == null and options.bin_path == null and - options.opt_ir_path == null and options.opt_bc_path == null and - !log_opt_llvm_ir) return; - - if (!build_options.have_llvm or !comp.config.use_lib_llvm) { - return diags.fail("emitting without libllvm not implemented", .{}); - } - - initializeLLVMTarget(io, target.cpu.arch); - - const context: *bindings.Context = .create(); - errdefer context.dispose(); - - const bitcode_memory_buffer = bindings.MemoryBuffer.createMemoryBufferWithMemoryRange( - @ptrCast(bitcode.ptr), - bitcode.len * 4, - "BitcodeBuffer", - bindings.Bool.False, - ); - defer bitcode_memory_buffer.dispose(); - - context.enableBrokenDebugInfoCheck(); - - var module: *bindings.Module = undefined; - if (context.parseBitcodeInContext2(bitcode_memory_buffer, &module).toBool() or context.getBrokenDebugInfo()) { - return diags.fail("Failed to parse bitcode", .{}); - } - break :emit .{ context, module }; - }; - defer context.dispose(); - - var llvm_target: *bindings.Target = undefined; - var error_message: [*:0]const u8 = undefined; - if (bindings.Target.getFromTriple(target_triple_sentinel, &llvm_target, &error_message).toBool()) { - defer bindings.disposeMessage(error_message); - return diags.fail("LLVM failed to parse '{s}': {s}", .{ target_triple_sentinel, error_message }); + if (options.bc_out_path) |path| { + var file = path.root_dir.handle.createFile(io, path.sub_path, .{}) catch |err| + return diags.fail("failed to create {qf}: {t}", .{ path, err }); + defer file.close(io); + file.writeStreamingAll(io, @ptrCast(bitcode)) catch |err| + return diags.fail("failed to write to {qf}: {t}", .{ path, err }); } - const optimize_mode = comp.root_mod.optimize_mode; - - const opt_level: bindings.CodeGenOptLevel = if (optimize_mode == .debug) - .None - else - .Aggressive; - - const reloc_mode: bindings.RelocMode = if (comp.config.pic) - .PIC - else if (comp.config.link_mode == .dynamic) - bindings.RelocMode.DynamicNoPIC - else - .Static; - - const code_model: bindings.CodeModel = switch (codeModel(comp.root_mod.code_model, target)) { - .default => .Default, - .tiny => .Tiny, - .small => .Small, - .kernel => .Kernel, - .medium => .Medium, - .large => .Large, - }; - - var target_machine = bindings.TargetMachine.create( - llvm_target, - target_triple_sentinel, - if (target.cpu.model.llvm_name) |s| s.ptr else null, - comp.root_mod.llvm_cpu_features.?, - opt_level, - reloc_mode, - code_model, - comp.config.function_sections, - comp.config.data_sections, - switch (target.abi.float()) { - .hard => .Hard, - .soft => .Soft, - }, - if (target_util.llvmMachineAbi(target)) |s| s.ptr else null, - target_util.useEmulatedTls(target), - ); - errdefer target_machine.dispose(); - - if (comp.llvm_opt_bisect_limit >= 0) { - context.setOptBisectLimit(comp.llvm_opt_bisect_limit); - } - - // Unfortunately, LLVM shits the bed when we ask for both binary and assembly. - // So we call the entire pipeline multiple times if this is requested. - var time_report_c_str: ?[*:0]u8 = null; - defer if (time_report_c_str) |time_report| bindings.disposeMessage(time_report); - var llvm_ir_c_str: ?[*:0]u8 = null; - defer if (llvm_ir_c_str) |llvm_ir| bindings.disposeMessage(llvm_ir); - var lowered_options: bindings.TargetMachine.EmitOptions = .{ - .is_debug = options.is_debug, - .is_small = options.is_small, - .time_report_out = null, // set below to make sure it's only set for a single `emitToFile` - .tsan = options.sanitize_thread, - .lto = switch (options.lto) { - .none => .None, - .thin => .ThinPreLink, - .full => .FullPreLink, - }, - .allow_fast_isel = true, - // LLVM's RISC-V backend for some reason enables the machine outliner by default even - // though it's clearly not ready and produces multiple miscompilations in our std tests. - .allow_machine_outliner = !target.cpu.arch.isRiscv(), - .asm_filename = null, - .bin_filename = if (options.bin_path) |x| x.ptr else null, - .llvm_ir_filename = if (options.opt_ir_path) |x| x.ptr else null, - .bitcode_filename = if (options.opt_bc_path) |x| x.ptr else null, - .llvm_ir_out = if (log_opt_llvm_ir) &llvm_ir_c_str else null, - - // `.coverage` value is only used when `.sancov` is enabled. - .sancov = options.fuzz or comp.config.san_cov_trace_pc_guard, - .coverage = .{ - .CoverageType = .Edge, - // Works in tandem with Inline8bitCounters or InlineBoolFlag. - // Zig does not yet implement its own version of this but it - // needs to for better fuzzing logic. - .IndirectCalls = false, - .TraceBB = false, - .TraceCmp = false, - .TraceDiv = false, - .TraceGep = false, - .Use8bitCounters = false, - .TracePC = false, - .TracePCGuard = comp.config.san_cov_trace_pc_guard, - // Zig emits its own inline 8-bit counters instrumentation. - .Inline8bitCounters = false, - .InlineBoolFlag = false, - // Zig emits its own PC table instrumentation. - .PCTable = false, - .NoPrune = false, - // Workaround for https://github.com/llvm/llvm-project/pull/106464 - .StackDepth = true, - .TraceLoads = false, - .TraceStores = false, - .CollectControlFlow = false, - }, - }; - if (options.asm_path != null and options.bin_path != null) { - if (target_machine.emitToFile(module, &error_message, &lowered_options)) { - return diags.fail("LLVM failed to emit bin={s} ir={s}: {s}", .{ - emit_bin_msg, opt_llvm_ir_msg, error_message, - }); - } - lowered_options.bin_filename = null; - lowered_options.llvm_ir_filename = null; - lowered_options.bitcode_filename = null; - lowered_options.llvm_ir_out = null; - } - if (options.time_report) |_| lowered_options.time_report_out = &time_report_c_str; - lowered_options.asm_filename = if (options.asm_path) |x| x.ptr else null; - if (target_machine.emitToFile(module, &error_message, &lowered_options)) { - defer bindings.disposeMessage(error_message); - return diags.fail("LLVM failed to emit asm={s} bin={s} ir={s} bc={s}: {s}", .{ - emit_asm_msg, emit_bin_msg, opt_llvm_ir_msg, opt_llvm_bc_msg, error_message, - }); - } - if (log_opt_llvm_ir) std.log.scoped(.@"opt-llvm-ir").debug("{s}", .{ - llvm_ir_c_str orelse return error.OutOfMemory, - }); - if (options.time_report) |time_report| { - assert(time_report.llvm_pass_timings.len == 0); - time_report.llvm_pass_timings = try comp.gpa.dupe(u8, std.mem.span( - time_report_c_str orelse return error.OutOfMemory, - )); + if (options.want_bitcode) { + return bitcode; + } else { + gpa.free(bitcode); + return &.{}; } } @@ -4607,212 +4406,3 @@ const struct_layout_version = 2; // TODO: Restore the non_null field to i1 once // https://github.com/llvm/llvm-project/issues/56585/ is fixed pub const optional_layout_version = 3; - -var target_registry_mutex: std.Io.Mutex = .init; - -pub fn initializeLLVMTarget(io: Io, arch: std.Target.Cpu.Arch) void { - // Repeated initialization is safe, as targets which have already been registered will be skipped. - // It is however the client's responsibility to synchronize registry access. - target_registry_mutex.lockUncancelable(io); - defer target_registry_mutex.unlock(io); - - switch (arch) { - .aarch64, .aarch64_be => { - bindings.LLVMInitializeAArch64Target(); - bindings.LLVMInitializeAArch64TargetInfo(); - bindings.LLVMInitializeAArch64TargetMC(); - bindings.LLVMInitializeAArch64AsmPrinter(); - bindings.LLVMInitializeAArch64AsmParser(); - }, - .amdgcn => { - bindings.LLVMInitializeAMDGPUTarget(); - bindings.LLVMInitializeAMDGPUTargetInfo(); - bindings.LLVMInitializeAMDGPUTargetMC(); - bindings.LLVMInitializeAMDGPUAsmPrinter(); - bindings.LLVMInitializeAMDGPUAsmParser(); - }, - .thumb, .thumbeb, .arm, .armeb => { - bindings.LLVMInitializeARMTarget(); - bindings.LLVMInitializeARMTargetInfo(); - bindings.LLVMInitializeARMTargetMC(); - bindings.LLVMInitializeARMAsmPrinter(); - bindings.LLVMInitializeARMAsmParser(); - }, - .avr => { - bindings.LLVMInitializeAVRTarget(); - bindings.LLVMInitializeAVRTargetInfo(); - bindings.LLVMInitializeAVRTargetMC(); - bindings.LLVMInitializeAVRAsmPrinter(); - bindings.LLVMInitializeAVRAsmParser(); - }, - .bpfel, .bpfeb => { - bindings.LLVMInitializeBPFTarget(); - bindings.LLVMInitializeBPFTargetInfo(); - bindings.LLVMInitializeBPFTargetMC(); - bindings.LLVMInitializeBPFAsmPrinter(); - bindings.LLVMInitializeBPFAsmParser(); - }, - .hexagon => { - bindings.LLVMInitializeHexagonTarget(); - bindings.LLVMInitializeHexagonTargetInfo(); - bindings.LLVMInitializeHexagonTargetMC(); - bindings.LLVMInitializeHexagonAsmPrinter(); - bindings.LLVMInitializeHexagonAsmParser(); - }, - .lanai => { - bindings.LLVMInitializeLanaiTarget(); - bindings.LLVMInitializeLanaiTargetInfo(); - bindings.LLVMInitializeLanaiTargetMC(); - bindings.LLVMInitializeLanaiAsmPrinter(); - bindings.LLVMInitializeLanaiAsmParser(); - }, - .mips, .mipsel, .mips64, .mips64el => { - bindings.LLVMInitializeMipsTarget(); - bindings.LLVMInitializeMipsTargetInfo(); - bindings.LLVMInitializeMipsTargetMC(); - bindings.LLVMInitializeMipsAsmPrinter(); - bindings.LLVMInitializeMipsAsmParser(); - }, - .msp430 => { - bindings.LLVMInitializeMSP430Target(); - bindings.LLVMInitializeMSP430TargetInfo(); - bindings.LLVMInitializeMSP430TargetMC(); - bindings.LLVMInitializeMSP430AsmPrinter(); - bindings.LLVMInitializeMSP430AsmParser(); - }, - .nvptx, .nvptx64 => { - bindings.LLVMInitializeNVPTXTarget(); - bindings.LLVMInitializeNVPTXTargetInfo(); - bindings.LLVMInitializeNVPTXTargetMC(); - bindings.LLVMInitializeNVPTXAsmPrinter(); - // There is no LLVMInitializeNVPTXAsmParser function available. - }, - .powerpc, .powerpcle, .powerpc64, .powerpc64le => { - bindings.LLVMInitializePowerPCTarget(); - bindings.LLVMInitializePowerPCTargetInfo(); - bindings.LLVMInitializePowerPCTargetMC(); - bindings.LLVMInitializePowerPCAsmPrinter(); - bindings.LLVMInitializePowerPCAsmParser(); - }, - .riscv32, .riscv32be, .riscv64, .riscv64be => { - bindings.LLVMInitializeRISCVTarget(); - bindings.LLVMInitializeRISCVTargetInfo(); - bindings.LLVMInitializeRISCVTargetMC(); - bindings.LLVMInitializeRISCVAsmPrinter(); - bindings.LLVMInitializeRISCVAsmParser(); - }, - .sparc, .sparc64 => { - bindings.LLVMInitializeSparcTarget(); - bindings.LLVMInitializeSparcTargetInfo(); - bindings.LLVMInitializeSparcTargetMC(); - bindings.LLVMInitializeSparcAsmPrinter(); - bindings.LLVMInitializeSparcAsmParser(); - }, - .s390x => { - bindings.LLVMInitializeSystemZTarget(); - bindings.LLVMInitializeSystemZTargetInfo(); - bindings.LLVMInitializeSystemZTargetMC(); - bindings.LLVMInitializeSystemZAsmPrinter(); - bindings.LLVMInitializeSystemZAsmParser(); - }, - .wasm32, .wasm64 => { - bindings.LLVMInitializeWebAssemblyTarget(); - bindings.LLVMInitializeWebAssemblyTargetInfo(); - bindings.LLVMInitializeWebAssemblyTargetMC(); - bindings.LLVMInitializeWebAssemblyAsmPrinter(); - bindings.LLVMInitializeWebAssemblyAsmParser(); - }, - .x86, .x86c16, .x86_64 => { - bindings.LLVMInitializeX86Target(); - bindings.LLVMInitializeX86TargetInfo(); - bindings.LLVMInitializeX86TargetMC(); - bindings.LLVMInitializeX86AsmPrinter(); - bindings.LLVMInitializeX86AsmParser(); - }, - .xtensa => { - if (build_options.llvm_has_xtensa) { - bindings.LLVMInitializeXtensaTarget(); - bindings.LLVMInitializeXtensaTargetInfo(); - bindings.LLVMInitializeXtensaTargetMC(); - bindings.LLVMInitializeXtensaAsmPrinter(); - bindings.LLVMInitializeXtensaAsmParser(); - } - }, - .xcore => { - bindings.LLVMInitializeXCoreTarget(); - bindings.LLVMInitializeXCoreTargetInfo(); - bindings.LLVMInitializeXCoreTargetMC(); - bindings.LLVMInitializeXCoreAsmPrinter(); - // There is no LLVMInitializeXCoreAsmParser function. - }, - .m68k => { - if (build_options.llvm_has_m68k) { - bindings.LLVMInitializeM68kTarget(); - bindings.LLVMInitializeM68kTargetInfo(); - bindings.LLVMInitializeM68kTargetMC(); - bindings.LLVMInitializeM68kAsmPrinter(); - bindings.LLVMInitializeM68kAsmParser(); - } - }, - .csky => { - if (build_options.llvm_has_csky) { - bindings.LLVMInitializeCSKYTarget(); - bindings.LLVMInitializeCSKYTargetInfo(); - bindings.LLVMInitializeCSKYTargetMC(); - // There is no LLVMInitializeCSKYAsmPrinter function. - bindings.LLVMInitializeCSKYAsmParser(); - } - }, - .ve => { - bindings.LLVMInitializeVETarget(); - bindings.LLVMInitializeVETargetInfo(); - bindings.LLVMInitializeVETargetMC(); - bindings.LLVMInitializeVEAsmPrinter(); - bindings.LLVMInitializeVEAsmParser(); - }, - .arc => { - if (build_options.llvm_has_arc) { - bindings.LLVMInitializeARCTarget(); - bindings.LLVMInitializeARCTargetInfo(); - bindings.LLVMInitializeARCTargetMC(); - bindings.LLVMInitializeARCAsmPrinter(); - // There is no LLVMInitializeARCAsmParser function. - } - }, - .loongarch32, .loongarch64 => { - bindings.LLVMInitializeLoongArchTarget(); - bindings.LLVMInitializeLoongArchTargetInfo(); - bindings.LLVMInitializeLoongArchTargetMC(); - bindings.LLVMInitializeLoongArchAsmPrinter(); - bindings.LLVMInitializeLoongArchAsmParser(); - }, - .spirv32, - .spirv64, - => { - bindings.LLVMInitializeSPIRVTarget(); - bindings.LLVMInitializeSPIRVTargetInfo(); - bindings.LLVMInitializeSPIRVTargetMC(); - bindings.LLVMInitializeSPIRVAsmPrinter(); - }, - - // LLVM does does not have a backend for these. - .alpha, - .arceb, - .ez80, - .hppa, - .hppa64, - .kvx, - .m88k, - .microblaze, - .microblazeel, - .or1k, - .propeller, - .sh, - .sheb, - .spork8, - .x86_16, - .xtensaeb, - .z80, - => unreachable, - } -} diff --git a/src/codegen/llvm/lib.zig b/src/codegen/llvm/lib.zig new file mode 100644 index 0000000000..a5531b60b9 --- /dev/null +++ b/src/codegen/llvm/lib.zig @@ -0,0 +1,416 @@ +pub const bindings = @import("lib/bindings.zig"); + +comptime { + if (!build_options.have_llvm) @compileError("LLVM unavailable"); +} + +var target_registry_mutex: std.Io.Mutex = .init; +pub fn initializeLLVMTarget(io: Io, arch: std.Target.Cpu.Arch) void { + // Repeated initialization is safe, as targets which have already been registered will be skipped. + // It is however the client's responsibility to synchronize registry access. + target_registry_mutex.lockUncancelable(io); + defer target_registry_mutex.unlock(io); + + switch (arch) { + .aarch64, .aarch64_be => { + bindings.LLVMInitializeAArch64Target(); + bindings.LLVMInitializeAArch64TargetInfo(); + bindings.LLVMInitializeAArch64TargetMC(); + bindings.LLVMInitializeAArch64AsmPrinter(); + bindings.LLVMInitializeAArch64AsmParser(); + }, + .amdgcn => { + bindings.LLVMInitializeAMDGPUTarget(); + bindings.LLVMInitializeAMDGPUTargetInfo(); + bindings.LLVMInitializeAMDGPUTargetMC(); + bindings.LLVMInitializeAMDGPUAsmPrinter(); + bindings.LLVMInitializeAMDGPUAsmParser(); + }, + .thumb, .thumbeb, .arm, .armeb => { + bindings.LLVMInitializeARMTarget(); + bindings.LLVMInitializeARMTargetInfo(); + bindings.LLVMInitializeARMTargetMC(); + bindings.LLVMInitializeARMAsmPrinter(); + bindings.LLVMInitializeARMAsmParser(); + }, + .avr => { + bindings.LLVMInitializeAVRTarget(); + bindings.LLVMInitializeAVRTargetInfo(); + bindings.LLVMInitializeAVRTargetMC(); + bindings.LLVMInitializeAVRAsmPrinter(); + bindings.LLVMInitializeAVRAsmParser(); + }, + .bpfel, .bpfeb => { + bindings.LLVMInitializeBPFTarget(); + bindings.LLVMInitializeBPFTargetInfo(); + bindings.LLVMInitializeBPFTargetMC(); + bindings.LLVMInitializeBPFAsmPrinter(); + bindings.LLVMInitializeBPFAsmParser(); + }, + .hexagon => { + bindings.LLVMInitializeHexagonTarget(); + bindings.LLVMInitializeHexagonTargetInfo(); + bindings.LLVMInitializeHexagonTargetMC(); + bindings.LLVMInitializeHexagonAsmPrinter(); + bindings.LLVMInitializeHexagonAsmParser(); + }, + .lanai => { + bindings.LLVMInitializeLanaiTarget(); + bindings.LLVMInitializeLanaiTargetInfo(); + bindings.LLVMInitializeLanaiTargetMC(); + bindings.LLVMInitializeLanaiAsmPrinter(); + bindings.LLVMInitializeLanaiAsmParser(); + }, + .mips, .mipsel, .mips64, .mips64el => { + bindings.LLVMInitializeMipsTarget(); + bindings.LLVMInitializeMipsTargetInfo(); + bindings.LLVMInitializeMipsTargetMC(); + bindings.LLVMInitializeMipsAsmPrinter(); + bindings.LLVMInitializeMipsAsmParser(); + }, + .msp430 => { + bindings.LLVMInitializeMSP430Target(); + bindings.LLVMInitializeMSP430TargetInfo(); + bindings.LLVMInitializeMSP430TargetMC(); + bindings.LLVMInitializeMSP430AsmPrinter(); + bindings.LLVMInitializeMSP430AsmParser(); + }, + .nvptx, .nvptx64 => { + bindings.LLVMInitializeNVPTXTarget(); + bindings.LLVMInitializeNVPTXTargetInfo(); + bindings.LLVMInitializeNVPTXTargetMC(); + bindings.LLVMInitializeNVPTXAsmPrinter(); + // There is no LLVMInitializeNVPTXAsmParser function available. + }, + .powerpc, .powerpcle, .powerpc64, .powerpc64le => { + bindings.LLVMInitializePowerPCTarget(); + bindings.LLVMInitializePowerPCTargetInfo(); + bindings.LLVMInitializePowerPCTargetMC(); + bindings.LLVMInitializePowerPCAsmPrinter(); + bindings.LLVMInitializePowerPCAsmParser(); + }, + .riscv32, .riscv32be, .riscv64, .riscv64be => { + bindings.LLVMInitializeRISCVTarget(); + bindings.LLVMInitializeRISCVTargetInfo(); + bindings.LLVMInitializeRISCVTargetMC(); + bindings.LLVMInitializeRISCVAsmPrinter(); + bindings.LLVMInitializeRISCVAsmParser(); + }, + .sparc, .sparc64 => { + bindings.LLVMInitializeSparcTarget(); + bindings.LLVMInitializeSparcTargetInfo(); + bindings.LLVMInitializeSparcTargetMC(); + bindings.LLVMInitializeSparcAsmPrinter(); + bindings.LLVMInitializeSparcAsmParser(); + }, + .s390x => { + bindings.LLVMInitializeSystemZTarget(); + bindings.LLVMInitializeSystemZTargetInfo(); + bindings.LLVMInitializeSystemZTargetMC(); + bindings.LLVMInitializeSystemZAsmPrinter(); + bindings.LLVMInitializeSystemZAsmParser(); + }, + .wasm32, .wasm64 => { + bindings.LLVMInitializeWebAssemblyTarget(); + bindings.LLVMInitializeWebAssemblyTargetInfo(); + bindings.LLVMInitializeWebAssemblyTargetMC(); + bindings.LLVMInitializeWebAssemblyAsmPrinter(); + bindings.LLVMInitializeWebAssemblyAsmParser(); + }, + .x86, .x86c16, .x86_64 => { + bindings.LLVMInitializeX86Target(); + bindings.LLVMInitializeX86TargetInfo(); + bindings.LLVMInitializeX86TargetMC(); + bindings.LLVMInitializeX86AsmPrinter(); + bindings.LLVMInitializeX86AsmParser(); + }, + .xtensa => { + if (build_options.llvm_has_xtensa) { + bindings.LLVMInitializeXtensaTarget(); + bindings.LLVMInitializeXtensaTargetInfo(); + bindings.LLVMInitializeXtensaTargetMC(); + bindings.LLVMInitializeXtensaAsmPrinter(); + bindings.LLVMInitializeXtensaAsmParser(); + } + }, + .xcore => { + bindings.LLVMInitializeXCoreTarget(); + bindings.LLVMInitializeXCoreTargetInfo(); + bindings.LLVMInitializeXCoreTargetMC(); + bindings.LLVMInitializeXCoreAsmPrinter(); + // There is no LLVMInitializeXCoreAsmParser function. + }, + .m68k => { + if (build_options.llvm_has_m68k) { + bindings.LLVMInitializeM68kTarget(); + bindings.LLVMInitializeM68kTargetInfo(); + bindings.LLVMInitializeM68kTargetMC(); + bindings.LLVMInitializeM68kAsmPrinter(); + bindings.LLVMInitializeM68kAsmParser(); + } + }, + .csky => { + if (build_options.llvm_has_csky) { + bindings.LLVMInitializeCSKYTarget(); + bindings.LLVMInitializeCSKYTargetInfo(); + bindings.LLVMInitializeCSKYTargetMC(); + // There is no LLVMInitializeCSKYAsmPrinter function. + bindings.LLVMInitializeCSKYAsmParser(); + } + }, + .ve => { + bindings.LLVMInitializeVETarget(); + bindings.LLVMInitializeVETargetInfo(); + bindings.LLVMInitializeVETargetMC(); + bindings.LLVMInitializeVEAsmPrinter(); + bindings.LLVMInitializeVEAsmParser(); + }, + .arc => { + if (build_options.llvm_has_arc) { + bindings.LLVMInitializeARCTarget(); + bindings.LLVMInitializeARCTargetInfo(); + bindings.LLVMInitializeARCTargetMC(); + bindings.LLVMInitializeARCAsmPrinter(); + // There is no LLVMInitializeARCAsmParser function. + } + }, + .loongarch32, .loongarch64 => { + bindings.LLVMInitializeLoongArchTarget(); + bindings.LLVMInitializeLoongArchTargetInfo(); + bindings.LLVMInitializeLoongArchTargetMC(); + bindings.LLVMInitializeLoongArchAsmPrinter(); + bindings.LLVMInitializeLoongArchAsmParser(); + }, + .spirv32, + .spirv64, + => { + bindings.LLVMInitializeSPIRVTarget(); + bindings.LLVMInitializeSPIRVTargetInfo(); + bindings.LLVMInitializeSPIRVTargetMC(); + bindings.LLVMInitializeSPIRVAsmPrinter(); + }, + + // LLVM does does not have a backend for these. + .alpha, + .arceb, + .ez80, + .hppa, + .hppa64, + .kvx, + .m88k, + .microblaze, + .microblazeel, + .or1k, + .propeller, + .sh, + .sheb, + .spork8, + .x86_16, + .xtensaeb, + .z80, + => unreachable, + } +} + +pub fn loadGeneratedBitcode( + comp: *Compilation, + bitcode: []const u32, +) link.Error!struct { *bindings.Context, *bindings.Module } { + initializeLLVMTarget(comp.io, comp.getTarget().cpu.arch); + + const context: *bindings.Context = .create(); + errdefer context.dispose(); + + const bitcode_memory_buffer: *bindings.MemoryBuffer = .createMemoryBufferWithMemoryRange( + @ptrCast(bitcode.ptr), + bitcode.len * 4, + "BitcodeBuffer", + bindings.Bool.False, + ); + defer bitcode_memory_buffer.dispose(); + + context.enableBrokenDebugInfoCheck(); + + var module: *bindings.Module = undefined; + if (context.parseBitcodeInContext2(bitcode_memory_buffer, &module).toBool() or + context.getBrokenDebugInfo()) + { + return comp.link_diags.fail("Failed to parse bitcode", .{}); + } + + return .{ context, module }; +} + +pub const EmitOptions = struct { + llvm_triple: [:0]const u8, + bin_path: ?[:0]const u8, + asm_path: ?[:0]const u8, + opt_ir_path: ?[:0]const u8, + opt_bc_path: ?[:0]const u8, +}; +pub fn emit( + comp: *Compilation, + context: *bindings.Context, + module: *bindings.Module, + options: EmitOptions, +) link.Error!void { + const diags = &comp.link_diags; + const target = comp.getTarget(); + + const emit_asm_msg = options.asm_path orelse "(none)"; + const emit_bin_msg = options.bin_path orelse "(none)"; + const opt_llvm_ir_msg = options.opt_ir_path orelse "(none)"; + const opt_llvm_bc_msg = options.opt_bc_path orelse "(none)"; + std.log.scoped(.codegen).debug("emit LLVM object asm={s} bin={s} ir={s} bc={s}", .{ + emit_asm_msg, emit_bin_msg, opt_llvm_ir_msg, opt_llvm_bc_msg, + }); + const log_opt_llvm_ir = debugLogScopeEnabled("opt-llvm-ir"); + + var llvm_target: *bindings.Target = undefined; + var error_message: [*:0]const u8 = undefined; + if (bindings.Target.getFromTriple(options.llvm_triple, &llvm_target, &error_message).toBool()) { + defer bindings.disposeMessage(error_message); + return diags.fail("LLVM failed to parse '{s}': {s}", .{ options.llvm_triple, error_message }); + } + + const optimize_mode = comp.root_mod.optimize_mode; + + const opt_level: bindings.CodeGenOptLevel = if (optimize_mode == .debug) + .None + else + .Aggressive; + + const reloc_mode: bindings.RelocMode = if (comp.config.pic) + .PIC + else if (comp.config.link_mode == .dynamic) + bindings.RelocMode.DynamicNoPIC + else + .Static; + + const code_model: bindings.CodeModel = switch (llvm.codeModel(comp.root_mod.code_model, target)) { + .default => .Default, + .tiny => .Tiny, + .small => .Small, + .kernel => .Kernel, + .medium => .Medium, + .large => .Large, + }; + + var target_machine = bindings.TargetMachine.create( + llvm_target, + options.llvm_triple, + if (target.cpu.model.llvm_name) |s| s.ptr else null, + comp.root_mod.llvm_cpu_features.?, + opt_level, + reloc_mode, + code_model, + comp.config.function_sections, + comp.config.data_sections, + switch (target.abi.float()) { + .hard => .Hard, + .soft => .Soft, + }, + if (target_util.llvmMachineAbi(target)) |s| s.ptr else null, + target_util.useEmulatedTls(target), + ); + errdefer target_machine.dispose(); + + if (comp.llvm_opt_bisect_limit >= 0) { + context.setOptBisectLimit(comp.llvm_opt_bisect_limit); + } + + // Unfortunately, LLVM shits the bed when we ask for both binary and assembly. + // So we call the entire pipeline multiple times if this is requested. + var time_report_c_str: ?[*:0]u8 = null; + defer if (time_report_c_str) |time_report| bindings.disposeMessage(time_report); + var llvm_ir_c_str: ?[*:0]u8 = null; + defer if (llvm_ir_c_str) |llvm_ir| bindings.disposeMessage(llvm_ir); + var lowered_options: bindings.TargetMachine.EmitOptions = .{ + .is_debug = optimize_mode == .debug, + .is_small = optimize_mode == .small, + .time_report_out = null, // set below to make sure it's only set for a single `emitToFile` + .tsan = comp.config.any_sanitize_thread, + .lto = switch (comp.config.lto) { + .none => .None, + .thin => .ThinPreLink, + .full => .FullPreLink, + }, + .allow_fast_isel = true, + // LLVM's RISC-V backend for some reason enables the machine outliner by default even + // though it's clearly not ready and produces multiple miscompilations in our std tests. + .allow_machine_outliner = !target.cpu.arch.isRiscv(), + .asm_filename = null, + .bin_filename = if (options.bin_path) |x| x.ptr else null, + .llvm_ir_filename = if (options.opt_ir_path) |x| x.ptr else null, + .bitcode_filename = if (options.opt_bc_path) |x| x.ptr else null, + .llvm_ir_out = if (log_opt_llvm_ir) &llvm_ir_c_str else null, + + // `.coverage` value is only used when `.sancov` is enabled. + .sancov = comp.config.any_fuzz or comp.config.san_cov_trace_pc_guard, + .coverage = .{ + .CoverageType = .Edge, + // Works in tandem with Inline8bitCounters or InlineBoolFlag. + // Zig does not yet implement its own version of this but it + // needs to for better fuzzing logic. + .IndirectCalls = false, + .TraceBB = false, + .TraceCmp = false, + .TraceDiv = false, + .TraceGep = false, + .Use8bitCounters = false, + .TracePC = false, + .TracePCGuard = comp.config.san_cov_trace_pc_guard, + // Zig emits its own inline 8-bit counters instrumentation. + .Inline8bitCounters = false, + .InlineBoolFlag = false, + // Zig emits its own PC table instrumentation. + .PCTable = false, + .NoPrune = false, + // Workaround for https://github.com/llvm/llvm-project/pull/106464 + .StackDepth = true, + .TraceLoads = false, + .TraceStores = false, + .CollectControlFlow = false, + }, + }; + if (options.asm_path != null and options.bin_path != null) { + if (target_machine.emitToFile(module, &error_message, &lowered_options)) { + return diags.fail("LLVM failed to emit bin={s} ir={s}: {s}", .{ + emit_bin_msg, opt_llvm_ir_msg, error_message, + }); + } + lowered_options.bin_filename = null; + lowered_options.llvm_ir_filename = null; + lowered_options.bitcode_filename = null; + lowered_options.llvm_ir_out = null; + } + if (comp.time_report) |_| lowered_options.time_report_out = &time_report_c_str; + lowered_options.asm_filename = if (options.asm_path) |x| x.ptr else null; + if (target_machine.emitToFile(module, &error_message, &lowered_options)) { + defer bindings.disposeMessage(error_message); + return diags.fail("LLVM failed to emit asm={s} bin={s} ir={s} bc={s}: {s}", .{ + emit_asm_msg, emit_bin_msg, opt_llvm_ir_msg, opt_llvm_bc_msg, error_message, + }); + } + if (log_opt_llvm_ir) std.log.scoped(.@"opt-llvm-ir").debug("{s}", .{ + llvm_ir_c_str orelse return error.OutOfMemory, + }); + if (comp.time_report) |*time_report| { + assert(time_report.llvm_pass_timings.len == 0); + time_report.llvm_pass_timings = try comp.gpa.dupe(u8, std.mem.span( + time_report_c_str orelse return error.OutOfMemory, + )); + } +} + +const std = @import("std"); +const Io = std.Io; +const assert = std.debug.assert; + +const build_options = @import("build_options"); + +const Compilation = @import("../../Compilation.zig"); +const link = @import("../../link.zig"); +const llvm = @import("../llvm.zig"); +const target_util = @import("../../target.zig"); +const debugLogScopeEnabled = @import("../../main.zig").debugLogScopeEnabled; diff --git a/src/codegen/llvm/bindings.zig b/src/codegen/llvm/lib/bindings.zig similarity index 100% rename from src/codegen/llvm/bindings.zig rename to src/codegen/llvm/lib/bindings.zig diff --git a/src/link/Lld.zig b/src/link/Lld.zig index 3fb717a90f..ef58d1e915 100644 --- a/src/link/Lld.zig +++ b/src/link/Lld.zig @@ -290,7 +290,7 @@ fn linkAsArchive(lld: *Lld, arena: Allocator) link.Error!void { const opt_zcu = comp.zcu; const zcu_obj_path: ?Cache.Path = if (opt_zcu) |zcu| p: { - break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object.?.out_bin_basename); + break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object_basename.?); } else null; log.debug("zcu_obj_path={?f}", .{zcu_obj_path}); @@ -337,13 +337,12 @@ fn linkAsArchive(lld: *Lld, arena: Allocator) link.Error!void { std.debug.print("\n", .{}); } - const llvm_bindings = @import("../codegen/llvm/bindings.zig"); - const llvm = @import("../codegen/llvm.zig"); + const libllvm = @import("../codegen/llvm/lib.zig"); const target = &comp.root_mod.resolved_target.result; - llvm.initializeLLVMTarget(comp.io, target.cpu.arch); + libllvm.initializeLLVMTarget(comp.io, target.cpu.arch); var err_file_index: usize = undefined; var err_msg: [*:0]u8 = undefined; - if (llvm_bindings.WriteArchive( + if (libllvm.bindings.WriteArchive( full_out_path_z, object_files.items.ptr, object_files.items.len, @@ -387,7 +386,7 @@ fn coffLink(lld: *Lld, arena: Allocator) !void { const full_out_path = try directory.join(arena, &[_][]const u8{base.emit.sub_path}); const zcu_obj_path: ?Cache.Path = if (comp.zcu) |zcu| p: { - break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object.?.out_bin_basename); + break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object_basename.?); } else null; const is_lib = comp.config.output_mode == .Lib; @@ -778,7 +777,7 @@ fn elfLink(lld: *Lld, arena: Allocator) !void { const full_out_path = try directory.join(arena, &[_][]const u8{base.emit.sub_path}); const zcu_obj_path: ?Cache.Path = if (comp.zcu) |zcu| p: { - break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object.?.out_bin_basename); + break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object_basename.?); } else null; const output_mode = comp.config.output_mode; @@ -1390,7 +1389,7 @@ fn wasmLink(lld: *Lld, arena: Allocator) !void { const full_out_path = try directory.join(arena, &[_][]const u8{base.emit.sub_path}); const zcu_obj_path: ?Cache.Path = if (comp.zcu) |zcu| p: { - break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object.?.out_bin_basename); + break :p try comp.resolveEmitPathFlush(arena, .temp, zcu.llvm_object_basename.?); } else null; const is_obj = comp.config.output_mode == .Obj; diff --git a/src/link/MachO.zig b/src/link/MachO.zig index a460d439f5..598b3acb9e 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -540,8 +540,8 @@ fn dumpArgv(self: *MachO, comp: *Compilation) !void { const full_out_path = try directory.join(arena, &[_][]const u8{self.base.emit.sub_path}); const zcu_obj_path: ?[]const u8 = p: { const zcu = comp.zcu orelse break :p null; - const llvm_object = zcu.llvm_object orelse break :p null; - const p = try comp.resolveEmitPathFlush(arena, .temp, llvm_object.out_bin_basename); + const basename = zcu.llvm_object_basename orelse break :p null; + const p = try comp.resolveEmitPathFlush(arena, .temp, basename); break :p try p.toString(arena); }; diff --git a/src/main.zig b/src/main.zig index 27e90a4b81..4952098f7a 100644 --- a/src/main.zig +++ b/src/main.zig @@ -3580,7 +3580,7 @@ fn buildOutputType( if (build_options.have_llvm and emit_asm_resolved != .no) { // LLVM has no way to set this non-globally. const argv = [_][*:0]const u8{ "zig (LLVM option parsing)", "--x86-asm-syntax=intel" }; - @import("codegen/llvm/bindings.zig").ParseCommandLineOptions(argv.len, &argv); + @import("codegen/llvm/lib.zig").bindings.ParseCommandLineOptions(argv.len, &argv); } if (build_options.have_llvm and create_module.resolved_options.use_llvm and target.cpu.arch.isSpirv()) { @@ -3609,7 +3609,7 @@ fn buildOutputType( } const argv = [_][*:0]const u8{ "zig (LLVM option parsing)", try extensions.toOwnedSliceSentinel(gpa, 0) }; - @import("codegen/llvm/bindings.zig").ParseCommandLineOptions(argv.len, &argv); + @import("codegen/llvm/lib.zig").bindings.ParseCommandLineOptions(argv.len, &argv); } const clang_passthrough_mode = switch (arg_mode) { @@ -5333,14 +5333,14 @@ pub fn lldMain( const argv = try argsCopyZ(arena, args[1..]); // "If an error occurs, false will be returned." const ok = rc: { - const llvm = @import("codegen/llvm/bindings.zig"); + const libllvm = @import("codegen/llvm/lib.zig"); const argc = @as(c_int, @intCast(argv.len)); if (mem.eql(u8, args[1], "ld.lld")) { - break :rc llvm.LinkELF(argc, argv.ptr, can_exit_early, false); + break :rc libllvm.bindings.LinkELF(argc, argv.ptr, can_exit_early, false); } else if (mem.eql(u8, args[1], "lld-link")) { - break :rc llvm.LinkCOFF(argc, argv.ptr, can_exit_early, false); + break :rc libllvm.bindings.LinkCOFF(argc, argv.ptr, can_exit_early, false); } else if (mem.eql(u8, args[1], "wasm-ld")) { - break :rc llvm.LinkWasm(argc, argv.ptr, can_exit_early, false); + break :rc libllvm.bindings.LinkWasm(argc, argv.ptr, can_exit_early, false); } else { unreachable; }