]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Remove incorrect span for second label inner macro invocation
[rust.git] / src / librustc_codegen_llvm / lib.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19       html_root_url = "https://doc.rust-lang.org/nightly/")]
20
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
23 #![feature(crate_visibility_modifier)]
24 #![feature(custom_attribute)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![allow(unused_attributes)]
28 #![feature(libc)]
29 #![feature(nll)]
30 #![feature(quote)]
31 #![feature(range_contains)]
32 #![feature(rustc_diagnostic_macros)]
33 #![feature(slice_sort_by_cached_key)]
34 #![feature(optin_builtin_traits)]
35 #![feature(concat_idents)]
36 #![feature(link_args)]
37 #![feature(static_nobundle)]
38
39 use back::write::create_target_machine;
40 use rustc::dep_graph::WorkProduct;
41 use syntax_pos::symbol::Symbol;
42
43 #[macro_use] extern crate bitflags;
44 extern crate flate2;
45 extern crate libc;
46 #[macro_use] extern crate rustc;
47 extern crate jobserver;
48 extern crate num_cpus;
49 extern crate rustc_mir;
50 extern crate rustc_allocator;
51 extern crate rustc_apfloat;
52 extern crate rustc_target;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_codegen_utils;
59 extern crate rustc_fs_util;
60
61 #[macro_use] extern crate log;
62 #[macro_use] extern crate syntax;
63 extern crate syntax_pos;
64 extern crate rustc_errors as errors;
65 extern crate serialize;
66 extern crate cc; // Used to locate MSVC
67 extern crate tempfile;
68 extern crate memmap;
69
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
71
72 pub use llvm_util::target_features;
73 use std::any::Any;
74 use std::path::{PathBuf};
75 use std::sync::mpsc;
76 use rustc_data_structures::sync::Lrc;
77
78 use rustc::dep_graph::DepGraph;
79 use rustc::hir::def_id::CrateNum;
80 use rustc::middle::cstore::MetadataLoader;
81 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
82 use rustc::middle::lang_items::LangItem;
83 use rustc::session::{Session, CompileIncomplete};
84 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
85 use rustc::ty::{self, TyCtxt};
86 use rustc::util::time_graph;
87 use rustc::util::nodemap::{FxHashSet, FxHashMap};
88 use rustc::util::profiling::ProfileCategory;
89 use rustc_mir::monomorphize;
90 use rustc_codegen_utils::codegen_backend::CodegenBackend;
91 use rustc_data_structures::svh::Svh;
92
93 mod diagnostics;
94
95 mod back {
96     pub use rustc_codegen_utils::symbol_names;
97     mod archive;
98     pub mod bytecode;
99     mod command;
100     pub mod linker;
101     pub mod link;
102     pub mod lto;
103     pub mod symbol_export;
104     pub mod write;
105     mod rpath;
106     pub mod wasm;
107 }
108
109 mod abi;
110 mod allocator;
111 mod asm;
112 mod attributes;
113 mod base;
114 mod builder;
115 mod callee;
116 mod common;
117 mod consts;
118 mod context;
119 mod debuginfo;
120 mod declare;
121 mod glue;
122 mod intrinsic;
123 pub mod llvm;
124 mod llvm_util;
125 mod metadata;
126 mod meth;
127 mod mir;
128 mod mono_item;
129 mod type_;
130 mod type_of;
131 mod value;
132
133 pub struct LlvmCodegenBackend(());
134
135 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
136 impl !Sync for LlvmCodegenBackend {}
137
138 impl LlvmCodegenBackend {
139     pub fn new() -> Box<dyn CodegenBackend> {
140         box LlvmCodegenBackend(())
141     }
142 }
143
144 impl CodegenBackend for LlvmCodegenBackend {
145     fn init(&self, sess: &Session) {
146         llvm_util::init(sess); // Make sure llvm is inited
147     }
148
149     fn print(&self, req: PrintRequest, sess: &Session) {
150         match req {
151             PrintRequest::RelocationModels => {
152                 println!("Available relocation models:");
153                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
154                     println!("    {}", name);
155                 }
156                 println!("");
157             }
158             PrintRequest::CodeModels => {
159                 println!("Available code models:");
160                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
161                     println!("    {}", name);
162                 }
163                 println!("");
164             }
165             PrintRequest::TlsModels => {
166                 println!("Available TLS models:");
167                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
168                     println!("    {}", name);
169                 }
170                 println!("");
171             }
172             req => llvm_util::print(req, sess),
173         }
174     }
175
176     fn print_passes(&self) {
177         llvm_util::print_passes();
178     }
179
180     fn print_version(&self) {
181         llvm_util::print_version();
182     }
183
184     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
185         &DIAGNOSTICS
186     }
187
188     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
189         target_features(sess)
190     }
191
192     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
193         box metadata::LlvmMetadataLoader
194     }
195
196     fn provide(&self, providers: &mut ty::query::Providers) {
197         back::symbol_names::provide(providers);
198         back::symbol_export::provide(providers);
199         base::provide(providers);
200         attributes::provide(providers);
201     }
202
203     fn provide_extern(&self, providers: &mut ty::query::Providers) {
204         back::symbol_export::provide_extern(providers);
205         base::provide_extern(providers);
206         attributes::provide_extern(providers);
207     }
208
209     fn codegen_crate<'a, 'tcx>(
210         &self,
211         tcx: TyCtxt<'a, 'tcx, 'tcx>,
212         rx: mpsc::Receiver<Box<dyn Any + Send>>
213     ) -> Box<dyn Any> {
214         box base::codegen_crate(tcx, rx)
215     }
216
217     fn join_codegen_and_link(
218         &self,
219         ongoing_codegen: Box<dyn Any>,
220         sess: &Session,
221         dep_graph: &DepGraph,
222         outputs: &OutputFilenames,
223     ) -> Result<(), CompileIncomplete>{
224         use rustc::util::common::time;
225         let (ongoing_codegen, work_products) =
226             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
227                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
228                 .join(sess);
229         if sess.opts.debugging_opts.incremental_info {
230             back::write::dump_incremental_data(&ongoing_codegen);
231         }
232
233         time(sess,
234              "serialize work products",
235              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
236
237         sess.compile_status()?;
238
239         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
240                                                    i == OutputType::Metadata) {
241             return Ok(());
242         }
243
244         // Run the linker on any artifacts that resulted from the LLVM run.
245         // This should produce either a finished executable or library.
246         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
247         time(sess, "linking", || {
248             back::link::link_binary(sess, &ongoing_codegen,
249                                     outputs, &ongoing_codegen.crate_name.as_str());
250         });
251         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
252
253         // Now that we won't touch anything in the incremental compilation directory
254         // any more, we can finalize it (which involves renaming it)
255         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
256
257         Ok(())
258     }
259 }
260
261 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
262 #[no_mangle]
263 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
264     LlvmCodegenBackend::new()
265 }
266
267 struct ModuleCodegen {
268     /// The name of the module. When the crate may be saved between
269     /// compilations, incremental compilation requires that name be
270     /// unique amongst **all** crates.  Therefore, it should contain
271     /// something unique to this crate (e.g., a module path) as well
272     /// as the crate name and disambiguator.
273     /// We currently generate these names via CodegenUnit::build_cgu_name().
274     name: String,
275     module_llvm: ModuleLlvm,
276     kind: ModuleKind,
277 }
278
279 struct CachedModuleCodegen {
280     name: String,
281     source: WorkProduct,
282 }
283
284 #[derive(Copy, Clone, Debug, PartialEq)]
285 enum ModuleKind {
286     Regular,
287     Metadata,
288     Allocator,
289 }
290
291 impl ModuleCodegen {
292     fn into_compiled_module(self,
293                             emit_obj: bool,
294                             emit_bc: bool,
295                             emit_bc_compressed: bool,
296                             outputs: &OutputFilenames) -> CompiledModule {
297         let object = if emit_obj {
298             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
299         } else {
300             None
301         };
302         let bytecode = if emit_bc {
303             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
304         } else {
305             None
306         };
307         let bytecode_compressed = if emit_bc_compressed {
308             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
309                     .with_extension(RLIB_BYTECODE_EXTENSION))
310         } else {
311             None
312         };
313
314         CompiledModule {
315             name: self.name.clone(),
316             kind: self.kind,
317             object,
318             bytecode,
319             bytecode_compressed,
320         }
321     }
322 }
323
324 #[derive(Debug)]
325 struct CompiledModule {
326     name: String,
327     kind: ModuleKind,
328     object: Option<PathBuf>,
329     bytecode: Option<PathBuf>,
330     bytecode_compressed: Option<PathBuf>,
331 }
332
333 struct ModuleLlvm {
334     llcx: &'static mut llvm::Context,
335     llmod_raw: *const llvm::Module,
336     tm: &'static mut llvm::TargetMachine,
337 }
338
339 unsafe impl Send for ModuleLlvm { }
340 unsafe impl Sync for ModuleLlvm { }
341
342 impl ModuleLlvm {
343     fn new(sess: &Session, mod_name: &str) -> Self {
344         unsafe {
345             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
346             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
347
348             ModuleLlvm {
349                 llmod_raw,
350                 llcx,
351                 tm: create_target_machine(sess, false),
352             }
353         }
354     }
355
356     fn llmod(&self) -> &llvm::Module {
357         unsafe {
358             &*self.llmod_raw
359         }
360     }
361 }
362
363 impl Drop for ModuleLlvm {
364     fn drop(&mut self) {
365         unsafe {
366             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
367             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
368         }
369     }
370 }
371
372 struct CodegenResults {
373     crate_name: Symbol,
374     modules: Vec<CompiledModule>,
375     allocator_module: Option<CompiledModule>,
376     metadata_module: CompiledModule,
377     crate_hash: Svh,
378     metadata: rustc::middle::cstore::EncodedMetadata,
379     windows_subsystem: Option<String>,
380     linker_info: back::linker::LinkerInfo,
381     crate_info: CrateInfo,
382 }
383
384 /// Misc info we load from metadata to persist beyond the tcx
385 struct CrateInfo {
386     panic_runtime: Option<CrateNum>,
387     compiler_builtins: Option<CrateNum>,
388     profiler_runtime: Option<CrateNum>,
389     sanitizer_runtime: Option<CrateNum>,
390     is_no_builtins: FxHashSet<CrateNum>,
391     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
392     crate_name: FxHashMap<CrateNum, String>,
393     used_libraries: Lrc<Vec<NativeLibrary>>,
394     link_args: Lrc<Vec<String>>,
395     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
396     used_crates_static: Vec<(CrateNum, LibSource)>,
397     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
398     wasm_imports: FxHashMap<String, String>,
399     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
400     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
401 }
402
403 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }