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