Skip to main content

rustc_codegen_llvm/
lib.rs

1//! The Rust compiler.
2//!
3//! # Note
4//!
5//! This API is completely unstable and subject to change.
6
7// tidy-alphabetical-start
8#![feature(extern_types)]
9#![feature(file_buffered)]
10#![feature(impl_trait_in_assoc_type)]
11#![feature(iter_intersperse)]
12#![feature(macro_derive)]
13#![feature(once_cell_try)]
14#![feature(trim_prefix_suffix)]
15#![feature(try_blocks)]
16// tidy-alphabetical-end
17
18use std::any::Any;
19use std::ffi::CStr;
20use std::mem::ManuallyDrop;
21use std::path::PathBuf;
22
23use back::owned_target_machine::OwnedTargetMachine;
24use back::write::{create_informational_target_machine, create_target_machine};
25use context::SimpleCx;
26use llvm_util::target_config;
27use rustc_ast::expand::allocator::AllocatorMethod;
28use rustc_codegen_ssa::back::lto::ThinModule;
29use rustc_codegen_ssa::back::write::{
30    CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryConfig,
31    TargetMachineFactoryFn, ThinLtoInput,
32};
33use rustc_codegen_ssa::traits::*;
34use rustc_codegen_ssa::{CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, TargetConfig};
35use rustc_data_structures::profiling::SelfProfilerRef;
36use rustc_errors::{DiagCtxt, DiagCtxtHandle};
37use rustc_metadata::EncodedMetadata;
38use rustc_middle::dep_graph::{WorkProduct, WorkProductMap};
39use rustc_middle::ty::TyCtxt;
40use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
41use rustc_session::{CodegenBackendInit, EarlySession, IncrCompSession, Session};
42use rustc_span::{Symbol, sym};
43use rustc_target::spec::{RelocModel, TlsModel};
44
45use crate::llvm::ToLlvmBool;
46
47mod abi;
48mod allocator;
49mod asm;
50mod attributes;
51mod back;
52mod base;
53mod builder;
54mod callee;
55mod common;
56mod consts;
57mod context;
58mod coverageinfo;
59mod debuginfo;
60mod declare;
61mod diagnostics;
62mod intrinsic;
63mod llvm;
64mod llvm_util;
65mod macros;
66mod mono_item;
67mod type_;
68mod type_of;
69mod typetree;
70mod va_arg;
71mod value;
72
73pub(crate) use macros::TryFromU32;
74
75#[derive(#[automatically_derived]
impl ::core::clone::Clone for LlvmCodegenBackend {
    #[inline]
    fn clone(&self) -> LlvmCodegenBackend {
        LlvmCodegenBackend(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
76pub struct LlvmCodegenBackend(());
77
78struct TimeTraceProfiler {}
79
80impl TimeTraceProfiler {
81    fn new() -> Self {
82        unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
83        TimeTraceProfiler {}
84    }
85}
86
87impl Drop for TimeTraceProfiler {
88    fn drop(&mut self) {
89        unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
90    }
91}
92
93impl ExtraBackendMethods for LlvmCodegenBackend {
94    type Module = ModuleLlvm;
95
96    fn codegen_allocator<'tcx>(
97        &self,
98        tcx: TyCtxt<'tcx>,
99        module_name: &str,
100        methods: &[AllocatorMethod],
101    ) -> ModuleLlvm {
102        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
103        let cx =
104            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
105        unsafe {
106            allocator::codegen(tcx, cx, module_name, methods);
107        }
108        module_llvm
109    }
110    fn compile_codegen_unit(
111        &self,
112        tcx: TyCtxt<'_>,
113        cgu_name: Symbol,
114        bitcode_needed: bool,
115    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
116        base::compile_codegen_unit(tcx, cgu_name, bitcode_needed)
117    }
118}
119
120impl WriteBackendMethods for LlvmCodegenBackend {
121    type Module = ModuleLlvm;
122    type ModuleBuffer = back::lto::ModuleBuffer;
123    type TargetMachine = OwnedTargetMachine;
124    type ThinData = back::lto::ThinData;
125
126    fn thread_profiler() -> Box<dyn Any> {
127        Box::new(TimeTraceProfiler::new())
128    }
129    fn target_machine_factory(
130        &self,
131        sess: &Session,
132        optlvl: OptLevel,
133    ) -> TargetMachineFactoryFn<Self> {
134        back::write::target_machine_factory(sess, optlvl)
135    }
136    fn optimize_and_codegen_fat_lto(
137        sess: &Session,
138        cgcx: &CodegenContext,
139        shared_emitter: &SharedEmitter,
140        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
141        exported_symbols_for_lto: &[String],
142        each_linked_rlib_for_lto: &[PathBuf],
143        modules: Vec<FatLtoInput<Self>>,
144    ) -> CompiledModule {
145        let mut module = back::lto::run_fat(
146            cgcx,
147            &sess.prof,
148            shared_emitter,
149            tm_factory,
150            exported_symbols_for_lto,
151            each_linked_rlib_for_lto,
152            modules,
153        );
154
155        let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
156        let dcx = dcx.handle();
157        back::lto::run_pass_manager(cgcx, &sess.prof, dcx, &mut module, false);
158
159        back::write::codegen(cgcx, &sess.prof, shared_emitter, module, &cgcx.module_config)
160    }
161    fn run_thin_lto(
162        cgcx: &CodegenContext,
163        prof: &SelfProfilerRef,
164        dcx: DiagCtxtHandle<'_>,
165        exported_symbols_for_lto: &[String],
166        each_linked_rlib_for_lto: &[PathBuf],
167        modules: Vec<ThinLtoInput<Self>>,
168    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
169        back::lto::run_thin(
170            cgcx,
171            prof,
172            dcx,
173            exported_symbols_for_lto,
174            each_linked_rlib_for_lto,
175            modules,
176        )
177    }
178    fn optimize(
179        cgcx: &CodegenContext,
180        prof: &SelfProfilerRef,
181        shared_emitter: &SharedEmitter,
182        module: &mut ModuleCodegen<Self::Module>,
183        config: &ModuleConfig,
184    ) {
185        back::write::optimize(cgcx, prof, shared_emitter, module, config)
186    }
187    fn optimize_and_codegen_thin(
188        cgcx: &CodegenContext,
189        prof: &SelfProfilerRef,
190        shared_emitter: &SharedEmitter,
191        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
192        thin: ThinModule<Self>,
193    ) -> CompiledModule {
194        back::lto::optimize_and_codegen_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
195    }
196    fn codegen(
197        cgcx: &CodegenContext,
198        prof: &SelfProfilerRef,
199        shared_emitter: &SharedEmitter,
200        module: ModuleCodegen<Self::Module>,
201        config: &ModuleConfig,
202    ) -> CompiledModule {
203        back::write::codegen(cgcx, prof, shared_emitter, module, config)
204    }
205    fn serialize_module(module: Self::Module, is_thin: bool) -> Self::ModuleBuffer {
206        back::lto::ModuleBuffer::new(module.llmod(), is_thin)
207    }
208}
209
210impl LlvmCodegenBackend {
211    pub fn new() -> Box<dyn CodegenBackend> {
212        Box::new(LlvmCodegenBackend(()))
213    }
214}
215
216impl CodegenBackend for LlvmCodegenBackend {
217    fn name(&self) -> &'static str {
218        "llvm"
219    }
220
221    fn init(&mut self, sess: &EarlySession) -> CodegenBackendInit {
222        llvm_util::init(sess); // Make sure llvm is inited
223
224        let global_backend_features =
225            llvm_util::global_llvm_features(sess, /* for_cfg */ false);
226
227        // autodiff is based on Enzyme, a library which we might not have available, when it was
228        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
229        // an early error here and abort compilation.
230        {
231            use rustc_session::config::AutoDiff;
232
233            use crate::back::lto::enable_autodiff_settings;
234            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
235                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
236                    Ok(_) => {}
237                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
238                        sess.dcx().emit_fatal(crate::diagnostics::AutoDiffComponentMissing { err });
239                    }
240                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
241                        sess.dcx()
242                            .emit_fatal(crate::diagnostics::AutoDiffComponentUnavailable { err });
243                    }
244                }
245                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
246            }
247        }
248
249        // Intrinsics whose fallback body will not be used by the LLVM backend.
250        let replaced_intrinsics = {
251            #[rustfmt::skip]
252            let mut will_not_use_fallback = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::unchecked_funnel_shl, sym::unchecked_funnel_shr,
                sym::carrying_mul_add, sym::integer_max, sym::integer_min,
                sym::sin, sym::cos, sym::powf16, sym::powf32, sym::powf64,
                sym::exp, sym::exp2, sym::log, sym::log10, sym::log2,
                sym::floorf16, sym::ceilf16, sym::truncf16,
                sym::round_ties_even_f16, sym::roundf16, sym::sqrtf16,
                sym::powif16, sym::fmaf16, sym::copysignf16, sym::copysignf32,
                sym::copysignf64, sym::copysignf128]))vec![
253                // These are mapped to LLVM intrinsics instead.
254                sym::unchecked_funnel_shl,
255                sym::unchecked_funnel_shr,
256                sym::carrying_mul_add,
257                sym::integer_max,
258                sym::integer_min,
259
260                // Fallback via libm, but the LLVM intrinsic is used instead.
261                sym::sin,
262                sym::cos,
263                sym::powf16, sym::powf32, sym::powf64,
264                sym::exp,
265                sym::exp2,
266                sym::log,
267                sym::log10,
268                sym::log2,
269
270                // Fallback via f32 or f64, but the LLVM intrinsic is used instead.
271                sym::floorf16, sym::ceilf16, sym::truncf16,
272                sym::round_ties_even_f16, sym::roundf16,
273                sym::sqrtf16, sym::powif16,
274                sym::fmaf16,
275
276                sym::copysignf16, sym::copysignf32, sym::copysignf64, sym::copysignf128,
277            ];
278
279            if llvm_util::get_version() >= (22, 0, 0) {
280                will_not_use_fallback.push(sym::carryless_mul);
281            }
282
283            will_not_use_fallback
284        };
285
286        // `type_id_eq` is a safe choice since *all* backends use the fallback body for that. When
287        // adding more intrinsics, keep in mind that the distributed standard library is compiled
288        // with the LLVM backend but might later be included in a project built with cranelift or
289        // GCC. Adding an intrinsic here can therefore mean the fallback body is used with
290        // cranelift/GCC even if they have dedicated implementations.
291        let fallback_intrinsics = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::type_id_eq]))vec![sym::type_id_eq];
292
293        CodegenBackendInit {
294            global_backend_features,
295            replaced_intrinsics,
296            fallback_intrinsics,
297            thin_lto_supported: true,
298        }
299    }
300
301    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
302        use std::fmt::Write;
303        match req.kind {
304            PrintKind::RelocationModels => {
305                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
306                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
307                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
308                }
309                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
310            }
311            PrintKind::CodeModels => {
312                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
313                for name in &["tiny", "small", "kernel", "medium", "large"] {
314                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
315                }
316                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
317            }
318            PrintKind::TlsModels => {
319                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
320                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
321                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
322                }
323                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
324            }
325            PrintKind::StackProtectorStrategies => {
326                out.write_fmt(format_args!("Available stack protector strategies:\n    all\n        Generate stack canaries in all functions.\n\n    strong\n        Generate stack canaries in a function if it either:\n        - has a local variable of `[T; N]` type, regardless of `T` and `N`\n        - takes the address of a local variable.\n\n          (Note that a local variable being borrowed is not equivalent to its\n          address being taken: e.g. some borrows may be removed by optimization,\n          while by-value argument passing may be implemented with reference to a\n          local stack variable in the ABI.)\n\n    basic\n        Generate stack canaries in functions with local variables of `[T; N]`\n        type, where `T` is byte-sized and `N` >= 8.\n\n    none\n        Do not generate stack canaries.\n\n"))writeln!(
327                    out,
328                    r#"Available stack protector strategies:
329    all
330        Generate stack canaries in all functions.
331
332    strong
333        Generate stack canaries in a function if it either:
334        - has a local variable of `[T; N]` type, regardless of `T` and `N`
335        - takes the address of a local variable.
336
337          (Note that a local variable being borrowed is not equivalent to its
338          address being taken: e.g. some borrows may be removed by optimization,
339          while by-value argument passing may be implemented with reference to a
340          local stack variable in the ABI.)
341
342    basic
343        Generate stack canaries in functions with local variables of `[T; N]`
344        type, where `T` is byte-sized and `N` >= 8.
345
346    none
347        Do not generate stack canaries.
348"#
349                )
350                .unwrap();
351            }
352            _other => llvm_util::print(req, out, sess),
353        }
354    }
355
356    fn print_passes(&self) {
357        llvm_util::print_passes();
358    }
359
360    fn print_version(&self) {
361        llvm_util::print_version();
362    }
363
364    fn has_zstd(&self) -> bool {
365        llvm::LLVMRustLLVMHasZstdCompression()
366    }
367
368    fn has_mnemonic(&self, sess: &Session, mnemonic: &str) -> bool {
369        llvm_util::target_has_mnemonic(sess, mnemonic)
370    }
371
372    fn target_config(&self, sess: &EarlySession) -> TargetConfig {
373        target_config(sess)
374    }
375
376    fn target_cpu(&self, sess: &Session) -> String {
377        crate::llvm_util::target_cpu(sess).to_string()
378    }
379
380    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
381        use rustc_session::config::Offload;
382
383        if tcx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Device(_) => true,
    _ => false,
}matches!(o, Offload::Device(_)))
384            || tcx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Host(_) => true,
    _ => false,
}matches!(o, Offload::Host(_)))
385        {
386            match llvm::RustOffloadWrapper::get_or_init(&tcx.sess.opts.sysroot) {
387                Ok(_) => {}
388                Err(llvm::RustOffloadLibraryError::NotFound { err }) => {
389                    tcx.sess
390                        .dcx()
391                        .emit_fatal(crate::diagnostics::RustOffloadComponentMissing { err });
392                }
393                Err(llvm::RustOffloadLibraryError::LoadFailed { err }) => {
394                    tcx.sess
395                        .dcx()
396                        .emit_fatal(crate::diagnostics::RustOffloadComponentUnavailable { err });
397                }
398            }
399        }
400
401        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx))
402    }
403
404    fn join_codegen(
405        &self,
406        ongoing_codegen: Box<dyn Any>,
407        sess: &Session,
408        incr_comp_session: Option<&IncrCompSession>,
409        outputs: &OutputFilenames,
410        crate_info: &CrateInfo,
411    ) -> (CompiledModules, WorkProductMap) {
412        let (compiled_modules, work_products) = ongoing_codegen
413            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
414            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
415            .join(sess, incr_comp_session, crate_info);
416
417        if sess.opts.unstable_opts.llvm_time_trace {
418            sess.time("llvm_dump_timing_file", || {
419                let file_name = outputs.with_extension("llvm_timings.json");
420                llvm_util::time_trace_profiler_finish(&file_name);
421            });
422        }
423
424        (compiled_modules, work_products)
425    }
426
427    fn print_pass_timings(&self) {
428        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
429        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
430    }
431
432    fn print_statistics(&self) {
433        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
434        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
435    }
436
437    fn print_statistics_json(&self) -> String {
438        llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatisticsJSON(s) }).unwrap()
439    }
440
441    fn link(
442        &self,
443        sess: &Session,
444        compiled_modules: CompiledModules,
445        crate_info: CrateInfo,
446        metadata: EncodedMetadata,
447        outputs: &OutputFilenames,
448    ) {
449        use rustc_codegen_ssa::back::link::link_binary;
450
451        use crate::back::archive::LlvmArchiveBuilderBuilder;
452
453        // Run the linker on any artifacts that resulted from the LLVM run.
454        // This should produce either a finished executable or library.
455        link_binary(
456            sess,
457            &LlvmArchiveBuilderBuilder,
458            compiled_modules,
459            crate_info,
460            metadata,
461            outputs,
462            self.name(),
463        );
464    }
465}
466
467pub struct ModuleLlvm {
468    llcx: &'static mut llvm::Context,
469    llmod_raw: *const llvm::Module,
470
471    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
472    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
473    tm: ManuallyDrop<OwnedTargetMachine>,
474}
475
476unsafe impl Send for ModuleLlvm {}
477unsafe impl Sync for ModuleLlvm {}
478
479impl ModuleLlvm {
480    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
481        unsafe {
482            let llcx = llvm::LLVMContextCreate();
483            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
484            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
485            ModuleLlvm {
486                llmod_raw,
487                llcx,
488                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
489            }
490        }
491    }
492
493    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
494        unsafe {
495            let llcx = llvm::LLVMContextCreate();
496            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
497            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
498            ModuleLlvm {
499                llmod_raw,
500                llcx,
501                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess)),
502            }
503        }
504    }
505
506    fn parse(
507        cgcx: &CodegenContext,
508        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
509        name: &CStr,
510        buffer: &[u8],
511        dcx: DiagCtxtHandle<'_>,
512    ) -> Self {
513        unsafe {
514            let llcx = llvm::LLVMContextCreate();
515            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
516            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
517            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
518
519            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
520        }
521    }
522
523    fn llmod(&self) -> &llvm::Module {
524        unsafe { &*self.llmod_raw }
525    }
526}
527
528impl Drop for ModuleLlvm {
529    fn drop(&mut self) {
530        unsafe {
531            ManuallyDrop::drop(&mut self.tm);
532            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
533        }
534    }
535}