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    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<ThinLtoInput<Self>>,
167    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
168        back::lto::run_thin(
169            cgcx,
170            prof,
171            dcx,
172            exported_symbols_for_lto,
173            each_linked_rlib_for_lto,
174            modules,
175        )
176    }
177    fn optimize(
178        cgcx: &CodegenContext,
179        prof: &SelfProfilerRef,
180        shared_emitter: &SharedEmitter,
181        module: &mut ModuleCodegen<Self::Module>,
182        config: &ModuleConfig,
183    ) {
184        back::write::optimize(cgcx, prof, shared_emitter, module, config)
185    }
186    fn optimize_and_codegen_thin(
187        cgcx: &CodegenContext,
188        prof: &SelfProfilerRef,
189        shared_emitter: &SharedEmitter,
190        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
191        thin: ThinModule<Self>,
192    ) -> CompiledModule {
193        back::lto::optimize_and_codegen_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
194    }
195    fn codegen(
196        cgcx: &CodegenContext,
197        prof: &SelfProfilerRef,
198        shared_emitter: &SharedEmitter,
199        module: ModuleCodegen<Self::Module>,
200        config: &ModuleConfig,
201    ) -> CompiledModule {
202        back::write::codegen(cgcx, prof, shared_emitter, module, config)
203    }
204    fn serialize_module(module: Self::Module, is_thin: bool) -> Self::ModuleBuffer {
205        back::lto::ModuleBuffer::new(module.llmod(), is_thin)
206    }
207}
208
209impl LlvmCodegenBackend {
210    pub fn new() -> Box<dyn CodegenBackend> {
211        Box::new(LlvmCodegenBackend(()))
212    }
213}
214
215impl CodegenBackend for LlvmCodegenBackend {
216    fn name(&self) -> &'static str {
217        "llvm"
218    }
219
220    fn init(&self, sess: &Session) {
221        llvm_util::init(sess); // Make sure llvm is inited
222
223        // autodiff is based on Enzyme, a library which we might not have available, when it was
224        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
225        // an early error here and abort compilation.
226        {
227            use rustc_session::config::AutoDiff;
228
229            use crate::back::lto::enable_autodiff_settings;
230            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
231                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
232                    Ok(_) => {}
233                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
234                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentMissing { err });
235                    }
236                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
237                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentUnavailable { err });
238                    }
239                }
240                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
241            }
242        }
243    }
244
245    fn provide(&self, providers: &mut Providers) {
246        providers.queries.global_backend_features =
247            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
248    }
249
250    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
251        use std::fmt::Write;
252        match req.kind {
253            PrintKind::RelocationModels => {
254                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
255                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
256                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
257                }
258                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
259            }
260            PrintKind::CodeModels => {
261                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
262                for name in &["tiny", "small", "kernel", "medium", "large"] {
263                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
264                }
265                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
266            }
267            PrintKind::TlsModels => {
268                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
269                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
270                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
271                }
272                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
273            }
274            PrintKind::StackProtectorStrategies => {
275                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!(
276                    out,
277                    r#"Available stack protector strategies:
278    all
279        Generate stack canaries in all functions.
280
281    strong
282        Generate stack canaries in a function if it either:
283        - has a local variable of `[T; N]` type, regardless of `T` and `N`
284        - takes the address of a local variable.
285
286          (Note that a local variable being borrowed is not equivalent to its
287          address being taken: e.g. some borrows may be removed by optimization,
288          while by-value argument passing may be implemented with reference to a
289          local stack variable in the ABI.)
290
291    basic
292        Generate stack canaries in functions with local variables of `[T; N]`
293        type, where `T` is byte-sized and `N` >= 8.
294
295    none
296        Do not generate stack canaries.
297"#
298                )
299                .unwrap();
300            }
301            _other => llvm_util::print(req, out, sess),
302        }
303    }
304
305    fn print_passes(&self) {
306        llvm_util::print_passes();
307    }
308
309    fn print_version(&self) {
310        llvm_util::print_version();
311    }
312
313    fn has_zstd(&self) -> bool {
314        llvm::LLVMRustLLVMHasZstdCompression()
315    }
316
317    fn target_config(&self, sess: &Session) -> TargetConfig {
318        target_config(sess)
319    }
320
321    fn replaced_intrinsics(&self) -> Vec<Symbol> {
322        let mut will_not_use_fallback =
323            ::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];
324
325        if llvm_util::get_version() >= (22, 0, 0) {
326            will_not_use_fallback.push(sym::carryless_mul);
327        }
328
329        will_not_use_fallback
330    }
331
332    fn target_cpu(&self, sess: &Session) -> String {
333        crate::llvm_util::target_cpu(sess).to_string()
334    }
335
336    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>, crate_info: &CrateInfo) -> Box<dyn Any> {
337        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, crate_info))
338    }
339
340    fn join_codegen(
341        &self,
342        ongoing_codegen: Box<dyn Any>,
343        sess: &Session,
344        outputs: &OutputFilenames,
345    ) -> (CompiledModules, FxIndexMap<WorkProductId, WorkProduct>) {
346        let (compiled_modules, work_products) = ongoing_codegen
347            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
348            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
349            .join(sess);
350
351        if sess.opts.unstable_opts.llvm_time_trace {
352            sess.time("llvm_dump_timing_file", || {
353                let file_name = outputs.with_extension("llvm_timings.json");
354                llvm_util::time_trace_profiler_finish(&file_name);
355            });
356        }
357
358        (compiled_modules, work_products)
359    }
360
361    fn print_pass_timings(&self) {
362        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
363        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
364    }
365
366    fn print_statistics(&self) {
367        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
368        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
369    }
370
371    fn link(
372        &self,
373        sess: &Session,
374        compiled_modules: CompiledModules,
375        crate_info: CrateInfo,
376        metadata: EncodedMetadata,
377        outputs: &OutputFilenames,
378    ) {
379        use rustc_codegen_ssa::back::link::link_binary;
380
381        use crate::back::archive::LlvmArchiveBuilderBuilder;
382
383        // Run the linker on any artifacts that resulted from the LLVM run.
384        // This should produce either a finished executable or library.
385        link_binary(
386            sess,
387            &LlvmArchiveBuilderBuilder,
388            compiled_modules,
389            crate_info,
390            metadata,
391            outputs,
392            self.name(),
393        );
394    }
395}
396
397pub struct ModuleLlvm {
398    llcx: &'static mut llvm::Context,
399    llmod_raw: *const llvm::Module,
400
401    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
402    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
403    tm: ManuallyDrop<OwnedTargetMachine>,
404}
405
406unsafe impl Send for ModuleLlvm {}
407unsafe impl Sync for ModuleLlvm {}
408
409impl ModuleLlvm {
410    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
411        unsafe {
412            let llcx = llvm::LLVMContextCreate();
413            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
414            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
415            ModuleLlvm {
416                llmod_raw,
417                llcx,
418                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
419            }
420        }
421    }
422
423    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
424        unsafe {
425            let llcx = llvm::LLVMContextCreate();
426            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
427            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
428            ModuleLlvm {
429                llmod_raw,
430                llcx,
431                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
432            }
433        }
434    }
435
436    fn parse(
437        cgcx: &CodegenContext,
438        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
439        name: &CStr,
440        buffer: &[u8],
441        dcx: DiagCtxtHandle<'_>,
442    ) -> Self {
443        unsafe {
444            let llcx = llvm::LLVMContextCreate();
445            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
446            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
447            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
448
449            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
450        }
451    }
452
453    fn llmod(&self) -> &llvm::Module {
454        unsafe { &*self.llmod_raw }
455    }
456}
457
458impl Drop for ModuleLlvm {
459    fn drop(&mut self) {
460        unsafe {
461            ManuallyDrop::drop(&mut self.tm);
462            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
463        }
464    }
465}