]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
Auto merge of #83357 - saethlin:vec-reserve-inlining, r=dtolnay
[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(extended_key_value_attributes)]
12 #![feature(extern_types)]
13 #![feature(in_band_lifetimes)]
14 #![feature(iter_zip)]
15 #![feature(nll)]
16 #![cfg_attr(bootstrap, feature(or_patterns))]
17 #![recursion_limit = "256"]
18
19 use back::write::{create_informational_target_machine, create_target_machine};
20
21 pub use llvm_util::target_features;
22 use rustc_ast::expand::allocator::AllocatorKind;
23 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
24 use rustc_codegen_ssa::back::write::{
25     CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
26 };
27 use rustc_codegen_ssa::traits::*;
28 use rustc_codegen_ssa::ModuleCodegen;
29 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
30 use rustc_data_structures::fx::FxHashMap;
31 use rustc_errors::{ErrorReported, FatalError, Handler};
32 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
33 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
34 use rustc_middle::ty::{self, TyCtxt};
35 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
36 use rustc_session::Session;
37 use rustc_span::symbol::Symbol;
38
39 use std::any::Any;
40 use std::ffi::CStr;
41
42 mod back {
43     pub mod archive;
44     pub mod lto;
45     mod profiling;
46     pub mod write;
47 }
48
49 mod abi;
50 mod allocator;
51 mod asm;
52 mod attributes;
53 mod base;
54 mod builder;
55 mod callee;
56 mod common;
57 mod consts;
58 mod context;
59 mod coverageinfo;
60 mod debuginfo;
61 mod declare;
62 mod intrinsic;
63
64 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
65 #[path = "llvm/mod.rs"]
66 mod llvm_;
67 pub mod llvm {
68     pub use super::llvm_::*;
69 }
70
71 mod llvm_util;
72 mod metadata;
73 mod mono_item;
74 mod type_;
75 mod type_of;
76 mod va_arg;
77 mod value;
78
79 #[derive(Clone)]
80 pub struct LlvmCodegenBackend(());
81
82 impl ExtraBackendMethods for LlvmCodegenBackend {
83     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
84         ModuleLlvm::new_metadata(tcx, mod_name)
85     }
86
87     fn write_compressed_metadata<'tcx>(
88         &self,
89         tcx: TyCtxt<'tcx>,
90         metadata: &EncodedMetadata,
91         llvm_module: &mut ModuleLlvm,
92     ) {
93         base::write_compressed_metadata(tcx, metadata, llvm_module)
94     }
95     fn codegen_allocator<'tcx>(
96         &self,
97         tcx: TyCtxt<'tcx>,
98         mods: &mut ModuleLlvm,
99         kind: AllocatorKind,
100         has_alloc_error_handler: bool,
101     ) {
102         unsafe { allocator::codegen(tcx, mods, kind, has_alloc_error_handler) }
103     }
104     fn compile_codegen_unit(
105         &self,
106         tcx: TyCtxt<'_>,
107         cgu_name: Symbol,
108     ) -> (ModuleCodegen<ModuleLlvm>, u64) {
109         base::compile_codegen_unit(tcx, cgu_name)
110     }
111     fn target_machine_factory(
112         &self,
113         sess: &Session,
114         optlvl: OptLevel,
115     ) -> TargetMachineFactoryFn<Self> {
116         back::write::target_machine_factory(sess, optlvl)
117     }
118     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
119         llvm_util::target_cpu(sess)
120     }
121     fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
122         llvm_util::tune_cpu(sess)
123     }
124 }
125
126 impl WriteBackendMethods for LlvmCodegenBackend {
127     type Module = ModuleLlvm;
128     type ModuleBuffer = back::lto::ModuleBuffer;
129     type Context = llvm::Context;
130     type TargetMachine = &'static mut llvm::TargetMachine;
131     type ThinData = back::lto::ThinData;
132     type ThinBuffer = back::lto::ThinBuffer;
133     fn print_pass_timings(&self) {
134         unsafe {
135             llvm::LLVMRustPrintPassTimings();
136         }
137     }
138     fn run_link(
139         cgcx: &CodegenContext<Self>,
140         diag_handler: &Handler,
141         modules: Vec<ModuleCodegen<Self::Module>>,
142     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
143         back::write::link(cgcx, diag_handler, modules)
144     }
145     fn run_fat_lto(
146         cgcx: &CodegenContext<Self>,
147         modules: Vec<FatLTOInput<Self>>,
148         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
149     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
150         back::lto::run_fat(cgcx, modules, cached_modules)
151     }
152     fn run_thin_lto(
153         cgcx: &CodegenContext<Self>,
154         modules: Vec<(String, Self::ThinBuffer)>,
155         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
156     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
157         back::lto::run_thin(cgcx, modules, cached_modules)
158     }
159     unsafe fn optimize(
160         cgcx: &CodegenContext<Self>,
161         diag_handler: &Handler,
162         module: &ModuleCodegen<Self::Module>,
163         config: &ModuleConfig,
164     ) -> Result<(), FatalError> {
165         Ok(back::write::optimize(cgcx, diag_handler, module, config))
166     }
167     unsafe fn optimize_thin(
168         cgcx: &CodegenContext<Self>,
169         thin: &mut ThinModule<Self>,
170     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
171         back::lto::optimize_thin_module(thin, cgcx)
172     }
173     unsafe fn codegen(
174         cgcx: &CodegenContext<Self>,
175         diag_handler: &Handler,
176         module: ModuleCodegen<Self::Module>,
177         config: &ModuleConfig,
178     ) -> Result<CompiledModule, FatalError> {
179         back::write::codegen(cgcx, diag_handler, module, config)
180     }
181     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
182         back::lto::prepare_thin(module)
183     }
184     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
185         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
186     }
187     fn run_lto_pass_manager(
188         cgcx: &CodegenContext<Self>,
189         module: &ModuleCodegen<Self::Module>,
190         config: &ModuleConfig,
191         thin: bool,
192     ) {
193         back::lto::run_pass_manager(cgcx, module, config, thin)
194     }
195 }
196
197 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
198 unsafe impl Sync for LlvmCodegenBackend {}
199
200 impl LlvmCodegenBackend {
201     pub fn new() -> Box<dyn CodegenBackend> {
202         Box::new(LlvmCodegenBackend(()))
203     }
204 }
205
206 impl CodegenBackend for LlvmCodegenBackend {
207     fn init(&self, sess: &Session) {
208         llvm_util::init(sess); // Make sure llvm is inited
209     }
210
211     fn print(&self, req: PrintRequest, sess: &Session) {
212         match req {
213             PrintRequest::RelocationModels => {
214                 println!("Available relocation models:");
215                 for name in
216                     &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
217                 {
218                     println!("    {}", name);
219                 }
220                 println!();
221             }
222             PrintRequest::CodeModels => {
223                 println!("Available code models:");
224                 for name in &["tiny", "small", "kernel", "medium", "large"] {
225                     println!("    {}", name);
226                 }
227                 println!();
228             }
229             PrintRequest::TlsModels => {
230                 println!("Available TLS models:");
231                 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
232                     println!("    {}", name);
233                 }
234                 println!();
235             }
236             req => llvm_util::print(req, sess),
237         }
238     }
239
240     fn print_passes(&self) {
241         llvm_util::print_passes();
242     }
243
244     fn print_version(&self) {
245         llvm_util::print_version();
246     }
247
248     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
249         target_features(sess)
250     }
251
252     fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
253         Box::new(metadata::LlvmMetadataLoader)
254     }
255
256     fn provide(&self, providers: &mut ty::query::Providers) {
257         attributes::provide_both(providers);
258     }
259
260     fn provide_extern(&self, providers: &mut ty::query::Providers) {
261         attributes::provide_both(providers);
262     }
263
264     fn codegen_crate<'tcx>(
265         &self,
266         tcx: TyCtxt<'tcx>,
267         metadata: EncodedMetadata,
268         need_metadata_module: bool,
269     ) -> Box<dyn Any> {
270         Box::new(rustc_codegen_ssa::base::codegen_crate(
271             LlvmCodegenBackend(()),
272             tcx,
273             metadata,
274             need_metadata_module,
275         ))
276     }
277
278     fn join_codegen(
279         &self,
280         ongoing_codegen: Box<dyn Any>,
281         sess: &Session,
282     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
283         let (codegen_results, work_products) = ongoing_codegen
284             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
285             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
286             .join(sess);
287
288         sess.time("llvm_dump_timing_file", || {
289             if sess.opts.debugging_opts.llvm_time_trace {
290                 llvm_util::time_trace_profiler_finish("llvm_timings.json");
291             }
292         });
293
294         Ok((codegen_results, work_products))
295     }
296
297     fn link(
298         &self,
299         sess: &Session,
300         codegen_results: CodegenResults,
301         outputs: &OutputFilenames,
302     ) -> Result<(), ErrorReported> {
303         use crate::back::archive::LlvmArchiveBuilder;
304         use rustc_codegen_ssa::back::link::link_binary;
305
306         // Run the linker on any artifacts that resulted from the LLVM run.
307         // This should produce either a finished executable or library.
308         let target_cpu = crate::llvm_util::target_cpu(sess);
309         link_binary::<LlvmArchiveBuilder<'_>>(
310             sess,
311             &codegen_results,
312             outputs,
313             &codegen_results.crate_name.as_str(),
314             target_cpu,
315         );
316
317         Ok(())
318     }
319 }
320
321 pub struct ModuleLlvm {
322     llcx: &'static mut llvm::Context,
323     llmod_raw: *const llvm::Module,
324     tm: &'static mut llvm::TargetMachine,
325 }
326
327 unsafe impl Send for ModuleLlvm {}
328 unsafe impl Sync for ModuleLlvm {}
329
330 impl ModuleLlvm {
331     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
332         unsafe {
333             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
334             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
335             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
336         }
337     }
338
339     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
340         unsafe {
341             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
342             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
343             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
344         }
345     }
346
347     fn parse(
348         cgcx: &CodegenContext<LlvmCodegenBackend>,
349         name: &CStr,
350         buffer: &[u8],
351         handler: &Handler,
352     ) -> Result<Self, FatalError> {
353         unsafe {
354             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
355             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
356             let tm_factory_config = TargetMachineFactoryConfig::new(&cgcx, name.to_str().unwrap());
357             let tm = match (cgcx.tm_factory)(tm_factory_config) {
358                 Ok(m) => m,
359                 Err(e) => {
360                     handler.struct_err(&e).emit();
361                     return Err(FatalError);
362                 }
363             };
364
365             Ok(ModuleLlvm { llmod_raw, llcx, tm })
366         }
367     }
368
369     fn llmod(&self) -> &llvm::Module {
370         unsafe { &*self.llmod_raw }
371     }
372 }
373
374 impl Drop for ModuleLlvm {
375     fn drop(&mut self) {
376         unsafe {
377             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
378             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
379         }
380     }
381 }