]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
New upstream version 1.58.1+dfsg1
[rustc.git] / compiler / rustc_codegen_llvm / src / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
13 #![feature(iter_zip)]
14 #![feature(nll)]
15 #![recursion_limit = "256"]
16
17 use back::write::{create_informational_target_machine, create_target_machine};
18
19 pub use llvm_util::target_features;
20 use rustc_ast::expand::allocator::AllocatorKind;
21 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
22 use rustc_codegen_ssa::back::write::{
23 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
24 };
25 use rustc_codegen_ssa::traits::*;
26 use rustc_codegen_ssa::ModuleCodegen;
27 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_errors::{ErrorReported, FatalError, Handler};
30 use rustc_metadata::EncodedMetadata;
31 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
32 use rustc_middle::ty::TyCtxt;
33 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
34 use rustc_session::Session;
35 use rustc_span::symbol::Symbol;
36
37 use std::any::Any;
38 use std::ffi::CStr;
39
40 mod back {
41 pub mod archive;
42 pub mod lto;
43 mod profiling;
44 pub mod write;
45 }
46
47 mod abi;
48 mod allocator;
49 mod asm;
50 mod attributes;
51 mod base;
52 mod builder;
53 mod callee;
54 mod common;
55 mod consts;
56 mod context;
57 mod coverageinfo;
58 mod debuginfo;
59 mod declare;
60 mod intrinsic;
61
62 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
63 #[path = "llvm/mod.rs"]
64 mod llvm_;
65 pub mod llvm {
66 pub use super::llvm_::*;
67 }
68
69 mod llvm_util;
70 mod mono_item;
71 mod type_;
72 mod type_of;
73 mod va_arg;
74 mod value;
75
76 #[derive(Clone)]
77 pub struct LlvmCodegenBackend(());
78
79 struct TimeTraceProfiler {
80 enabled: bool,
81 }
82
83 impl TimeTraceProfiler {
84 fn new(enabled: bool) -> Self {
85 if enabled {
86 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
87 }
88 TimeTraceProfiler { enabled }
89 }
90 }
91
92 impl Drop for TimeTraceProfiler {
93 fn drop(&mut self) {
94 if self.enabled {
95 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
96 }
97 }
98 }
99
100 impl ExtraBackendMethods for LlvmCodegenBackend {
101 fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
102 ModuleLlvm::new_metadata(tcx, mod_name)
103 }
104
105 fn write_compressed_metadata<'tcx>(
106 &self,
107 tcx: TyCtxt<'tcx>,
108 metadata: &EncodedMetadata,
109 llvm_module: &mut ModuleLlvm,
110 ) {
111 base::write_compressed_metadata(tcx, metadata, llvm_module)
112 }
113 fn codegen_allocator<'tcx>(
114 &self,
115 tcx: TyCtxt<'tcx>,
116 module_llvm: &mut ModuleLlvm,
117 module_name: &str,
118 kind: AllocatorKind,
119 has_alloc_error_handler: bool,
120 ) {
121 unsafe { allocator::codegen(tcx, module_llvm, module_name, kind, has_alloc_error_handler) }
122 }
123 fn compile_codegen_unit(
124 &self,
125 tcx: TyCtxt<'_>,
126 cgu_name: Symbol,
127 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
128 base::compile_codegen_unit(tcx, cgu_name)
129 }
130 fn target_machine_factory(
131 &self,
132 sess: &Session,
133 optlvl: OptLevel,
134 ) -> TargetMachineFactoryFn<Self> {
135 back::write::target_machine_factory(sess, optlvl)
136 }
137 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
138 llvm_util::target_cpu(sess)
139 }
140 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
141 llvm_util::tune_cpu(sess)
142 }
143
144 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
145 where
146 F: FnOnce() -> T,
147 F: Send + 'static,
148 T: Send + 'static,
149 {
150 std::thread::spawn(move || {
151 let _profiler = TimeTraceProfiler::new(time_trace);
152 f()
153 })
154 }
155
156 fn spawn_named_thread<F, T>(
157 time_trace: bool,
158 name: String,
159 f: F,
160 ) -> std::io::Result<std::thread::JoinHandle<T>>
161 where
162 F: FnOnce() -> T,
163 F: Send + 'static,
164 T: Send + 'static,
165 {
166 std::thread::Builder::new().name(name).spawn(move || {
167 let _profiler = TimeTraceProfiler::new(time_trace);
168 f()
169 })
170 }
171 }
172
173 impl WriteBackendMethods for LlvmCodegenBackend {
174 type Module = ModuleLlvm;
175 type ModuleBuffer = back::lto::ModuleBuffer;
176 type Context = llvm::Context;
177 type TargetMachine = &'static mut llvm::TargetMachine;
178 type ThinData = back::lto::ThinData;
179 type ThinBuffer = back::lto::ThinBuffer;
180 fn print_pass_timings(&self) {
181 unsafe {
182 llvm::LLVMRustPrintPassTimings();
183 }
184 }
185 fn run_link(
186 cgcx: &CodegenContext<Self>,
187 diag_handler: &Handler,
188 modules: Vec<ModuleCodegen<Self::Module>>,
189 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
190 back::write::link(cgcx, diag_handler, modules)
191 }
192 fn run_fat_lto(
193 cgcx: &CodegenContext<Self>,
194 modules: Vec<FatLTOInput<Self>>,
195 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
196 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
197 back::lto::run_fat(cgcx, modules, cached_modules)
198 }
199 fn run_thin_lto(
200 cgcx: &CodegenContext<Self>,
201 modules: Vec<(String, Self::ThinBuffer)>,
202 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
203 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
204 back::lto::run_thin(cgcx, modules, cached_modules)
205 }
206 unsafe fn optimize(
207 cgcx: &CodegenContext<Self>,
208 diag_handler: &Handler,
209 module: &ModuleCodegen<Self::Module>,
210 config: &ModuleConfig,
211 ) -> Result<(), FatalError> {
212 back::write::optimize(cgcx, diag_handler, module, config)
213 }
214 unsafe fn optimize_thin(
215 cgcx: &CodegenContext<Self>,
216 thin: &mut ThinModule<Self>,
217 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
218 back::lto::optimize_thin_module(thin, cgcx)
219 }
220 unsafe fn codegen(
221 cgcx: &CodegenContext<Self>,
222 diag_handler: &Handler,
223 module: ModuleCodegen<Self::Module>,
224 config: &ModuleConfig,
225 ) -> Result<CompiledModule, FatalError> {
226 back::write::codegen(cgcx, diag_handler, module, config)
227 }
228 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
229 back::lto::prepare_thin(module)
230 }
231 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
232 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
233 }
234 fn run_lto_pass_manager(
235 cgcx: &CodegenContext<Self>,
236 module: &ModuleCodegen<Self::Module>,
237 config: &ModuleConfig,
238 thin: bool,
239 ) -> Result<(), FatalError> {
240 let diag_handler = cgcx.create_diag_handler();
241 back::lto::run_pass_manager(cgcx, &diag_handler, module, config, thin)
242 }
243 }
244
245 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
246 unsafe impl Sync for LlvmCodegenBackend {}
247
248 impl LlvmCodegenBackend {
249 pub fn new() -> Box<dyn CodegenBackend> {
250 Box::new(LlvmCodegenBackend(()))
251 }
252 }
253
254 impl CodegenBackend for LlvmCodegenBackend {
255 fn init(&self, sess: &Session) {
256 llvm_util::init(sess); // Make sure llvm is inited
257 }
258
259 fn print(&self, req: PrintRequest, sess: &Session) {
260 match req {
261 PrintRequest::RelocationModels => {
262 println!("Available relocation models:");
263 for name in &[
264 "static",
265 "pic",
266 "pie",
267 "dynamic-no-pic",
268 "ropi",
269 "rwpi",
270 "ropi-rwpi",
271 "default",
272 ] {
273 println!(" {}", name);
274 }
275 println!();
276 }
277 PrintRequest::CodeModels => {
278 println!("Available code models:");
279 for name in &["tiny", "small", "kernel", "medium", "large"] {
280 println!(" {}", name);
281 }
282 println!();
283 }
284 PrintRequest::TlsModels => {
285 println!("Available TLS models:");
286 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
287 println!(" {}", name);
288 }
289 println!();
290 }
291 PrintRequest::StackProtectorStrategies => {
292 println!(
293 r#"Available stack protector strategies:
294 all
295 Generate stack canaries in all functions.
296
297 strong
298 Generate stack canaries in a function if it either:
299 - has a local variable of `[T; N]` type, regardless of `T` and `N`
300 - takes the address of a local variable.
301
302 (Note that a local variable being borrowed is not equivalent to its
303 address being taken: e.g. some borrows may be removed by optimization,
304 while by-value argument passing may be implemented with reference to a
305 local stack variable in the ABI.)
306
307 basic
308 Generate stack canaries in functions with:
309 - local variables of `[T; N]` type, where `T` is byte-sized and `N` > 8.
310
311 none
312 Do not generate stack canaries.
313 "#
314 );
315 }
316 req => llvm_util::print(req, sess),
317 }
318 }
319
320 fn print_passes(&self) {
321 llvm_util::print_passes();
322 }
323
324 fn print_version(&self) {
325 llvm_util::print_version();
326 }
327
328 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
329 target_features(sess)
330 }
331
332 fn codegen_crate<'tcx>(
333 &self,
334 tcx: TyCtxt<'tcx>,
335 metadata: EncodedMetadata,
336 need_metadata_module: bool,
337 ) -> Box<dyn Any> {
338 Box::new(rustc_codegen_ssa::base::codegen_crate(
339 LlvmCodegenBackend(()),
340 tcx,
341 crate::llvm_util::target_cpu(tcx.sess).to_string(),
342 metadata,
343 need_metadata_module,
344 ))
345 }
346
347 fn join_codegen(
348 &self,
349 ongoing_codegen: Box<dyn Any>,
350 sess: &Session,
351 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
352 let (codegen_results, work_products) = ongoing_codegen
353 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
354 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
355 .join(sess);
356
357 sess.time("llvm_dump_timing_file", || {
358 if sess.opts.debugging_opts.llvm_time_trace {
359 llvm_util::time_trace_profiler_finish("llvm_timings.json");
360 }
361 });
362
363 Ok((codegen_results, work_products))
364 }
365
366 fn link(
367 &self,
368 sess: &Session,
369 codegen_results: CodegenResults,
370 outputs: &OutputFilenames,
371 ) -> Result<(), ErrorReported> {
372 use crate::back::archive::LlvmArchiveBuilder;
373 use rustc_codegen_ssa::back::link::link_binary;
374
375 // Run the linker on any artifacts that resulted from the LLVM run.
376 // This should produce either a finished executable or library.
377 link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
378 }
379 }
380
381 pub struct ModuleLlvm {
382 llcx: &'static mut llvm::Context,
383 llmod_raw: *const llvm::Module,
384 tm: &'static mut llvm::TargetMachine,
385 }
386
387 unsafe impl Send for ModuleLlvm {}
388 unsafe impl Sync for ModuleLlvm {}
389
390 impl ModuleLlvm {
391 fn new(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 { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
396 }
397 }
398
399 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
400 unsafe {
401 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
402 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
403 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
404 }
405 }
406
407 fn parse(
408 cgcx: &CodegenContext<LlvmCodegenBackend>,
409 name: &CStr,
410 buffer: &[u8],
411 handler: &Handler,
412 ) -> Result<Self, FatalError> {
413 unsafe {
414 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
415 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
416 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
417 let tm = match (cgcx.tm_factory)(tm_factory_config) {
418 Ok(m) => m,
419 Err(e) => {
420 handler.struct_err(&e).emit();
421 return Err(FatalError);
422 }
423 };
424
425 Ok(ModuleLlvm { llmod_raw, llcx, tm })
426 }
427 }
428
429 fn llmod(&self) -> &llvm::Module {
430 unsafe { &*self.llmod_raw }
431 }
432 }
433
434 impl Drop for ModuleLlvm {
435 fn drop(&mut self) {
436 unsafe {
437 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
438 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
439 }
440 }
441 }