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#![cfg_attr(bootstrap, feature(assert_matches))]
9#![cfg_attr(bootstrap, feature(if_let_guard))]
10#![feature(extern_types)]
11#![feature(file_buffered)]
12#![feature(impl_trait_in_assoc_type)]
13#![feature(iter_intersperse)]
14#![feature(macro_derive)]
15#![feature(once_cell_try)]
16#![feature(trim_prefix_suffix)]
17#![feature(try_blocks)]
18// tidy-alphabetical-end
19
20use std::any::Any;
21use std::ffi::CStr;
22use std::mem::ManuallyDrop;
23use std::path::PathBuf;
24
25use back::owned_target_machine::OwnedTargetMachine;
26use back::write::{create_informational_target_machine, create_target_machine};
27use context::SimpleCx;
28use llvm_util::target_config;
29use rustc_ast::expand::allocator::AllocatorMethod;
30use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
31use rustc_codegen_ssa::back::write::{
32    CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryConfig,
33    TargetMachineFactoryFn,
34};
35use rustc_codegen_ssa::traits::*;
36use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
37use rustc_data_structures::fx::FxIndexMap;
38use rustc_data_structures::profiling::SelfProfilerRef;
39use rustc_errors::{DiagCtxt, DiagCtxtHandle};
40use rustc_metadata::EncodedMetadata;
41use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
42use rustc_middle::ty::TyCtxt;
43use rustc_middle::util::Providers;
44use rustc_session::Session;
45use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
46use rustc_span::{Symbol, sym};
47use rustc_target::spec::{RelocModel, TlsModel};
48
49use crate::llvm::ToLlvmBool;
50
51mod abi;
52mod allocator;
53mod asm;
54mod attributes;
55mod back;
56mod base;
57mod builder;
58mod callee;
59mod common;
60mod consts;
61mod context;
62mod coverageinfo;
63mod debuginfo;
64mod declare;
65mod errors;
66mod intrinsic;
67mod llvm;
68mod llvm_util;
69mod macros;
70mod mono_item;
71mod type_;
72mod type_of;
73mod typetree;
74mod va_arg;
75mod value;
76
77pub(crate) use macros::TryFromU32;
78
79#[derive(#[automatically_derived]
impl ::core::clone::Clone for LlvmCodegenBackend {
    #[inline]
    fn clone(&self) -> LlvmCodegenBackend {
        LlvmCodegenBackend(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
80pub struct LlvmCodegenBackend(());
81
82struct TimeTraceProfiler {
83    enabled: bool,
84}
85
86impl TimeTraceProfiler {
87    fn new(enabled: bool) -> Self {
88        if enabled {
89            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
90        }
91        TimeTraceProfiler { enabled }
92    }
93}
94
95impl Drop for TimeTraceProfiler {
96    fn drop(&mut self) {
97        if self.enabled {
98            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
99        }
100    }
101}
102
103impl ExtraBackendMethods for LlvmCodegenBackend {
104    fn codegen_allocator<'tcx>(
105        &self,
106        tcx: TyCtxt<'tcx>,
107        module_name: &str,
108        methods: &[AllocatorMethod],
109    ) -> ModuleLlvm {
110        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
111        let cx =
112            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
113        unsafe {
114            allocator::codegen(tcx, cx, module_name, methods);
115        }
116        module_llvm
117    }
118    fn compile_codegen_unit(
119        &self,
120        tcx: TyCtxt<'_>,
121        cgu_name: Symbol,
122    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
123        base::compile_codegen_unit(tcx, cgu_name)
124    }
125    fn target_machine_factory(
126        &self,
127        sess: &Session,
128        optlvl: OptLevel,
129        target_features: &[String],
130    ) -> TargetMachineFactoryFn<Self> {
131        back::write::target_machine_factory(sess, optlvl, target_features)
132    }
133
134    fn spawn_named_thread<F, T>(
135        time_trace: bool,
136        name: String,
137        f: F,
138    ) -> std::io::Result<std::thread::JoinHandle<T>>
139    where
140        F: FnOnce() -> T,
141        F: Send + 'static,
142        T: Send + 'static,
143    {
144        std::thread::Builder::new().name(name).spawn(move || {
145            let _profiler = TimeTraceProfiler::new(time_trace);
146            f()
147        })
148    }
149}
150
151impl WriteBackendMethods for LlvmCodegenBackend {
152    type Module = ModuleLlvm;
153    type ModuleBuffer = back::lto::ModuleBuffer;
154    type TargetMachine = OwnedTargetMachine;
155    type ThinData = back::lto::ThinData;
156    fn print_pass_timings(&self) {
157        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
158        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
159    }
160    fn print_statistics(&self) {
161        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
162        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
163    }
164    fn run_and_optimize_fat_lto(
165        cgcx: &CodegenContext,
166        prof: &SelfProfilerRef,
167        shared_emitter: &SharedEmitter,
168        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
169        exported_symbols_for_lto: &[String],
170        each_linked_rlib_for_lto: &[PathBuf],
171        modules: Vec<FatLtoInput<Self>>,
172    ) -> ModuleCodegen<Self::Module> {
173        let mut module = back::lto::run_fat(
174            cgcx,
175            prof,
176            shared_emitter,
177            tm_factory,
178            exported_symbols_for_lto,
179            each_linked_rlib_for_lto,
180            modules,
181        );
182
183        let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
184        let dcx = dcx.handle();
185        back::lto::run_pass_manager(cgcx, prof, dcx, &mut module, false);
186
187        module
188    }
189    fn run_thin_lto(
190        cgcx: &CodegenContext,
191        prof: &SelfProfilerRef,
192        dcx: DiagCtxtHandle<'_>,
193        exported_symbols_for_lto: &[String],
194        each_linked_rlib_for_lto: &[PathBuf],
195        modules: Vec<(String, Self::ModuleBuffer)>,
196        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
197    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
198        back::lto::run_thin(
199            cgcx,
200            prof,
201            dcx,
202            exported_symbols_for_lto,
203            each_linked_rlib_for_lto,
204            modules,
205            cached_modules,
206        )
207    }
208    fn optimize(
209        cgcx: &CodegenContext,
210        prof: &SelfProfilerRef,
211        shared_emitter: &SharedEmitter,
212        module: &mut ModuleCodegen<Self::Module>,
213        config: &ModuleConfig,
214    ) {
215        back::write::optimize(cgcx, prof, shared_emitter, module, config)
216    }
217    fn optimize_thin(
218        cgcx: &CodegenContext,
219        prof: &SelfProfilerRef,
220        shared_emitter: &SharedEmitter,
221        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
222        thin: ThinModule<Self>,
223    ) -> ModuleCodegen<Self::Module> {
224        back::lto::optimize_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
225    }
226    fn codegen(
227        cgcx: &CodegenContext,
228        prof: &SelfProfilerRef,
229        shared_emitter: &SharedEmitter,
230        module: ModuleCodegen<Self::Module>,
231        config: &ModuleConfig,
232    ) -> CompiledModule {
233        back::write::codegen(cgcx, prof, shared_emitter, module, config)
234    }
235    fn serialize_module(module: Self::Module, is_thin: bool) -> Self::ModuleBuffer {
236        back::lto::ModuleBuffer::new(module.llmod(), is_thin)
237    }
238}
239
240impl LlvmCodegenBackend {
241    pub fn new() -> Box<dyn CodegenBackend> {
242        Box::new(LlvmCodegenBackend(()))
243    }
244}
245
246impl CodegenBackend for LlvmCodegenBackend {
247    fn name(&self) -> &'static str {
248        "llvm"
249    }
250
251    fn init(&self, sess: &Session) {
252        llvm_util::init(sess); // Make sure llvm is inited
253
254        // autodiff is based on Enzyme, a library which we might not have available, when it was
255        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
256        // an early error here and abort compilation.
257        {
258            use rustc_session::config::AutoDiff;
259
260            use crate::back::lto::enable_autodiff_settings;
261            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
262                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
263                    Ok(_) => {}
264                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
265                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentMissing { err });
266                    }
267                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
268                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentUnavailable { err });
269                    }
270                }
271                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
272            }
273        }
274    }
275
276    fn provide(&self, providers: &mut Providers) {
277        providers.queries.global_backend_features =
278            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
279    }
280
281    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
282        use std::fmt::Write;
283        match req.kind {
284            PrintKind::RelocationModels => {
285                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
286                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
287                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
288                }
289                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
290            }
291            PrintKind::CodeModels => {
292                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
293                for name in &["tiny", "small", "kernel", "medium", "large"] {
294                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
295                }
296                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
297            }
298            PrintKind::TlsModels => {
299                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
300                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
301                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
302                }
303                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
304            }
305            PrintKind::StackProtectorStrategies => {
306                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!(
307                    out,
308                    r#"Available stack protector strategies:
309    all
310        Generate stack canaries in all functions.
311
312    strong
313        Generate stack canaries in a function if it either:
314        - has a local variable of `[T; N]` type, regardless of `T` and `N`
315        - takes the address of a local variable.
316
317          (Note that a local variable being borrowed is not equivalent to its
318          address being taken: e.g. some borrows may be removed by optimization,
319          while by-value argument passing may be implemented with reference to a
320          local stack variable in the ABI.)
321
322    basic
323        Generate stack canaries in functions with local variables of `[T; N]`
324        type, where `T` is byte-sized and `N` >= 8.
325
326    none
327        Do not generate stack canaries.
328"#
329                )
330                .unwrap();
331            }
332            _other => llvm_util::print(req, out, sess),
333        }
334    }
335
336    fn print_passes(&self) {
337        llvm_util::print_passes();
338    }
339
340    fn print_version(&self) {
341        llvm_util::print_version();
342    }
343
344    fn has_zstd(&self) -> bool {
345        llvm::LLVMRustLLVMHasZstdCompression()
346    }
347
348    fn target_config(&self, sess: &Session) -> TargetConfig {
349        target_config(sess)
350    }
351
352    fn replaced_intrinsics(&self) -> Vec<Symbol> {
353        let mut will_not_use_fallback =
354            ::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];
355
356        if llvm_util::get_version() >= (22, 0, 0) {
357            will_not_use_fallback.push(sym::carryless_mul);
358        }
359
360        will_not_use_fallback
361    }
362
363    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
364        Box::new(rustc_codegen_ssa::base::codegen_crate(
365            LlvmCodegenBackend(()),
366            tcx,
367            crate::llvm_util::target_cpu(tcx.sess).to_string(),
368        ))
369    }
370
371    fn join_codegen(
372        &self,
373        ongoing_codegen: Box<dyn Any>,
374        sess: &Session,
375        outputs: &OutputFilenames,
376    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
377        let (codegen_results, work_products) = ongoing_codegen
378            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
379            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
380            .join(sess);
381
382        if sess.opts.unstable_opts.llvm_time_trace {
383            sess.time("llvm_dump_timing_file", || {
384                let file_name = outputs.with_extension("llvm_timings.json");
385                llvm_util::time_trace_profiler_finish(&file_name);
386            });
387        }
388
389        (codegen_results, work_products)
390    }
391
392    fn link(
393        &self,
394        sess: &Session,
395        codegen_results: CodegenResults,
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            codegen_results,
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}