rustc_codegen_llvm/back/
write.rs

1use std::ffi::{CStr, CString};
2use std::io::{self, Write};
3use std::path::{Path, PathBuf};
4use std::ptr::null_mut;
5use std::sync::Arc;
6use std::{fs, slice, str};
7
8use libc::{c_char, c_int, c_void, size_t};
9use rustc_codegen_ssa::back::link::ensure_removed;
10use rustc_codegen_ssa::back::versioned_llvm_target;
11use rustc_codegen_ssa::back::write::{
12    BitcodeSection, CodegenContext, EmitObj, InlineAsmError, ModuleConfig,
13    TargetMachineFactoryConfig, TargetMachineFactoryFn,
14};
15use rustc_codegen_ssa::base::wants_wasm_eh;
16use rustc_codegen_ssa::traits::*;
17use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind};
18use rustc_data_structures::profiling::SelfProfilerRef;
19use rustc_data_structures::small_c_str::SmallCStr;
20use rustc_errors::{DiagCtxtHandle, Level};
21use rustc_fs_util::{link_or_copy, path_to_c_string};
22use rustc_middle::ty::TyCtxt;
23use rustc_session::Session;
24use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
25use rustc_span::{BytePos, InnerSpan, Pos, RemapPathScopeComponents, SpanData, SyntaxContext, sym};
26use rustc_target::spec::{
27    Arch, CodeModel, FloatAbi, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel,
28};
29use tracing::{debug, trace};
30
31use crate::back::lto::ThinBuffer;
32use crate::back::owned_target_machine::OwnedTargetMachine;
33use crate::back::profiling::{
34    LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
35};
36use crate::common::AsCCharPtr;
37use crate::errors::{
38    CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression,
39    WithLlvmError, WriteBytecode,
40};
41use crate::llvm::diagnostic::OptimizationDiagnosticKind::*;
42use crate::llvm::{self, DiagnosticInfo};
43use crate::type_::llvm_type_ptr;
44use crate::{LlvmCodegenBackend, ModuleLlvm, SimpleCx, attributes, base, common, llvm_util};
45
46pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> ! {
47    match llvm::last_error() {
48        Some(llvm_err) => dcx.emit_fatal(WithLlvmError(err, llvm_err)),
49        None => dcx.emit_fatal(err),
50    }
51}
52
53fn write_output_file<'ll>(
54    dcx: DiagCtxtHandle<'_>,
55    target: &'ll llvm::TargetMachine,
56    no_builtins: bool,
57    m: &'ll llvm::Module,
58    output: &Path,
59    dwo_output: Option<&Path>,
60    file_type: llvm::FileType,
61    self_profiler_ref: &SelfProfilerRef,
62    verify_llvm_ir: bool,
63) {
64    debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
65    let output_c = path_to_c_string(output);
66    let dwo_output_c;
67    let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
68        dwo_output_c = path_to_c_string(dwo_output);
69        dwo_output_c.as_ptr()
70    } else {
71        std::ptr::null()
72    };
73    let result = unsafe {
74        let pm = llvm::LLVMCreatePassManager();
75        llvm::LLVMAddAnalysisPasses(target, pm);
76        llvm::LLVMRustAddLibraryInfo(target, pm, m, no_builtins);
77        llvm::LLVMRustWriteOutputFile(
78            target,
79            pm,
80            m,
81            output_c.as_ptr(),
82            dwo_output_ptr,
83            file_type,
84            verify_llvm_ir,
85        )
86    };
87
88    // Record artifact sizes for self-profiling
89    if result == llvm::LLVMRustResult::Success {
90        let artifact_kind = match file_type {
91            llvm::FileType::ObjectFile => "object_file",
92            llvm::FileType::AssemblyFile => "assembly_file",
93        };
94        record_artifact_size(self_profiler_ref, artifact_kind, output);
95        if let Some(dwo_file) = dwo_output {
96            record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
97        }
98    }
99
100    result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
101}
102
103pub(crate) fn create_informational_target_machine(
104    sess: &Session,
105    only_base_features: bool,
106) -> OwnedTargetMachine {
107    let config = TargetMachineFactoryConfig { split_dwarf_file: None, output_obj_file: None };
108    // Can't use query system here quite yet because this function is invoked before the query
109    // system/tcx is set up.
110    let features = llvm_util::global_llvm_features(sess, only_base_features);
111    target_machine_factory(sess, config::OptLevel::No, &features)(config)
112        .unwrap_or_else(|err| llvm_err(sess.dcx(), err))
113}
114
115pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine {
116    let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
117        tcx.output_filenames(()).split_dwarf_path(
118            tcx.sess.split_debuginfo(),
119            tcx.sess.opts.unstable_opts.split_dwarf_kind,
120            mod_name,
121            tcx.sess.invocation_temp.as_deref(),
122        )
123    } else {
124        None
125    };
126
127    let output_obj_file = Some(tcx.output_filenames(()).temp_path_for_cgu(
128        OutputType::Object,
129        mod_name,
130        tcx.sess.invocation_temp.as_deref(),
131    ));
132    let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file };
133
134    target_machine_factory(
135        tcx.sess,
136        tcx.backend_optimization_level(()),
137        tcx.global_backend_features(()),
138    )(config)
139    .unwrap_or_else(|err| llvm_err(tcx.dcx(), err))
140}
141
142fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
143    use self::config::OptLevel::*;
144    match cfg {
145        No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
146        Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
147        More => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
148        Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
149        Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
150        SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
151    }
152}
153
154fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
155    use config::OptLevel::*;
156    match cfg {
157        No => llvm::PassBuilderOptLevel::O0,
158        Less => llvm::PassBuilderOptLevel::O1,
159        More => llvm::PassBuilderOptLevel::O2,
160        Aggressive => llvm::PassBuilderOptLevel::O3,
161        Size => llvm::PassBuilderOptLevel::Os,
162        SizeMin => llvm::PassBuilderOptLevel::Oz,
163    }
164}
165
166fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
167    match relocation_model {
168        RelocModel::Static => llvm::RelocModel::Static,
169        // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra
170        // attribute.
171        RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
172        RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
173        RelocModel::Ropi => llvm::RelocModel::ROPI,
174        RelocModel::Rwpi => llvm::RelocModel::RWPI,
175        RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
176    }
177}
178
179pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
180    match code_model {
181        Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
182        Some(CodeModel::Small) => llvm::CodeModel::Small,
183        Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
184        Some(CodeModel::Medium) => llvm::CodeModel::Medium,
185        Some(CodeModel::Large) => llvm::CodeModel::Large,
186        None => llvm::CodeModel::None,
187    }
188}
189
190fn to_llvm_float_abi(float_abi: Option<FloatAbi>) -> llvm::FloatAbi {
191    match float_abi {
192        None => llvm::FloatAbi::Default,
193        Some(FloatAbi::Soft) => llvm::FloatAbi::Soft,
194        Some(FloatAbi::Hard) => llvm::FloatAbi::Hard,
195    }
196}
197
198pub(crate) fn target_machine_factory(
199    sess: &Session,
200    optlvl: config::OptLevel,
201    target_features: &[String],
202) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
203    // Self-profile timer for creating a _factory_.
204    let _prof_timer = sess.prof.generic_activity("target_machine_factory");
205
206    let reloc_model = to_llvm_relocation_model(sess.relocation_model());
207
208    let (opt_level, _) = to_llvm_opt_settings(optlvl);
209    let float_abi = if sess.target.arch == Arch::Arm && sess.opts.cg.soft_float {
210        llvm::FloatAbi::Soft
211    } else {
212        // `validate_commandline_args_with_session_available` has already warned about this being
213        // ignored. Let's make sure LLVM doesn't suddenly start using this flag on more targets.
214        to_llvm_float_abi(sess.target.llvm_floatabi)
215    };
216
217    let ffunction_sections =
218        sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
219    let fdata_sections = ffunction_sections;
220    let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
221
222    let code_model = to_llvm_code_model(sess.code_model());
223
224    let mut singlethread = sess.target.singlethread;
225
226    // On the wasm target once the `atomics` feature is enabled that means that
227    // we're no longer single-threaded, or otherwise we don't want LLVM to
228    // lower atomic operations to single-threaded operations.
229    if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
230        singlethread = false;
231    }
232
233    let triple = SmallCStr::new(&versioned_llvm_target(sess));
234    let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
235    let features = CString::new(target_features.join(",")).unwrap();
236    let abi = SmallCStr::new(&sess.target.llvm_abiname);
237    let trap_unreachable =
238        sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
239    let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
240
241    let verbose_asm = sess.opts.unstable_opts.verbose_asm;
242    let relax_elf_relocations =
243        sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
244
245    let use_init_array =
246        !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
247
248    let path_mapping = sess.source_map().path_mapping().clone();
249    let working_dir = sess.source_map().working_dir().clone();
250
251    let use_emulated_tls = matches!(sess.tls_model(), TlsModel::Emulated);
252
253    let debuginfo_compression = match sess.opts.debuginfo_compression {
254        config::DebugInfoCompression::None => llvm::CompressionKind::None,
255        config::DebugInfoCompression::Zlib => {
256            if llvm::LLVMRustLLVMHasZlibCompression() {
257                llvm::CompressionKind::Zlib
258            } else {
259                sess.dcx().emit_warn(UnknownCompression { algorithm: "zlib" });
260                llvm::CompressionKind::None
261            }
262        }
263        config::DebugInfoCompression::Zstd => {
264            if llvm::LLVMRustLLVMHasZstdCompression() {
265                llvm::CompressionKind::Zstd
266            } else {
267                sess.dcx().emit_warn(UnknownCompression { algorithm: "zstd" });
268                llvm::CompressionKind::None
269            }
270        }
271    };
272
273    let use_wasm_eh = wants_wasm_eh(sess);
274
275    let prof = SelfProfilerRef::clone(&sess.prof);
276    Arc::new(move |config: TargetMachineFactoryConfig| {
277        // Self-profile timer for invoking a factory to create a target machine.
278        let _prof_timer = prof.generic_activity("target_machine_factory_inner");
279
280        let path_to_cstring_helper = |path: Option<PathBuf>| -> CString {
281            let path = path.unwrap_or_default();
282            let path = path_mapping
283                .to_real_filename(&working_dir, path)
284                .path(RemapPathScopeComponents::DEBUGINFO)
285                .to_string_lossy()
286                .into_owned();
287            CString::new(path).unwrap()
288        };
289
290        let split_dwarf_file = path_to_cstring_helper(config.split_dwarf_file);
291        let output_obj_file = path_to_cstring_helper(config.output_obj_file);
292
293        OwnedTargetMachine::new(
294            &triple,
295            &cpu,
296            &features,
297            &abi,
298            code_model,
299            reloc_model,
300            opt_level,
301            float_abi,
302            ffunction_sections,
303            fdata_sections,
304            funique_section_names,
305            trap_unreachable,
306            singlethread,
307            verbose_asm,
308            emit_stack_size_section,
309            relax_elf_relocations,
310            use_init_array,
311            &split_dwarf_file,
312            &output_obj_file,
313            debuginfo_compression,
314            use_emulated_tls,
315            use_wasm_eh,
316        )
317    })
318}
319
320pub(crate) fn save_temp_bitcode(
321    cgcx: &CodegenContext<LlvmCodegenBackend>,
322    module: &ModuleCodegen<ModuleLlvm>,
323    name: &str,
324) {
325    if !cgcx.save_temps {
326        return;
327    }
328    let ext = format!("{name}.bc");
329    let path = cgcx.output_filenames.temp_path_ext_for_cgu(
330        &ext,
331        &module.name,
332        cgcx.invocation_temp.as_deref(),
333    );
334    write_bitcode_to_file(module, &path)
335}
336
337fn write_bitcode_to_file(module: &ModuleCodegen<ModuleLlvm>, path: &Path) {
338    unsafe {
339        let path = path_to_c_string(&path);
340        let llmod = module.module_llvm.llmod();
341        llvm::LLVMWriteBitcodeToFile(llmod, path.as_ptr());
342    }
343}
344
345/// In what context is a diagnostic handler being attached to a codegen unit?
346pub(crate) enum CodegenDiagnosticsStage {
347    /// Prelink optimization stage.
348    Opt,
349    /// LTO/ThinLTO postlink optimization stage.
350    LTO,
351    /// Code generation.
352    Codegen,
353}
354
355pub(crate) struct DiagnosticHandlers<'a> {
356    data: *mut (&'a CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'a>),
357    llcx: &'a llvm::Context,
358    old_handler: Option<&'a llvm::DiagnosticHandler>,
359}
360
361impl<'a> DiagnosticHandlers<'a> {
362    pub(crate) fn new(
363        cgcx: &'a CodegenContext<LlvmCodegenBackend>,
364        dcx: DiagCtxtHandle<'a>,
365        llcx: &'a llvm::Context,
366        module: &ModuleCodegen<ModuleLlvm>,
367        stage: CodegenDiagnosticsStage,
368    ) -> Self {
369        let remark_passes_all: bool;
370        let remark_passes: Vec<CString>;
371        match &cgcx.remark {
372            Passes::All => {
373                remark_passes_all = true;
374                remark_passes = Vec::new();
375            }
376            Passes::Some(passes) => {
377                remark_passes_all = false;
378                remark_passes =
379                    passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
380            }
381        };
382        let remark_passes: Vec<*const c_char> =
383            remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
384        let remark_file = cgcx
385            .remark_dir
386            .as_ref()
387            // Use the .opt.yaml file suffix, which is supported by LLVM's opt-viewer.
388            .map(|dir| {
389                let stage_suffix = match stage {
390                    CodegenDiagnosticsStage::Codegen => "codegen",
391                    CodegenDiagnosticsStage::Opt => "opt",
392                    CodegenDiagnosticsStage::LTO => "lto",
393                };
394                dir.join(format!("{}.{stage_suffix}.opt.yaml", module.name))
395            })
396            .and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
397
398        let pgo_available = cgcx.opts.cg.profile_use.is_some();
399        let data = Box::into_raw(Box::new((cgcx, dcx)));
400        unsafe {
401            let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
402            llvm::LLVMRustContextConfigureDiagnosticHandler(
403                llcx,
404                diagnostic_handler,
405                data.cast(),
406                remark_passes_all,
407                remark_passes.as_ptr(),
408                remark_passes.len(),
409                // The `as_ref()` is important here, otherwise the `CString` will be dropped
410                // too soon!
411                remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
412                pgo_available,
413            );
414            DiagnosticHandlers { data, llcx, old_handler }
415        }
416    }
417}
418
419impl<'a> Drop for DiagnosticHandlers<'a> {
420    fn drop(&mut self) {
421        unsafe {
422            llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
423            drop(Box::from_raw(self.data));
424        }
425    }
426}
427
428fn report_inline_asm(
429    cgcx: &CodegenContext<LlvmCodegenBackend>,
430    msg: String,
431    level: llvm::DiagnosticLevel,
432    cookie: u64,
433    source: Option<(String, Vec<InnerSpan>)>,
434) -> InlineAsmError {
435    // In LTO build we may get srcloc values from other crates which are invalid
436    // since they use a different source map. To be safe we just suppress these
437    // in LTO builds.
438    let span = if cookie == 0 || matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
439        SpanData::default()
440    } else {
441        SpanData {
442            lo: BytePos::from_u32(cookie as u32),
443            hi: BytePos::from_u32((cookie >> 32) as u32),
444            ctxt: SyntaxContext::root(),
445            parent: None,
446        }
447    };
448    let level = match level {
449        llvm::DiagnosticLevel::Error => Level::Error,
450        llvm::DiagnosticLevel::Warning => Level::Warning,
451        llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
452    };
453    let msg = msg.trim_prefix("error: ").to_string();
454    InlineAsmError { span, msg, level, source }
455}
456
457unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
458    if user.is_null() {
459        return;
460    }
461    let (cgcx, dcx) =
462        unsafe { *(user as *const (&CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'_>)) };
463
464    match unsafe { llvm::diagnostic::Diagnostic::unpack(info) } {
465        llvm::diagnostic::InlineAsm(inline) => {
466            cgcx.diag_emitter.inline_asm_error(report_inline_asm(
467                cgcx,
468                inline.message,
469                inline.level,
470                inline.cookie,
471                inline.source,
472            ));
473        }
474
475        llvm::diagnostic::Optimization(opt) => {
476            dcx.emit_note(FromLlvmOptimizationDiag {
477                filename: &opt.filename,
478                line: opt.line,
479                column: opt.column,
480                pass_name: &opt.pass_name,
481                kind: match opt.kind {
482                    OptimizationRemark => "success",
483                    OptimizationMissed | OptimizationFailure => "missed",
484                    OptimizationAnalysis
485                    | OptimizationAnalysisFPCommute
486                    | OptimizationAnalysisAliasing => "analysis",
487                    OptimizationRemarkOther => "other",
488                },
489                message: &opt.message,
490            });
491        }
492        llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
493            let message = llvm::build_string(|s| unsafe {
494                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
495            })
496            .expect("non-UTF8 diagnostic");
497            dcx.emit_warn(FromLlvmDiag { message });
498        }
499        llvm::diagnostic::Unsupported(diagnostic_ref) => {
500            let message = llvm::build_string(|s| unsafe {
501                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
502            })
503            .expect("non-UTF8 diagnostic");
504            dcx.emit_err(FromLlvmDiag { message });
505        }
506        llvm::diagnostic::UnknownDiagnostic(..) => {}
507    }
508}
509
510fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
511    match config.pgo_gen {
512        SwitchWithOptPath::Enabled(ref opt_dir_path) => {
513            let path = if let Some(dir_path) = opt_dir_path {
514                dir_path.join("default_%m.profraw")
515            } else {
516                PathBuf::from("default_%m.profraw")
517            };
518
519            Some(CString::new(format!("{}", path.display())).unwrap())
520        }
521        SwitchWithOptPath::Disabled => None,
522    }
523}
524
525fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
526    config
527        .pgo_use
528        .as_ref()
529        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
530}
531
532fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
533    config
534        .pgo_sample_use
535        .as_ref()
536        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
537}
538
539fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
540    config.instrument_coverage.then(|| c"default_%m_%p.profraw".to_owned())
541}
542
543// PreAD will run llvm opts but disable size increasing opts (vectorization, loop unrolling)
544// DuringAD is the same as above, but also runs the enzyme opt and autodiff passes.
545// PostAD will run all opts, including size increasing opts.
546#[derive(Debug, Eq, PartialEq)]
547pub(crate) enum AutodiffStage {
548    PreAD,
549    DuringAD,
550    PostAD,
551}
552
553pub(crate) unsafe fn llvm_optimize(
554    cgcx: &CodegenContext<LlvmCodegenBackend>,
555    dcx: DiagCtxtHandle<'_>,
556    module: &ModuleCodegen<ModuleLlvm>,
557    thin_lto_buffer: Option<&mut *mut llvm::ThinLTOBuffer>,
558    config: &ModuleConfig,
559    opt_level: config::OptLevel,
560    opt_stage: llvm::OptStage,
561    autodiff_stage: AutodiffStage,
562) {
563    // Enzyme:
564    // The whole point of compiler based AD is to differentiate optimized IR instead of unoptimized
565    // source code. However, benchmarks show that optimizations increasing the code size
566    // tend to reduce AD performance. Therefore deactivate them before AD, then differentiate the code
567    // and finally re-optimize the module, now with all optimizations available.
568    // FIXME(ZuseZ4): In a future update we could figure out how to only optimize individual functions getting
569    // differentiated.
570
571    let consider_ad =
572        cfg!(feature = "llvm_enzyme") && config.autodiff.contains(&config::AutoDiff::Enable);
573    let run_enzyme = autodiff_stage == AutodiffStage::DuringAD;
574    let print_before_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModBefore);
575    let print_after_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModAfter);
576    let print_passes = config.autodiff.contains(&config::AutoDiff::PrintPasses);
577    let merge_functions;
578    let unroll_loops;
579    let vectorize_slp;
580    let vectorize_loop;
581
582    // When we build rustc with enzyme/autodiff support, we want to postpone size-increasing
583    // optimizations until after differentiation. Our pipeline is thus: (opt + enzyme), (full opt).
584    // We therefore have two calls to llvm_optimize, if autodiff is used.
585    //
586    // We also must disable merge_functions, since autodiff placeholder/dummy bodies tend to be
587    // identical. We run opts before AD, so there is a chance that LLVM will merge our dummies.
588    // In that case, we lack some dummy bodies and can't replace them with the real AD code anymore.
589    // We then would need to abort compilation. This was especially common in test cases.
590    if consider_ad && autodiff_stage != AutodiffStage::PostAD {
591        merge_functions = false;
592        unroll_loops = false;
593        vectorize_slp = false;
594        vectorize_loop = false;
595    } else {
596        unroll_loops =
597            opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
598        merge_functions = config.merge_functions;
599        vectorize_slp = config.vectorize_slp;
600        vectorize_loop = config.vectorize_loop;
601    }
602    trace!(?unroll_loops, ?vectorize_slp, ?vectorize_loop, ?run_enzyme);
603    if thin_lto_buffer.is_some() {
604        assert!(
605            matches!(
606                opt_stage,
607                llvm::OptStage::PreLinkNoLTO
608                    | llvm::OptStage::PreLinkFatLTO
609                    | llvm::OptStage::PreLinkThinLTO
610            ),
611            "the bitcode for LTO can only be obtained at the pre-link stage"
612        );
613    }
614    let pgo_gen_path = get_pgo_gen_path(config);
615    let pgo_use_path = get_pgo_use_path(config);
616    let pgo_sample_use_path = get_pgo_sample_use_path(config);
617    let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
618    let instr_profile_output_path = get_instr_profile_output_path(config);
619    let sanitize_dataflow_abilist: Vec<_> = config
620        .sanitizer_dataflow_abilist
621        .iter()
622        .map(|file| CString::new(file.as_str()).unwrap())
623        .collect();
624    let sanitize_dataflow_abilist_ptrs: Vec<_> =
625        sanitize_dataflow_abilist.iter().map(|file| file.as_ptr()).collect();
626    // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
627    let sanitizer_options = if !is_lto {
628        Some(llvm::SanitizerOptions {
629            sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
630            sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
631            sanitize_cfi: config.sanitizer.contains(SanitizerSet::CFI),
632            sanitize_dataflow: config.sanitizer.contains(SanitizerSet::DATAFLOW),
633            sanitize_dataflow_abilist: sanitize_dataflow_abilist_ptrs.as_ptr(),
634            sanitize_dataflow_abilist_len: sanitize_dataflow_abilist_ptrs.len(),
635            sanitize_kcfi: config.sanitizer.contains(SanitizerSet::KCFI),
636            sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
637            sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
638            sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
639            sanitize_realtime: config.sanitizer.contains(SanitizerSet::REALTIME),
640            sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
641            sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
642            sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
643            sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
644            sanitize_kernel_address_recover: config
645                .sanitizer_recover
646                .contains(SanitizerSet::KERNELADDRESS),
647        })
648    } else {
649        None
650    };
651
652    fn handle_offload<'ll>(cx: &'ll SimpleCx<'_>, old_fn: &llvm::Value) {
653        let old_fn_ty = cx.get_type_of_global(old_fn);
654        let old_param_types = cx.func_params_types(old_fn_ty);
655        let old_param_count = old_param_types.len();
656        if old_param_count == 0 {
657            return;
658        }
659
660        let first_param = llvm::get_param(old_fn, 0);
661        let c_name = llvm::get_value_name(first_param);
662        let first_arg_name = str::from_utf8(&c_name).unwrap();
663        // We might call llvm_optimize (and thus this code) multiple times on the same IR,
664        // but we shouldn't add this helper ptr multiple times.
665        // FIXME(offload): This could break if the user calls his first argument `dyn_ptr`.
666        if first_arg_name == "dyn_ptr" {
667            return;
668        }
669
670        // Create the new parameter list, with ptr as the first argument
671        let mut new_param_types = Vec::with_capacity(old_param_count as usize + 1);
672        new_param_types.push(cx.type_ptr());
673        new_param_types.extend(old_param_types);
674
675        // Create the new function type
676        let ret_ty = unsafe { llvm::LLVMGetReturnType(old_fn_ty) };
677        let new_fn_ty = cx.type_func(&new_param_types, ret_ty);
678
679        // Create the new function, with a temporary .offload name to avoid a name collision.
680        let old_fn_name = String::from_utf8(llvm::get_value_name(old_fn)).unwrap();
681        let new_fn_name = format!("{}.offload", &old_fn_name);
682        let new_fn = cx.add_func(&new_fn_name, new_fn_ty);
683        let a0 = llvm::get_param(new_fn, 0);
684        llvm::set_value_name(a0, CString::new("dyn_ptr").unwrap().as_bytes());
685
686        // Here we map the old arguments to the new arguments, with an offset of 1 to make sure
687        // that we don't use the newly added `%dyn_ptr`.
688        unsafe {
689            llvm::LLVMRustOffloadMapper(old_fn, new_fn);
690        }
691
692        llvm::set_linkage(new_fn, llvm::get_linkage(old_fn));
693        llvm::set_visibility(new_fn, llvm::get_visibility(old_fn));
694
695        // Replace all uses of old_fn with new_fn (RAUW)
696        unsafe {
697            llvm::LLVMReplaceAllUsesWith(old_fn, new_fn);
698        }
699        let name = llvm::get_value_name(old_fn);
700        unsafe {
701            llvm::LLVMDeleteFunction(old_fn);
702        }
703        // Now we can re-use the old name, without name collision.
704        llvm::set_value_name(new_fn, &name);
705    }
706
707    if cgcx.target_is_like_gpu && config.offload.contains(&config::Offload::Enable) {
708        let cx =
709            SimpleCx::new(module.module_llvm.llmod(), module.module_llvm.llcx, cgcx.pointer_size);
710        // For now we only support up to 10 kernels named kernel_0 ... kernel_9, a follow-up PR is
711        // introducing a proper offload intrinsic to solve this limitation.
712        for func in cx.get_functions() {
713            let offload_kernel = "offload-kernel";
714            if attributes::has_string_attr(func, offload_kernel) {
715                handle_offload(&cx, func);
716            }
717            attributes::remove_string_attr_from_llfn(func, offload_kernel);
718        }
719    }
720
721    let mut llvm_profiler = cgcx
722        .prof
723        .llvm_recording_enabled()
724        .then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()));
725
726    let llvm_selfprofiler =
727        llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
728
729    let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
730
731    let llvm_plugins = config.llvm_plugins.join(",");
732
733    let result = unsafe {
734        llvm::LLVMRustOptimize(
735            module.module_llvm.llmod(),
736            &*module.module_llvm.tm.raw(),
737            to_pass_builder_opt_level(opt_level),
738            opt_stage,
739            cgcx.opts.cg.linker_plugin_lto.enabled(),
740            config.no_prepopulate_passes,
741            config.verify_llvm_ir,
742            config.lint_llvm_ir,
743            thin_lto_buffer,
744            config.emit_thin_lto,
745            config.emit_thin_lto_summary,
746            merge_functions,
747            unroll_loops,
748            vectorize_slp,
749            vectorize_loop,
750            config.no_builtins,
751            config.emit_lifetime_markers,
752            run_enzyme,
753            print_before_enzyme,
754            print_after_enzyme,
755            print_passes,
756            sanitizer_options.as_ref(),
757            pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
758            pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
759            config.instrument_coverage,
760            instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
761            pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
762            config.debug_info_for_profiling,
763            llvm_selfprofiler,
764            selfprofile_before_pass_callback,
765            selfprofile_after_pass_callback,
766            extra_passes.as_c_char_ptr(),
767            extra_passes.len(),
768            llvm_plugins.as_c_char_ptr(),
769            llvm_plugins.len(),
770        )
771    };
772
773    if cgcx.target_is_like_gpu && config.offload.contains(&config::Offload::Enable) {
774        unsafe {
775            llvm::LLVMRustBundleImages(module.module_llvm.llmod(), module.module_llvm.tm.raw());
776        }
777    }
778
779    result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
780}
781
782// Unsafe due to LLVM calls.
783pub(crate) fn optimize(
784    cgcx: &CodegenContext<LlvmCodegenBackend>,
785    dcx: DiagCtxtHandle<'_>,
786    module: &mut ModuleCodegen<ModuleLlvm>,
787    config: &ModuleConfig,
788) {
789    let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
790
791    let llcx = &*module.module_llvm.llcx;
792    let _handlers = DiagnosticHandlers::new(cgcx, dcx, llcx, module, CodegenDiagnosticsStage::Opt);
793
794    if config.emit_no_opt_bc {
795        let out = cgcx.output_filenames.temp_path_ext_for_cgu(
796            "no-opt.bc",
797            &module.name,
798            cgcx.invocation_temp.as_deref(),
799        );
800        write_bitcode_to_file(module, &out)
801    }
802
803    // FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts
804
805    if let Some(opt_level) = config.opt_level {
806        let opt_stage = match cgcx.lto {
807            Lto::Fat => llvm::OptStage::PreLinkFatLTO,
808            Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
809            _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
810            _ => llvm::OptStage::PreLinkNoLTO,
811        };
812
813        // If we know that we will later run AD, then we disable vectorization and loop unrolling.
814        // Otherwise we pretend AD is already done and run the normal opt pipeline (=PostAD).
815        let consider_ad =
816            cfg!(feature = "llvm_enzyme") && config.autodiff.contains(&config::AutoDiff::Enable);
817        let autodiff_stage = if consider_ad { AutodiffStage::PreAD } else { AutodiffStage::PostAD };
818        // The embedded bitcode is used to run LTO/ThinLTO.
819        // The bitcode obtained during the `codegen` phase is no longer suitable for performing LTO.
820        // It may have undergone LTO due to ThinLocal, so we need to obtain the embedded bitcode at
821        // this point.
822        let mut thin_lto_buffer = if (module.kind == ModuleKind::Regular
823            && config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full))
824            || config.emit_thin_lto_summary
825        {
826            Some(null_mut())
827        } else {
828            None
829        };
830        unsafe {
831            llvm_optimize(
832                cgcx,
833                dcx,
834                module,
835                thin_lto_buffer.as_mut(),
836                config,
837                opt_level,
838                opt_stage,
839                autodiff_stage,
840            )
841        };
842        if let Some(thin_lto_buffer) = thin_lto_buffer {
843            let thin_lto_buffer = unsafe { ThinBuffer::from_raw_ptr(thin_lto_buffer) };
844            module.thin_lto_buffer = Some(thin_lto_buffer.data().to_vec());
845            let bc_summary_out = cgcx.output_filenames.temp_path_for_cgu(
846                OutputType::ThinLinkBitcode,
847                &module.name,
848                cgcx.invocation_temp.as_deref(),
849            );
850            if config.emit_thin_lto_summary
851                && let Some(thin_link_bitcode_filename) = bc_summary_out.file_name()
852            {
853                let summary_data = thin_lto_buffer.thin_link_data();
854                cgcx.prof.artifact_size(
855                    "llvm_bitcode_summary",
856                    thin_link_bitcode_filename.to_string_lossy(),
857                    summary_data.len() as u64,
858                );
859                let _timer = cgcx.prof.generic_activity_with_arg(
860                    "LLVM_module_codegen_emit_bitcode_summary",
861                    &*module.name,
862                );
863                if let Err(err) = fs::write(&bc_summary_out, summary_data) {
864                    dcx.emit_err(WriteBytecode { path: &bc_summary_out, err });
865                }
866            }
867        }
868    }
869}
870
871pub(crate) fn codegen(
872    cgcx: &CodegenContext<LlvmCodegenBackend>,
873    module: ModuleCodegen<ModuleLlvm>,
874    config: &ModuleConfig,
875) -> CompiledModule {
876    let dcx = cgcx.create_dcx();
877    let dcx = dcx.handle();
878
879    let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
880    {
881        let llmod = module.module_llvm.llmod();
882        let llcx = &*module.module_llvm.llcx;
883        let tm = &*module.module_llvm.tm;
884        let _handlers =
885            DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::Codegen);
886
887        if cgcx.msvc_imps_needed {
888            create_msvc_imps(cgcx, llcx, llmod);
889        }
890
891        // Note that if object files are just LLVM bitcode we write bitcode,
892        // copy it to the .o file, and delete the bitcode if it wasn't
893        // otherwise requested.
894
895        let bc_out = cgcx.output_filenames.temp_path_for_cgu(
896            OutputType::Bitcode,
897            &module.name,
898            cgcx.invocation_temp.as_deref(),
899        );
900        let obj_out = cgcx.output_filenames.temp_path_for_cgu(
901            OutputType::Object,
902            &module.name,
903            cgcx.invocation_temp.as_deref(),
904        );
905
906        if config.bitcode_needed() {
907            if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
908                let thin = {
909                    let _timer = cgcx.prof.generic_activity_with_arg(
910                        "LLVM_module_codegen_make_bitcode",
911                        &*module.name,
912                    );
913                    ThinBuffer::new(llmod, config.emit_thin_lto)
914                };
915                let data = thin.data();
916                let _timer = cgcx
917                    .prof
918                    .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
919                if let Some(bitcode_filename) = bc_out.file_name() {
920                    cgcx.prof.artifact_size(
921                        "llvm_bitcode",
922                        bitcode_filename.to_string_lossy(),
923                        data.len() as u64,
924                    );
925                }
926                if let Err(err) = fs::write(&bc_out, data) {
927                    dcx.emit_err(WriteBytecode { path: &bc_out, err });
928                }
929            }
930
931            if config.embed_bitcode() && module.kind == ModuleKind::Regular {
932                let _timer = cgcx
933                    .prof
934                    .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
935                let thin_bc =
936                    module.thin_lto_buffer.as_deref().expect("cannot find embedded bitcode");
937                embed_bitcode(cgcx, llcx, llmod, &thin_bc);
938            }
939        }
940
941        if config.emit_ir {
942            let _timer =
943                cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
944            let out = cgcx.output_filenames.temp_path_for_cgu(
945                OutputType::LlvmAssembly,
946                &module.name,
947                cgcx.invocation_temp.as_deref(),
948            );
949            let out_c = path_to_c_string(&out);
950
951            extern "C" fn demangle_callback(
952                input_ptr: *const c_char,
953                input_len: size_t,
954                output_ptr: *mut c_char,
955                output_len: size_t,
956            ) -> size_t {
957                let input =
958                    unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
959
960                let Ok(input) = str::from_utf8(input) else { return 0 };
961
962                let output = unsafe {
963                    slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
964                };
965                let mut cursor = io::Cursor::new(output);
966
967                let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
968
969                if write!(cursor, "{demangled:#}").is_err() {
970                    // Possible only if provided buffer is not big enough
971                    return 0;
972                }
973
974                cursor.position() as size_t
975            }
976
977            let result =
978                unsafe { llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback) };
979
980            if result == llvm::LLVMRustResult::Success {
981                record_artifact_size(&cgcx.prof, "llvm_ir", &out);
982            }
983
984            result
985                .into_result()
986                .unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteIr { path: &out }));
987        }
988
989        if config.emit_asm {
990            let _timer =
991                cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
992            let path = cgcx.output_filenames.temp_path_for_cgu(
993                OutputType::Assembly,
994                &module.name,
995                cgcx.invocation_temp.as_deref(),
996            );
997
998            // We can't use the same module for asm and object code output,
999            // because that triggers various errors like invalid IR or broken
1000            // binaries. So we must clone the module to produce the asm output
1001            // if we are also producing object code.
1002            let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
1003                llvm::LLVMCloneModule(llmod)
1004            } else {
1005                llmod
1006            };
1007            write_output_file(
1008                dcx,
1009                tm.raw(),
1010                config.no_builtins,
1011                llmod,
1012                &path,
1013                None,
1014                llvm::FileType::AssemblyFile,
1015                &cgcx.prof,
1016                config.verify_llvm_ir,
1017            );
1018        }
1019
1020        match config.emit_obj {
1021            EmitObj::ObjectCode(_) => {
1022                let _timer = cgcx
1023                    .prof
1024                    .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
1025
1026                let dwo_out = cgcx
1027                    .output_filenames
1028                    .temp_path_dwo_for_cgu(&module.name, cgcx.invocation_temp.as_deref());
1029                let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
1030                    // Don't change how DWARF is emitted when disabled.
1031                    (SplitDebuginfo::Off, _) => None,
1032                    // Don't provide a DWARF object path if split debuginfo is enabled but this is
1033                    // a platform that doesn't support Split DWARF.
1034                    _ if !cgcx.target_can_use_split_dwarf => None,
1035                    // Don't provide a DWARF object path in single mode, sections will be written
1036                    // into the object as normal but ignored by linker.
1037                    (_, SplitDwarfKind::Single) => None,
1038                    // Emit (a subset of the) DWARF into a separate dwarf object file in split
1039                    // mode.
1040                    (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
1041                };
1042
1043                write_output_file(
1044                    dcx,
1045                    tm.raw(),
1046                    config.no_builtins,
1047                    llmod,
1048                    &obj_out,
1049                    dwo_out,
1050                    llvm::FileType::ObjectFile,
1051                    &cgcx.prof,
1052                    config.verify_llvm_ir,
1053                );
1054            }
1055
1056            EmitObj::Bitcode => {
1057                debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
1058                if let Err(err) = link_or_copy(&bc_out, &obj_out) {
1059                    dcx.emit_err(CopyBitcode { err });
1060                }
1061
1062                if !config.emit_bc {
1063                    debug!("removing_bitcode {:?}", bc_out);
1064                    ensure_removed(dcx, &bc_out);
1065                }
1066            }
1067
1068            EmitObj::None => {}
1069        }
1070
1071        record_llvm_cgu_instructions_stats(&cgcx.prof, llmod);
1072    }
1073
1074    // `.dwo` files are only emitted if:
1075    //
1076    // - Object files are being emitted (i.e. bitcode only or metadata only compilations will not
1077    //   produce dwarf objects, even if otherwise enabled)
1078    // - Target supports Split DWARF
1079    // - Split debuginfo is enabled
1080    // - Split DWARF kind is `split` (i.e. debuginfo is split into `.dwo` files, not different
1081    //   sections in the `.o` files).
1082    let dwarf_object_emitted = matches!(config.emit_obj, EmitObj::ObjectCode(_))
1083        && cgcx.target_can_use_split_dwarf
1084        && cgcx.split_debuginfo != SplitDebuginfo::Off
1085        && cgcx.split_dwarf_kind == SplitDwarfKind::Split;
1086    module.into_compiled_module(
1087        config.emit_obj != EmitObj::None,
1088        dwarf_object_emitted,
1089        config.emit_bc,
1090        config.emit_asm,
1091        config.emit_ir,
1092        &cgcx.output_filenames,
1093        cgcx.invocation_temp.as_deref(),
1094    )
1095}
1096
1097fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
1098    let mut asm = format!(".section {section_name},\"{section_flags}\"\n").into_bytes();
1099    asm.extend_from_slice(b".ascii \"");
1100    asm.reserve(data.len());
1101    for &byte in data {
1102        if byte == b'\\' || byte == b'"' {
1103            asm.push(b'\\');
1104            asm.push(byte);
1105        } else if byte < 0x20 || byte >= 0x80 {
1106            // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
1107            // width, while hex escapes will consume following characters.
1108            asm.push(b'\\');
1109            asm.push(b'0' + ((byte >> 6) & 0x7));
1110            asm.push(b'0' + ((byte >> 3) & 0x7));
1111            asm.push(b'0' + ((byte >> 0) & 0x7));
1112        } else {
1113            asm.push(byte);
1114        }
1115    }
1116    asm.extend_from_slice(b"\"\n");
1117    asm
1118}
1119
1120pub(crate) fn bitcode_section_name(cgcx: &CodegenContext<LlvmCodegenBackend>) -> &'static CStr {
1121    if cgcx.target_is_like_darwin {
1122        c"__LLVM,__bitcode"
1123    } else if cgcx.target_is_like_aix {
1124        c".ipa"
1125    } else {
1126        c".llvmbc"
1127    }
1128}
1129
1130/// Embed the bitcode of an LLVM module for LTO in the LLVM module itself.
1131fn embed_bitcode(
1132    cgcx: &CodegenContext<LlvmCodegenBackend>,
1133    llcx: &llvm::Context,
1134    llmod: &llvm::Module,
1135    bitcode: &[u8],
1136) {
1137    // We're adding custom sections to the output object file, but we definitely
1138    // do not want these custom sections to make their way into the final linked
1139    // executable. The purpose of these custom sections is for tooling
1140    // surrounding object files to work with the LLVM IR, if necessary. For
1141    // example rustc's own LTO will look for LLVM IR inside of the object file
1142    // in these sections by default.
1143    //
1144    // To handle this is a bit different depending on the object file format
1145    // used by the backend, broken down into a few different categories:
1146    //
1147    // * Mach-O - this is for macOS. Inspecting the source code for the native
1148    //   linker here shows that the `.llvmbc` and `.llvmcmd` sections are
1149    //   automatically skipped by the linker. In that case there's nothing extra
1150    //   that we need to do here. We do need to make sure that the
1151    //   `__LLVM,__cmdline` section exists even though it is empty as otherwise
1152    //   ld64 rejects the object file.
1153    //
1154    // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
1155    //   `.llvmcmd` sections, so there's nothing extra we need to do.
1156    //
1157    // * COFF - if we don't do anything the linker will by default copy all
1158    //   these sections to the output artifact, not what we want! To subvert
1159    //   this we want to flag the sections we inserted here as
1160    //   `IMAGE_SCN_LNK_REMOVE`.
1161    //
1162    // * ELF - this is very similar to COFF above. One difference is that these
1163    //   sections are removed from the output linked artifact when
1164    //   `--gc-sections` is passed, which we pass by default. If that flag isn't
1165    //   passed though then these sections will show up in the final output.
1166    //   Additionally the flag that we need to set here is `SHF_EXCLUDE`.
1167    //
1168    // * XCOFF - AIX linker ignores content in .ipa and .info if no auxiliary
1169    //   symbol associated with these sections.
1170    //
1171    // Unfortunately, LLVM provides no way to set custom section flags. For ELF
1172    // and COFF we emit the sections using module level inline assembly for that
1173    // reason (see issue #90326 for historical background).
1174
1175    if cgcx.target_is_like_darwin
1176        || cgcx.target_is_like_aix
1177        || cgcx.target_arch == "wasm32"
1178        || cgcx.target_arch == "wasm64"
1179    {
1180        // We don't need custom section flags, create LLVM globals.
1181        let llconst = common::bytes_in_context(llcx, bitcode);
1182        let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.module");
1183        llvm::set_initializer(llglobal, llconst);
1184
1185        llvm::set_section(llglobal, bitcode_section_name(cgcx));
1186        llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1187        llvm::LLVMSetGlobalConstant(llglobal, llvm::TRUE);
1188
1189        let llconst = common::bytes_in_context(llcx, &[]);
1190        let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.cmdline");
1191        llvm::set_initializer(llglobal, llconst);
1192        let section = if cgcx.target_is_like_darwin {
1193            c"__LLVM,__cmdline"
1194        } else if cgcx.target_is_like_aix {
1195            c".info"
1196        } else {
1197            c".llvmcmd"
1198        };
1199        llvm::set_section(llglobal, section);
1200        llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1201    } else {
1202        // We need custom section flags, so emit module-level inline assembly.
1203        let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
1204        let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
1205        llvm::append_module_inline_asm(llmod, &asm);
1206        let asm = create_section_with_flags_asm(".llvmcmd", section_flags, &[]);
1207        llvm::append_module_inline_asm(llmod, &asm);
1208    }
1209}
1210
1211// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1212// This is required to satisfy `dllimport` references to static data in .rlibs
1213// when using MSVC linker. We do this only for data, as linker can fix up
1214// code references on its own.
1215// See #26591, #27438
1216fn create_msvc_imps(
1217    cgcx: &CodegenContext<LlvmCodegenBackend>,
1218    llcx: &llvm::Context,
1219    llmod: &llvm::Module,
1220) {
1221    if !cgcx.msvc_imps_needed {
1222        return;
1223    }
1224    // The x86 ABI seems to require that leading underscores are added to symbol
1225    // names, so we need an extra underscore on x86. There's also a leading
1226    // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1227    // underscores added in front).
1228    let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1229
1230    let ptr_ty = llvm_type_ptr(llcx);
1231    let globals = base::iter_globals(llmod)
1232        .filter(|&val| {
1233            llvm::get_linkage(val) == llvm::Linkage::ExternalLinkage && !llvm::is_declaration(val)
1234        })
1235        .filter_map(|val| {
1236            // Exclude some symbols that we know are not Rust symbols.
1237            let name = llvm::get_value_name(val);
1238            if ignored(&name) { None } else { Some((val, name)) }
1239        })
1240        .map(move |(val, name)| {
1241            let mut imp_name = prefix.as_bytes().to_vec();
1242            imp_name.extend(name);
1243            let imp_name = CString::new(imp_name).unwrap();
1244            (imp_name, val)
1245        })
1246        .collect::<Vec<_>>();
1247
1248    for (imp_name, val) in globals {
1249        let imp = llvm::add_global(llmod, ptr_ty, &imp_name);
1250
1251        llvm::set_initializer(imp, val);
1252        llvm::set_linkage(imp, llvm::Linkage::ExternalLinkage);
1253    }
1254
1255    // Use this function to exclude certain symbols from `__imp` generation.
1256    fn ignored(symbol_name: &[u8]) -> bool {
1257        // These are symbols generated by LLVM's profiling instrumentation
1258        symbol_name.starts_with(b"__llvm_profile_")
1259    }
1260}
1261
1262fn record_artifact_size(
1263    self_profiler_ref: &SelfProfilerRef,
1264    artifact_kind: &'static str,
1265    path: &Path,
1266) {
1267    // Don't stat the file if we are not going to record its size.
1268    if !self_profiler_ref.enabled() {
1269        return;
1270    }
1271
1272    if let Some(artifact_name) = path.file_name() {
1273        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
1274        self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
1275    }
1276}
1277
1278fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, llmod: &llvm::Module) {
1279    if !prof.enabled() {
1280        return;
1281    }
1282
1283    let raw_stats =
1284        llvm::build_string(|s| unsafe { llvm::LLVMRustModuleInstructionStats(llmod, s) })
1285            .expect("cannot get module instruction stats");
1286
1287    #[derive(serde::Deserialize)]
1288    struct InstructionsStats {
1289        module: String,
1290        total: u64,
1291    }
1292
1293    let InstructionsStats { module, total } =
1294        serde_json::from_str(&raw_stats).expect("cannot parse llvm cgu instructions stats");
1295    prof.artifact_size("cgu_instructions", module, total);
1296}