]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
Rollup merge of #90930 - Nilstrieb:fix-non-const-value-ice, r=estebank
[rust.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             req => llvm_util::print(req, sess),
292         }
293     }
294
295     fn print_passes(&self) {
296         llvm_util::print_passes();
297     }
298
299     fn print_version(&self) {
300         llvm_util::print_version();
301     }
302
303     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
304         target_features(sess)
305     }
306
307     fn codegen_crate<'tcx>(
308         &self,
309         tcx: TyCtxt<'tcx>,
310         metadata: EncodedMetadata,
311         need_metadata_module: bool,
312     ) -> Box<dyn Any> {
313         Box::new(rustc_codegen_ssa::base::codegen_crate(
314             LlvmCodegenBackend(()),
315             tcx,
316             crate::llvm_util::target_cpu(tcx.sess).to_string(),
317             metadata,
318             need_metadata_module,
319         ))
320     }
321
322     fn join_codegen(
323         &self,
324         ongoing_codegen: Box<dyn Any>,
325         sess: &Session,
326     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
327         let (codegen_results, work_products) = ongoing_codegen
328             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
329             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
330             .join(sess);
331
332         sess.time("llvm_dump_timing_file", || {
333             if sess.opts.debugging_opts.llvm_time_trace {
334                 llvm_util::time_trace_profiler_finish("llvm_timings.json");
335             }
336         });
337
338         Ok((codegen_results, work_products))
339     }
340
341     fn link(
342         &self,
343         sess: &Session,
344         codegen_results: CodegenResults,
345         outputs: &OutputFilenames,
346     ) -> Result<(), ErrorReported> {
347         use crate::back::archive::LlvmArchiveBuilder;
348         use rustc_codegen_ssa::back::link::link_binary;
349
350         // Run the linker on any artifacts that resulted from the LLVM run.
351         // This should produce either a finished executable or library.
352         link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
353     }
354 }
355
356 pub struct ModuleLlvm {
357     llcx: &'static mut llvm::Context,
358     llmod_raw: *const llvm::Module,
359     tm: &'static mut llvm::TargetMachine,
360 }
361
362 unsafe impl Send for ModuleLlvm {}
363 unsafe impl Sync for ModuleLlvm {}
364
365 impl ModuleLlvm {
366     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
367         unsafe {
368             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
369             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
370             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
371         }
372     }
373
374     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
375         unsafe {
376             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
377             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
378             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
379         }
380     }
381
382     fn parse(
383         cgcx: &CodegenContext<LlvmCodegenBackend>,
384         name: &CStr,
385         buffer: &[u8],
386         handler: &Handler,
387     ) -> Result<Self, FatalError> {
388         unsafe {
389             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
390             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
391             let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
392             let tm = match (cgcx.tm_factory)(tm_factory_config) {
393                 Ok(m) => m,
394                 Err(e) => {
395                     handler.struct_err(&e).emit();
396                     return Err(FatalError);
397                 }
398             };
399
400             Ok(ModuleLlvm { llmod_raw, llcx, tm })
401         }
402     }
403
404     fn llmod(&self) -> &llvm::Module {
405         unsafe { &*self.llmod_raw }
406     }
407 }
408
409 impl Drop for ModuleLlvm {
410     fn drop(&mut self) {
411         unsafe {
412             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
413             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
414         }
415     }
416 }