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