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::{SerializedModule, ThinModule};
29use rustc_codegen_ssa::back::write::{
30    CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryConfig,
31    TargetMachineFactoryFn,
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    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    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
115        base::compile_codegen_unit(tcx, cgu_name)
116    }
117}
118
119impl WriteBackendMethods for LlvmCodegenBackend {
120    type Module = ModuleLlvm;
121    type ModuleBuffer = back::lto::ModuleBuffer;
122    type TargetMachine = OwnedTargetMachine;
123    type ThinData = back::lto::ThinData;
124    fn thread_profiler() -> Box<dyn Any> {
125        Box::new(TimeTraceProfiler::new())
126    }
127    fn target_machine_factory(
128        &self,
129        sess: &Session,
130        optlvl: OptLevel,
131        target_features: &[String],
132    ) -> TargetMachineFactoryFn<Self> {
133        back::write::target_machine_factory(sess, optlvl, target_features)
134    }
135    fn optimize_and_codegen_fat_lto(
136        cgcx: &CodegenContext,
137        prof: &SelfProfilerRef,
138        shared_emitter: &SharedEmitter,
139        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
140        exported_symbols_for_lto: &[String],
141        each_linked_rlib_for_lto: &[PathBuf],
142        modules: Vec<FatLtoInput<Self>>,
143    ) -> CompiledModule {
144        let mut module = back::lto::run_fat(
145            cgcx,
146            prof,
147            shared_emitter,
148            tm_factory,
149            exported_symbols_for_lto,
150            each_linked_rlib_for_lto,
151            modules,
152        );
153
154        let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
155        let dcx = dcx.handle();
156        back::lto::run_pass_manager(cgcx, prof, dcx, &mut module, false);
157
158        back::write::codegen(cgcx, prof, shared_emitter, module, &cgcx.module_config)
159    }
160    fn run_thin_lto(
161        cgcx: &CodegenContext,
162        prof: &SelfProfilerRef,
163        dcx: DiagCtxtHandle<'_>,
164        exported_symbols_for_lto: &[String],
165        each_linked_rlib_for_lto: &[PathBuf],
166        modules: Vec<(String, Self::ModuleBuffer)>,
167        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
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            cached_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 target_config(&self, sess: &Session) -> TargetConfig {
320        target_config(sess)
321    }
322
323    fn replaced_intrinsics(&self) -> Vec<Symbol> {
324        let mut will_not_use_fallback =
325            ::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];
326
327        if llvm_util::get_version() >= (22, 0, 0) {
328            will_not_use_fallback.push(sym::carryless_mul);
329        }
330
331        will_not_use_fallback
332    }
333
334    fn target_cpu(&self, sess: &Session) -> String {
335        crate::llvm_util::target_cpu(sess).to_string()
336    }
337
338    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>, crate_info: &CrateInfo) -> Box<dyn Any> {
339        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, crate_info))
340    }
341
342    fn join_codegen(
343        &self,
344        ongoing_codegen: Box<dyn Any>,
345        sess: &Session,
346        outputs: &OutputFilenames,
347    ) -> (CompiledModules, FxIndexMap<WorkProductId, WorkProduct>) {
348        let (compiled_modules, work_products) = ongoing_codegen
349            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
350            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
351            .join(sess);
352
353        if sess.opts.unstable_opts.llvm_time_trace {
354            sess.time("llvm_dump_timing_file", || {
355                let file_name = outputs.with_extension("llvm_timings.json");
356                llvm_util::time_trace_profiler_finish(&file_name);
357            });
358        }
359
360        (compiled_modules, work_products)
361    }
362
363    fn print_pass_timings(&self) {
364        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
365        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
366    }
367
368    fn print_statistics(&self) {
369        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
370        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
371    }
372
373    fn link(
374        &self,
375        sess: &Session,
376        compiled_modules: CompiledModules,
377        crate_info: CrateInfo,
378        metadata: EncodedMetadata,
379        outputs: &OutputFilenames,
380    ) {
381        use rustc_codegen_ssa::back::link::link_binary;
382
383        use crate::back::archive::LlvmArchiveBuilderBuilder;
384
385        // Run the linker on any artifacts that resulted from the LLVM run.
386        // This should produce either a finished executable or library.
387        link_binary(
388            sess,
389            &LlvmArchiveBuilderBuilder,
390            compiled_modules,
391            crate_info,
392            metadata,
393            outputs,
394            self.name(),
395        );
396    }
397}
398
399pub struct ModuleLlvm {
400    llcx: &'static mut llvm::Context,
401    llmod_raw: *const llvm::Module,
402
403    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
404    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
405    tm: ManuallyDrop<OwnedTargetMachine>,
406}
407
408unsafe impl Send for ModuleLlvm {}
409unsafe impl Sync for ModuleLlvm {}
410
411impl ModuleLlvm {
412    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
413        unsafe {
414            let llcx = llvm::LLVMContextCreate();
415            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
416            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
417            ModuleLlvm {
418                llmod_raw,
419                llcx,
420                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
421            }
422        }
423    }
424
425    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
426        unsafe {
427            let llcx = llvm::LLVMContextCreate();
428            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
429            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
430            ModuleLlvm {
431                llmod_raw,
432                llcx,
433                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
434            }
435        }
436    }
437
438    fn parse(
439        cgcx: &CodegenContext,
440        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
441        name: &CStr,
442        buffer: &[u8],
443        dcx: DiagCtxtHandle<'_>,
444    ) -> Self {
445        unsafe {
446            let llcx = llvm::LLVMContextCreate();
447            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
448            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
449            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
450
451            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
452        }
453    }
454
455    fn llmod(&self) -> &llvm::Module {
456        unsafe { &*self.llmod_raw }
457    }
458}
459
460impl Drop for ModuleLlvm {
461    fn drop(&mut self) {
462        unsafe {
463            ManuallyDrop::drop(&mut self.tm);
464            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
465        }
466    }
467}