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