]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Add projection query for upstream drop-glue instances.
[rust.git] / src / librustc_codegen_llvm / 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/")]
8 #![feature(bool_to_option)]
9 #![feature(box_patterns)]
10 #![feature(box_syntax)]
11 #![feature(const_cstr_unchecked)]
12 #![feature(crate_visibility_modifier)]
13 #![feature(extern_types)]
14 #![feature(in_band_lifetimes)]
15 #![feature(libc)]
16 #![feature(nll)]
17 #![feature(optin_builtin_traits)]
18 #![feature(concat_idents)]
19 #![feature(link_args)]
20 #![feature(static_nobundle)]
21 #![feature(trusted_len)]
22 #![recursion_limit = "256"]
23
24 use back::write::{create_informational_target_machine, create_target_machine};
25 use rustc_span::symbol::Symbol;
26
27 pub use llvm_util::target_features;
28 use rustc::dep_graph::WorkProduct;
29 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
30 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig};
31 use rustc_codegen_ssa::traits::*;
32 use rustc_codegen_ssa::CompiledModule;
33 use rustc_errors::{FatalError, Handler};
34 use std::any::Any;
35 use std::ffi::CStr;
36 use std::fs;
37 use std::sync::Arc;
38 use syntax::expand::allocator::AllocatorKind;
39
40 use rustc::dep_graph::DepGraph;
41 use rustc::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
42 use rustc::session::config::{OptLevel, OutputFilenames, OutputType, PrintRequest};
43 use rustc::session::Session;
44 use rustc::ty::{self, TyCtxt};
45 use rustc::util::common::ErrorReported;
46 use rustc_codegen_ssa::ModuleCodegen;
47 use rustc_codegen_utils::codegen_backend::CodegenBackend;
48 use rustc_serialize::json;
49
50 mod back {
51     pub mod archive;
52     pub mod bytecode;
53     pub mod lto;
54     pub mod write;
55 }
56
57 mod abi;
58 mod allocator;
59 mod asm;
60 mod attributes;
61 mod base;
62 mod builder;
63 mod callee;
64 mod common;
65 mod consts;
66 mod context;
67 mod debuginfo;
68 mod declare;
69 mod intrinsic;
70
71 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
72 #[path = "llvm/mod.rs"]
73 mod llvm_;
74 pub mod llvm {
75     pub use super::llvm_::*;
76 }
77
78 mod llvm_util;
79 mod metadata;
80 mod mono_item;
81 mod type_;
82 mod type_of;
83 mod va_arg;
84 mod value;
85
86 #[derive(Clone)]
87 pub struct LlvmCodegenBackend(());
88
89 impl ExtraBackendMethods for LlvmCodegenBackend {
90     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
91         ModuleLlvm::new_metadata(tcx, mod_name)
92     }
93
94     fn write_compressed_metadata<'tcx>(
95         &self,
96         tcx: TyCtxt<'tcx>,
97         metadata: &EncodedMetadata,
98         llvm_module: &mut ModuleLlvm,
99     ) {
100         base::write_compressed_metadata(tcx, metadata, llvm_module)
101     }
102     fn codegen_allocator<'tcx>(
103         &self,
104         tcx: TyCtxt<'tcx>,
105         mods: &mut ModuleLlvm,
106         kind: AllocatorKind,
107     ) {
108         unsafe { allocator::codegen(tcx, mods, kind) }
109     }
110     fn compile_codegen_unit(
111         &self,
112         tcx: TyCtxt<'_>,
113         cgu_name: Symbol,
114     ) -> (ModuleCodegen<ModuleLlvm>, u64) {
115         base::compile_codegen_unit(tcx, cgu_name)
116     }
117     fn target_machine_factory(
118         &self,
119         sess: &Session,
120         optlvl: OptLevel,
121         find_features: bool,
122     ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
123         back::write::target_machine_factory(sess, optlvl, find_features)
124     }
125     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
126         llvm_util::target_cpu(sess)
127     }
128 }
129
130 impl WriteBackendMethods for LlvmCodegenBackend {
131     type Module = ModuleLlvm;
132     type ModuleBuffer = back::lto::ModuleBuffer;
133     type Context = llvm::Context;
134     type TargetMachine = &'static mut llvm::TargetMachine;
135     type ThinData = back::lto::ThinData;
136     type ThinBuffer = back::lto::ThinBuffer;
137     fn print_pass_timings(&self) {
138         unsafe {
139             llvm::LLVMRustPrintPassTimings();
140         }
141     }
142     fn run_fat_lto(
143         cgcx: &CodegenContext<Self>,
144         modules: Vec<FatLTOInput<Self>>,
145         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
146     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
147         back::lto::run_fat(cgcx, modules, cached_modules)
148     }
149     fn run_thin_lto(
150         cgcx: &CodegenContext<Self>,
151         modules: Vec<(String, Self::ThinBuffer)>,
152         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
153     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
154         back::lto::run_thin(cgcx, modules, cached_modules)
155     }
156     unsafe fn optimize(
157         cgcx: &CodegenContext<Self>,
158         diag_handler: &Handler,
159         module: &ModuleCodegen<Self::Module>,
160         config: &ModuleConfig,
161     ) -> Result<(), FatalError> {
162         back::write::optimize(cgcx, diag_handler, module, config)
163     }
164     unsafe fn optimize_thin(
165         cgcx: &CodegenContext<Self>,
166         thin: &mut ThinModule<Self>,
167     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
168         back::lto::optimize_thin_module(thin, cgcx)
169     }
170     unsafe fn codegen(
171         cgcx: &CodegenContext<Self>,
172         diag_handler: &Handler,
173         module: ModuleCodegen<Self::Module>,
174         config: &ModuleConfig,
175     ) -> Result<CompiledModule, FatalError> {
176         back::write::codegen(cgcx, diag_handler, module, config)
177     }
178     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
179         back::lto::prepare_thin(module)
180     }
181     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
182         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
183     }
184     fn run_lto_pass_manager(
185         cgcx: &CodegenContext<Self>,
186         module: &ModuleCodegen<Self::Module>,
187         config: &ModuleConfig,
188         thin: bool,
189     ) {
190         back::lto::run_pass_manager(cgcx, module, config, thin)
191     }
192 }
193
194 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
195 unsafe impl Sync for LlvmCodegenBackend {}
196
197 impl LlvmCodegenBackend {
198     pub fn new() -> Box<dyn CodegenBackend> {
199         box LlvmCodegenBackend(())
200     }
201 }
202
203 impl CodegenBackend for LlvmCodegenBackend {
204     fn init(&self, sess: &Session) {
205         llvm_util::init(sess); // Make sure llvm is inited
206     }
207
208     fn print(&self, req: PrintRequest, sess: &Session) {
209         match req {
210             PrintRequest::RelocationModels => {
211                 println!("Available relocation models:");
212                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
213                     println!("    {}", name);
214                 }
215                 println!();
216             }
217             PrintRequest::CodeModels => {
218                 println!("Available code models:");
219                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter() {
220                     println!("    {}", name);
221                 }
222                 println!();
223             }
224             PrintRequest::TlsModels => {
225                 println!("Available TLS models:");
226                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter() {
227                     println!("    {}", name);
228                 }
229                 println!();
230             }
231             req => llvm_util::print(req, sess),
232         }
233     }
234
235     fn print_passes(&self) {
236         llvm_util::print_passes();
237     }
238
239     fn print_version(&self) {
240         llvm_util::print_version();
241     }
242
243     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
244         target_features(sess)
245     }
246
247     fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
248         box metadata::LlvmMetadataLoader
249     }
250
251     fn provide(&self, providers: &mut ty::query::Providers<'_>) {
252         attributes::provide(providers);
253     }
254
255     fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
256         attributes::provide_extern(providers);
257     }
258
259     fn codegen_crate<'tcx>(
260         &self,
261         tcx: TyCtxt<'tcx>,
262         metadata: EncodedMetadata,
263         need_metadata_module: bool,
264     ) -> Box<dyn Any> {
265         box rustc_codegen_ssa::base::codegen_crate(
266             LlvmCodegenBackend(()),
267             tcx,
268             metadata,
269             need_metadata_module,
270         )
271     }
272
273     fn join_codegen_and_link(
274         &self,
275         ongoing_codegen: Box<dyn Any>,
276         sess: &Session,
277         dep_graph: &DepGraph,
278         outputs: &OutputFilenames,
279     ) -> Result<(), ErrorReported> {
280         let (codegen_results, work_products) = ongoing_codegen
281             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
282             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
283             .join(sess);
284         if sess.opts.debugging_opts.incremental_info {
285             rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
286         }
287
288         sess.time("serialize_work_products", move || {
289             rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
290         });
291
292         sess.compile_status()?;
293
294         if !sess
295             .opts
296             .output_types
297             .keys()
298             .any(|&i| i == OutputType::Exe || i == OutputType::Metadata)
299         {
300             return Ok(());
301         }
302
303         if sess.opts.debugging_opts.no_link {
304             // FIXME: use a binary format to encode the `.rlink` file
305             let rlink_data = json::encode(&codegen_results).map_err(|err| {
306                 sess.fatal(&format!("failed to encode rlink: {}", err));
307             })?;
308             let rlink_file = outputs.with_extension("rlink");
309             fs::write(&rlink_file, rlink_data).map_err(|err| {
310                 sess.fatal(&format!("failed to write file {}: {}", rlink_file.display(), err));
311             })?;
312             return Ok(());
313         }
314
315         // Run the linker on any artifacts that resulted from the LLVM run.
316         // This should produce either a finished executable or library.
317         sess.time("link_crate", || {
318             use crate::back::archive::LlvmArchiveBuilder;
319             use rustc_codegen_ssa::back::link::link_binary;
320
321             let target_cpu = crate::llvm_util::target_cpu(sess);
322             link_binary::<LlvmArchiveBuilder<'_>>(
323                 sess,
324                 &codegen_results,
325                 outputs,
326                 &codegen_results.crate_name.as_str(),
327                 target_cpu,
328             );
329         });
330
331         // Now that we won't touch anything in the incremental compilation directory
332         // any more, we can finalize it (which involves renaming it)
333         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
334
335         Ok(())
336     }
337 }
338
339 pub struct ModuleLlvm {
340     llcx: &'static mut llvm::Context,
341     llmod_raw: *const llvm::Module,
342     tm: &'static mut llvm::TargetMachine,
343 }
344
345 unsafe impl Send for ModuleLlvm {}
346 unsafe impl Sync for ModuleLlvm {}
347
348 impl ModuleLlvm {
349     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
350         unsafe {
351             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
352             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
353             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, false) }
354         }
355     }
356
357     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
358         unsafe {
359             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
360             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
361             ModuleLlvm {
362                 llmod_raw,
363                 llcx,
364                 tm: create_informational_target_machine(&tcx.sess, false),
365             }
366         }
367     }
368
369     fn parse(
370         cgcx: &CodegenContext<LlvmCodegenBackend>,
371         name: &CStr,
372         buffer: &[u8],
373         handler: &Handler,
374     ) -> Result<Self, FatalError> {
375         unsafe {
376             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
377             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
378             let tm = match (cgcx.tm_factory.0)() {
379                 Ok(m) => m,
380                 Err(e) => {
381                     handler.struct_err(&e).emit();
382                     return Err(FatalError);
383                 }
384             };
385
386             Ok(ModuleLlvm { llmod_raw, llcx, tm })
387         }
388     }
389
390     fn llmod(&self) -> &llvm::Module {
391         unsafe { &*self.llmod_raw }
392     }
393 }
394
395 impl Drop for ModuleLlvm {
396     fn drop(&mut self) {
397         unsafe {
398             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
399             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
400         }
401     }
402 }