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#![allow(internal_features)]
9#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10#![doc(rust_logo)]
11#![feature(assert_matches)]
12#![feature(extern_types)]
13#![feature(file_buffered)]
14#![feature(if_let_guard)]
15#![feature(impl_trait_in_assoc_type)]
16#![feature(iter_intersperse)]
17#![feature(rustdoc_internals)]
18#![feature(slice_as_array)]
19#![feature(try_blocks)]
20// tidy-alphabetical-end
21
22use std::any::Any;
23use std::ffi::CStr;
24use std::mem::ManuallyDrop;
25use std::path::PathBuf;
26
27use back::owned_target_machine::OwnedTargetMachine;
28use back::write::{create_informational_target_machine, create_target_machine};
29use context::SimpleCx;
30use errors::ParseTargetMachineConfig;
31use llvm_util::target_config;
32use rustc_ast::expand::allocator::AllocatorKind;
33use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
34use rustc_codegen_ssa::back::write::{
35    CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
36};
37use rustc_codegen_ssa::traits::*;
38use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
39use rustc_data_structures::fx::FxIndexMap;
40use rustc_errors::DiagCtxtHandle;
41use rustc_metadata::EncodedMetadata;
42use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
43use rustc_middle::ty::TyCtxt;
44use rustc_middle::util::Providers;
45use rustc_session::Session;
46use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
47use rustc_span::Symbol;
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 mono_item;
68mod type_;
69mod type_of;
70mod va_arg;
71mod value;
72
73rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
74
75#[derive(Clone)]
76pub struct LlvmCodegenBackend(());
77
78struct TimeTraceProfiler {
79    enabled: bool,
80}
81
82impl TimeTraceProfiler {
83    fn new(enabled: bool) -> Self {
84        if enabled {
85            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
86        }
87        TimeTraceProfiler { enabled }
88    }
89}
90
91impl Drop for TimeTraceProfiler {
92    fn drop(&mut self) {
93        if self.enabled {
94            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
95        }
96    }
97}
98
99impl ExtraBackendMethods for LlvmCodegenBackend {
100    fn codegen_allocator<'tcx>(
101        &self,
102        tcx: TyCtxt<'tcx>,
103        module_name: &str,
104        kind: AllocatorKind,
105        alloc_error_handler_kind: AllocatorKind,
106    ) -> ModuleLlvm {
107        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
108        let cx =
109            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
110        unsafe {
111            allocator::codegen(tcx, cx, module_name, kind, alloc_error_handler_kind);
112        }
113        module_llvm
114    }
115    fn compile_codegen_unit(
116        &self,
117        tcx: TyCtxt<'_>,
118        cgu_name: Symbol,
119    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
120        base::compile_codegen_unit(tcx, cgu_name)
121    }
122    fn target_machine_factory(
123        &self,
124        sess: &Session,
125        optlvl: OptLevel,
126        target_features: &[String],
127    ) -> TargetMachineFactoryFn<Self> {
128        back::write::target_machine_factory(sess, optlvl, target_features)
129    }
130
131    fn spawn_named_thread<F, T>(
132        time_trace: bool,
133        name: String,
134        f: F,
135    ) -> std::io::Result<std::thread::JoinHandle<T>>
136    where
137        F: FnOnce() -> T,
138        F: Send + 'static,
139        T: Send + 'static,
140    {
141        std::thread::Builder::new().name(name).spawn(move || {
142            let _profiler = TimeTraceProfiler::new(time_trace);
143            f()
144        })
145    }
146}
147
148impl WriteBackendMethods for LlvmCodegenBackend {
149    type Module = ModuleLlvm;
150    type ModuleBuffer = back::lto::ModuleBuffer;
151    type TargetMachine = OwnedTargetMachine;
152    type TargetMachineError = crate::errors::LlvmError<'static>;
153    type ThinData = back::lto::ThinData;
154    type ThinBuffer = back::lto::ThinBuffer;
155    fn print_pass_timings(&self) {
156        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
157        print!("{timings}");
158    }
159    fn print_statistics(&self) {
160        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
161        print!("{stats}");
162    }
163    fn run_and_optimize_fat_lto(
164        cgcx: &CodegenContext<Self>,
165        exported_symbols_for_lto: &[String],
166        each_linked_rlib_for_lto: &[PathBuf],
167        modules: Vec<FatLtoInput<Self>>,
168    ) -> ModuleCodegen<Self::Module> {
169        let mut module =
170            back::lto::run_fat(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, modules);
171
172        let dcx = cgcx.create_dcx();
173        let dcx = dcx.handle();
174        back::lto::run_pass_manager(cgcx, dcx, &mut module, false);
175
176        module
177    }
178    fn run_thin_lto(
179        cgcx: &CodegenContext<Self>,
180        exported_symbols_for_lto: &[String],
181        each_linked_rlib_for_lto: &[PathBuf],
182        modules: Vec<(String, Self::ThinBuffer)>,
183        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
184    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
185        back::lto::run_thin(
186            cgcx,
187            exported_symbols_for_lto,
188            each_linked_rlib_for_lto,
189            modules,
190            cached_modules,
191        )
192    }
193    fn optimize(
194        cgcx: &CodegenContext<Self>,
195        dcx: DiagCtxtHandle<'_>,
196        module: &mut ModuleCodegen<Self::Module>,
197        config: &ModuleConfig,
198    ) {
199        back::write::optimize(cgcx, dcx, module, config)
200    }
201    fn optimize_thin(
202        cgcx: &CodegenContext<Self>,
203        thin: ThinModule<Self>,
204    ) -> ModuleCodegen<Self::Module> {
205        back::lto::optimize_thin_module(thin, cgcx)
206    }
207    fn codegen(
208        cgcx: &CodegenContext<Self>,
209        module: ModuleCodegen<Self::Module>,
210        config: &ModuleConfig,
211    ) -> CompiledModule {
212        back::write::codegen(cgcx, module, config)
213    }
214    fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
215        back::lto::prepare_thin(module)
216    }
217    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
218        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
219    }
220}
221
222impl LlvmCodegenBackend {
223    pub fn new() -> Box<dyn CodegenBackend> {
224        Box::new(LlvmCodegenBackend(()))
225    }
226}
227
228impl CodegenBackend for LlvmCodegenBackend {
229    fn locale_resource(&self) -> &'static str {
230        crate::DEFAULT_LOCALE_RESOURCE
231    }
232
233    fn init(&self, sess: &Session) {
234        llvm_util::init(sess); // Make sure llvm is inited
235    }
236
237    fn provide(&self, providers: &mut Providers) {
238        providers.global_backend_features =
239            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true, false)
240    }
241
242    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
243        use std::fmt::Write;
244        match req.kind {
245            PrintKind::RelocationModels => {
246                writeln!(out, "Available relocation models:").unwrap();
247                for name in &[
248                    "static",
249                    "pic",
250                    "pie",
251                    "dynamic-no-pic",
252                    "ropi",
253                    "rwpi",
254                    "ropi-rwpi",
255                    "default",
256                ] {
257                    writeln!(out, "    {name}").unwrap();
258                }
259                writeln!(out).unwrap();
260            }
261            PrintKind::CodeModels => {
262                writeln!(out, "Available code models:").unwrap();
263                for name in &["tiny", "small", "kernel", "medium", "large"] {
264                    writeln!(out, "    {name}").unwrap();
265                }
266                writeln!(out).unwrap();
267            }
268            PrintKind::TlsModels => {
269                writeln!(out, "Available TLS models:").unwrap();
270                for name in
271                    &["global-dynamic", "local-dynamic", "initial-exec", "local-exec", "emulated"]
272                {
273                    writeln!(out, "    {name}").unwrap();
274                }
275                writeln!(out).unwrap();
276            }
277            PrintKind::StackProtectorStrategies => {
278                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 target_config(&self, sess: &Session) -> TargetConfig {
317        target_config(sess)
318    }
319
320    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
321        Box::new(rustc_codegen_ssa::base::codegen_crate(
322            LlvmCodegenBackend(()),
323            tcx,
324            crate::llvm_util::target_cpu(tcx.sess).to_string(),
325        ))
326    }
327
328    fn join_codegen(
329        &self,
330        ongoing_codegen: Box<dyn Any>,
331        sess: &Session,
332        outputs: &OutputFilenames,
333    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
334        let (codegen_results, work_products) = ongoing_codegen
335            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
336            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
337            .join(sess);
338
339        if sess.opts.unstable_opts.llvm_time_trace {
340            sess.time("llvm_dump_timing_file", || {
341                let file_name = outputs.with_extension("llvm_timings.json");
342                llvm_util::time_trace_profiler_finish(&file_name);
343            });
344        }
345
346        (codegen_results, work_products)
347    }
348
349    fn link(
350        &self,
351        sess: &Session,
352        codegen_results: CodegenResults,
353        metadata: EncodedMetadata,
354        outputs: &OutputFilenames,
355    ) {
356        use rustc_codegen_ssa::back::link::link_binary;
357
358        use crate::back::archive::LlvmArchiveBuilderBuilder;
359
360        // Run the linker on any artifacts that resulted from the LLVM run.
361        // This should produce either a finished executable or library.
362        link_binary(sess, &LlvmArchiveBuilderBuilder, codegen_results, metadata, outputs);
363    }
364}
365
366pub struct ModuleLlvm {
367    llcx: &'static mut llvm::Context,
368    llmod_raw: *const llvm::Module,
369
370    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
371    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
372    tm: ManuallyDrop<OwnedTargetMachine>,
373}
374
375unsafe impl Send for ModuleLlvm {}
376unsafe impl Sync for ModuleLlvm {}
377
378impl ModuleLlvm {
379    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
380        unsafe {
381            let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
382            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
383            ModuleLlvm {
384                llmod_raw,
385                llcx,
386                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
387            }
388        }
389    }
390
391    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
392        unsafe {
393            let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
394            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
395            ModuleLlvm {
396                llmod_raw,
397                llcx,
398                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
399            }
400        }
401    }
402
403    fn tm_from_cgcx(
404        cgcx: &CodegenContext<LlvmCodegenBackend>,
405        name: &str,
406        dcx: DiagCtxtHandle<'_>,
407    ) -> OwnedTargetMachine {
408        let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
409        match (cgcx.tm_factory)(tm_factory_config) {
410            Ok(m) => m,
411            Err(e) => {
412                dcx.emit_fatal(ParseTargetMachineConfig(e));
413            }
414        }
415    }
416
417    fn parse(
418        cgcx: &CodegenContext<LlvmCodegenBackend>,
419        name: &CStr,
420        buffer: &[u8],
421        dcx: DiagCtxtHandle<'_>,
422    ) -> Self {
423        unsafe {
424            let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
425            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
426            let tm = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx);
427
428            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
429        }
430    }
431
432    fn llmod(&self) -> &llvm::Module {
433        unsafe { &*self.llmod_raw }
434    }
435}
436
437impl Drop for ModuleLlvm {
438    fn drop(&mut self) {
439        unsafe {
440            ManuallyDrop::drop(&mut self.tm);
441            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
442        }
443    }
444}