1#![cfg_attr(bootstrap, feature(slice_as_array))]
9#![feature(assert_matches)]
10#![feature(extern_types)]
11#![feature(file_buffered)]
12#![feature(if_let_guard)]
13#![feature(impl_trait_in_assoc_type)]
14#![feature(iter_intersperse)]
15#![feature(macro_derive)]
16#![feature(trim_prefix_suffix)]
17#![feature(try_blocks)]
18use 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 errors::ParseTargetMachineConfig;
29use llvm_util::target_config;
30use rustc_ast::expand::allocator::AllocatorMethod;
31use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
32use rustc_codegen_ssa::back::write::{
33 CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
34};
35use rustc_codegen_ssa::traits::*;
36use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
37use rustc_data_structures::fx::FxIndexMap;
38use rustc_errors::DiagCtxtHandle;
39use rustc_metadata::EncodedMetadata;
40use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
41use rustc_middle::ty::TyCtxt;
42use rustc_middle::util::Providers;
43use rustc_session::Session;
44use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
45use rustc_span::Symbol;
46use rustc_target::spec::{RelocModel, TlsModel};
47
48use crate::llvm::ToLlvmBool;
49
50mod abi;
51mod allocator;
52mod asm;
53mod attributes;
54mod back;
55mod base;
56mod builder;
57mod callee;
58mod common;
59mod consts;
60mod context;
61mod coverageinfo;
62mod debuginfo;
63mod declare;
64mod errors;
65mod intrinsic;
66mod llvm;
67mod llvm_util;
68mod macros;
69mod mono_item;
70mod type_;
71mod type_of;
72mod typetree;
73mod va_arg;
74mod value;
75
76rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
77
78pub(crate) use macros::TryFromU32;
79
80#[derive(Clone)]
81pub struct LlvmCodegenBackend(());
82
83struct TimeTraceProfiler {
84 enabled: bool,
85}
86
87impl TimeTraceProfiler {
88 fn new(enabled: bool) -> Self {
89 if enabled {
90 unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
91 }
92 TimeTraceProfiler { enabled }
93 }
94}
95
96impl Drop for TimeTraceProfiler {
97 fn drop(&mut self) {
98 if self.enabled {
99 unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
100 }
101 }
102}
103
104impl ExtraBackendMethods for LlvmCodegenBackend {
105 fn codegen_allocator<'tcx>(
106 &self,
107 tcx: TyCtxt<'tcx>,
108 module_name: &str,
109 methods: &[AllocatorMethod],
110 ) -> ModuleLlvm {
111 let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
112 let cx =
113 SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
114 unsafe {
115 allocator::codegen(tcx, cx, module_name, methods);
116 }
117 module_llvm
118 }
119 fn compile_codegen_unit(
120 &self,
121 tcx: TyCtxt<'_>,
122 cgu_name: Symbol,
123 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
124 base::compile_codegen_unit(tcx, cgu_name)
125 }
126 fn target_machine_factory(
127 &self,
128 sess: &Session,
129 optlvl: OptLevel,
130 target_features: &[String],
131 ) -> TargetMachineFactoryFn<Self> {
132 back::write::target_machine_factory(sess, optlvl, target_features)
133 }
134
135 fn spawn_named_thread<F, T>(
136 time_trace: bool,
137 name: String,
138 f: F,
139 ) -> std::io::Result<std::thread::JoinHandle<T>>
140 where
141 F: FnOnce() -> T,
142 F: Send + 'static,
143 T: Send + 'static,
144 {
145 std::thread::Builder::new().name(name).spawn(move || {
146 let _profiler = TimeTraceProfiler::new(time_trace);
147 f()
148 })
149 }
150}
151
152impl WriteBackendMethods for LlvmCodegenBackend {
153 type Module = ModuleLlvm;
154 type ModuleBuffer = back::lto::ModuleBuffer;
155 type TargetMachine = OwnedTargetMachine;
156 type TargetMachineError = crate::errors::LlvmError<'static>;
157 type ThinData = back::lto::ThinData;
158 type ThinBuffer = back::lto::ThinBuffer;
159 fn print_pass_timings(&self) {
160 let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
161 print!("{timings}");
162 }
163 fn print_statistics(&self) {
164 let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
165 print!("{stats}");
166 }
167 fn run_and_optimize_fat_lto(
168 cgcx: &CodegenContext<Self>,
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 =
174 back::lto::run_fat(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, modules);
175
176 let dcx = cgcx.create_dcx();
177 let dcx = dcx.handle();
178 back::lto::run_pass_manager(cgcx, dcx, &mut module, false);
179
180 module
181 }
182 fn run_thin_lto(
183 cgcx: &CodegenContext<Self>,
184 exported_symbols_for_lto: &[String],
185 each_linked_rlib_for_lto: &[PathBuf],
186 modules: Vec<(String, Self::ThinBuffer)>,
187 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
188 ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
189 back::lto::run_thin(
190 cgcx,
191 exported_symbols_for_lto,
192 each_linked_rlib_for_lto,
193 modules,
194 cached_modules,
195 )
196 }
197 fn optimize(
198 cgcx: &CodegenContext<Self>,
199 dcx: DiagCtxtHandle<'_>,
200 module: &mut ModuleCodegen<Self::Module>,
201 config: &ModuleConfig,
202 ) {
203 back::write::optimize(cgcx, dcx, module, config)
204 }
205 fn optimize_thin(
206 cgcx: &CodegenContext<Self>,
207 thin: ThinModule<Self>,
208 ) -> ModuleCodegen<Self::Module> {
209 back::lto::optimize_thin_module(thin, cgcx)
210 }
211 fn codegen(
212 cgcx: &CodegenContext<Self>,
213 module: ModuleCodegen<Self::Module>,
214 config: &ModuleConfig,
215 ) -> CompiledModule {
216 back::write::codegen(cgcx, module, config)
217 }
218 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
219 back::lto::prepare_thin(module)
220 }
221 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
222 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
223 }
224}
225
226impl LlvmCodegenBackend {
227 pub fn new() -> Box<dyn CodegenBackend> {
228 Box::new(LlvmCodegenBackend(()))
229 }
230}
231
232impl CodegenBackend for LlvmCodegenBackend {
233 fn locale_resource(&self) -> &'static str {
234 crate::DEFAULT_LOCALE_RESOURCE
235 }
236
237 fn name(&self) -> &'static str {
238 "llvm"
239 }
240
241 fn init(&self, sess: &Session) {
242 llvm_util::init(sess); }
244
245 fn provide(&self, providers: &mut Providers) {
246 providers.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 writeln!(out, "Available relocation models:").unwrap();
255 for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
256 writeln!(out, " {name}").unwrap();
257 }
258 writeln!(out).unwrap();
259 }
260 PrintKind::CodeModels => {
261 writeln!(out, "Available code models:").unwrap();
262 for name in &["tiny", "small", "kernel", "medium", "large"] {
263 writeln!(out, " {name}").unwrap();
264 }
265 writeln!(out).unwrap();
266 }
267 PrintKind::TlsModels => {
268 writeln!(out, "Available TLS models:").unwrap();
269 for name in TlsModel::ALL.iter().map(TlsModel::desc) {
270 writeln!(out, " {name}").unwrap();
271 }
272 writeln!(out).unwrap();
273 }
274 PrintKind::StackProtectorStrategies => {
275 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 codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
322 Box::new(rustc_codegen_ssa::base::codegen_crate(
323 LlvmCodegenBackend(()),
324 tcx,
325 crate::llvm_util::target_cpu(tcx.sess).to_string(),
326 ))
327 }
328
329 fn join_codegen(
330 &self,
331 ongoing_codegen: Box<dyn Any>,
332 sess: &Session,
333 outputs: &OutputFilenames,
334 ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
335 let (codegen_results, work_products) = ongoing_codegen
336 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
337 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
338 .join(sess);
339
340 if sess.opts.unstable_opts.llvm_time_trace {
341 sess.time("llvm_dump_timing_file", || {
342 let file_name = outputs.with_extension("llvm_timings.json");
343 llvm_util::time_trace_profiler_finish(&file_name);
344 });
345 }
346
347 (codegen_results, work_products)
348 }
349
350 fn link(
351 &self,
352 sess: &Session,
353 codegen_results: CodegenResults,
354 metadata: EncodedMetadata,
355 outputs: &OutputFilenames,
356 ) {
357 use rustc_codegen_ssa::back::link::link_binary;
358
359 use crate::back::archive::LlvmArchiveBuilderBuilder;
360
361 link_binary(
364 sess,
365 &LlvmArchiveBuilderBuilder,
366 codegen_results,
367 metadata,
368 outputs,
369 self.name(),
370 );
371 }
372}
373
374pub struct ModuleLlvm {
375 llcx: &'static mut llvm::Context,
376 llmod_raw: *const llvm::Module,
377
378 tm: ManuallyDrop<OwnedTargetMachine>,
381}
382
383unsafe impl Send for ModuleLlvm {}
384unsafe impl Sync for ModuleLlvm {}
385
386impl ModuleLlvm {
387 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
388 unsafe {
389 let llcx = llvm::LLVMContextCreate();
390 llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
391 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
392 ModuleLlvm {
393 llmod_raw,
394 llcx,
395 tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
396 }
397 }
398 }
399
400 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
401 unsafe {
402 let llcx = llvm::LLVMContextCreate();
403 llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
404 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
405 ModuleLlvm {
406 llmod_raw,
407 llcx,
408 tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
409 }
410 }
411 }
412
413 fn tm_from_cgcx(
414 cgcx: &CodegenContext<LlvmCodegenBackend>,
415 name: &str,
416 dcx: DiagCtxtHandle<'_>,
417 ) -> OwnedTargetMachine {
418 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
419 match (cgcx.tm_factory)(tm_factory_config) {
420 Ok(m) => m,
421 Err(e) => {
422 dcx.emit_fatal(ParseTargetMachineConfig(e));
423 }
424 }
425 }
426
427 fn parse(
428 cgcx: &CodegenContext<LlvmCodegenBackend>,
429 name: &CStr,
430 buffer: &[u8],
431 dcx: DiagCtxtHandle<'_>,
432 ) -> Self {
433 unsafe {
434 let llcx = llvm::LLVMContextCreate();
435 llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
436 let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
437 let tm = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx);
438
439 ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
440 }
441 }
442
443 fn llmod(&self) -> &llvm::Module {
444 unsafe { &*self.llmod_raw }
445 }
446}
447
448impl Drop for ModuleLlvm {
449 fn drop(&mut self) {
450 unsafe {
451 ManuallyDrop::drop(&mut self.tm);
452 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
453 }
454 }
455}