]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Merge pull request #1093 from bjorn3/use_new_module_interface
[rust.git] / src / lib.rs
1 #![feature(
2     rustc_private,
3     decl_macro,
4     type_alias_impl_trait,
5     associated_type_bounds,
6     never_type,
7     try_blocks,
8     hash_drain_filter
9 )]
10 #![warn(rust_2018_idioms)]
11 #![warn(unused_lifetimes)]
12
13 #[cfg(feature = "jit")]
14 extern crate libc;
15 extern crate snap;
16 #[macro_use]
17 extern crate rustc_middle;
18 extern crate rustc_ast;
19 extern crate rustc_codegen_ssa;
20 extern crate rustc_data_structures;
21 extern crate rustc_errors;
22 extern crate rustc_fs_util;
23 extern crate rustc_hir;
24 extern crate rustc_incremental;
25 extern crate rustc_index;
26 extern crate rustc_mir;
27 extern crate rustc_session;
28 extern crate rustc_span;
29 extern crate rustc_symbol_mangling;
30 extern crate rustc_target;
31
32 // This prevents duplicating functions and statics that are already part of the host rustc process.
33 #[allow(unused_extern_crates)]
34 extern crate rustc_driver;
35
36 use std::any::Any;
37
38 use rustc_codegen_ssa::traits::CodegenBackend;
39 use rustc_codegen_ssa::CodegenResults;
40 use rustc_errors::ErrorReported;
41 use rustc_middle::dep_graph::{DepGraph, WorkProduct, WorkProductId};
42 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoader};
43 use rustc_middle::ty::query::Providers;
44 use rustc_session::config::OutputFilenames;
45 use rustc_session::Session;
46
47 use cranelift_codegen::settings::{self, Configurable};
48
49 use crate::constant::ConstantCx;
50 use crate::prelude::*;
51
52 mod abi;
53 mod allocator;
54 mod analyze;
55 mod archive;
56 mod atomic_shim;
57 mod backend;
58 mod base;
59 mod cast;
60 mod codegen_i128;
61 mod common;
62 mod constant;
63 mod debuginfo;
64 mod discriminant;
65 mod driver;
66 mod inline_asm;
67 mod intrinsics;
68 mod linkage;
69 mod main_shim;
70 mod metadata;
71 mod num;
72 mod optimize;
73 mod pointer;
74 mod pretty_clif;
75 mod toolchain;
76 mod trap;
77 mod unsize;
78 mod value_and_place;
79 mod vtable;
80
81 mod prelude {
82     pub(crate) use std::convert::{TryFrom, TryInto};
83
84     pub(crate) use rustc_ast::ast::{FloatTy, IntTy, UintTy};
85     pub(crate) use rustc_span::Span;
86
87     pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
88     pub(crate) use rustc_middle::bug;
89     pub(crate) use rustc_middle::mir::{self, *};
90     pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
91     pub(crate) use rustc_middle::ty::{
92         self, FnSig, Instance, InstanceDef, ParamEnv, Ty, TyCtxt, TypeAndMut, TypeFoldable,
93     };
94     pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
95
96     pub(crate) use rustc_data_structures::fx::FxHashMap;
97
98     pub(crate) use rustc_index::vec::Idx;
99
100     pub(crate) use cranelift_codegen::entity::EntitySet;
101     pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
102     pub(crate) use cranelift_codegen::ir::function::Function;
103     pub(crate) use cranelift_codegen::ir::types;
104     pub(crate) use cranelift_codegen::ir::{
105         AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
106         StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
107     };
108     pub(crate) use cranelift_codegen::isa::{self, CallConv};
109     pub(crate) use cranelift_codegen::Context;
110     pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
111     pub(crate) use cranelift_module::{self, DataContext, DataId, FuncId, Linkage, Module};
112
113     pub(crate) use crate::abi::*;
114     pub(crate) use crate::base::{trans_operand, trans_place};
115     pub(crate) use crate::cast::*;
116     pub(crate) use crate::common::*;
117     pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
118     pub(crate) use crate::pointer::Pointer;
119     pub(crate) use crate::trap::*;
120     pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
121 }
122
123 struct PrintOnPanic<F: Fn() -> String>(F);
124 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
125     fn drop(&mut self) {
126         if ::std::thread::panicking() {
127             println!("{}", (self.0)());
128         }
129     }
130 }
131
132 struct CodegenCx<'tcx, M: Module> {
133     tcx: TyCtxt<'tcx>,
134     module: M,
135     global_asm: String,
136     constants_cx: ConstantCx,
137     cached_context: Context,
138     vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
139     debug_context: Option<DebugContext<'tcx>>,
140     unwind_context: UnwindContext<'tcx>,
141 }
142
143 impl<'tcx, M: Module> CodegenCx<'tcx, M> {
144     fn new(tcx: TyCtxt<'tcx>, module: M, debug_info: bool) -> Self {
145         let unwind_context = UnwindContext::new(tcx, module.isa());
146         let debug_context = if debug_info {
147             Some(DebugContext::new(tcx, module.isa()))
148         } else {
149             None
150         };
151         CodegenCx {
152             tcx,
153             module,
154             global_asm: String::new(),
155             constants_cx: ConstantCx::default(),
156             cached_context: Context::new(),
157             vtables: FxHashMap::default(),
158             debug_context,
159             unwind_context,
160         }
161     }
162
163     fn finalize(mut self) -> (M, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
164         self.constants_cx.finalize(self.tcx, &mut self.module);
165         (
166             self.module,
167             self.global_asm,
168             self.debug_context,
169             self.unwind_context,
170         )
171     }
172 }
173
174 #[derive(Copy, Clone, Debug)]
175 pub struct BackendConfig {
176     pub use_jit: bool,
177 }
178
179 pub struct CraneliftCodegenBackend {
180     pub config: BackendConfig,
181 }
182
183 impl CodegenBackend for CraneliftCodegenBackend {
184     fn init(&self, sess: &Session) {
185         if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
186             sess.warn("LTO is not supported. You may get a linker error.");
187         }
188     }
189
190     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
191         Box::new(crate::metadata::CraneliftMetadataLoader)
192     }
193
194     fn provide(&self, providers: &mut Providers) {
195         providers.supported_target_features = |tcx, cnum| {
196             assert_eq!(cnum, LOCAL_CRATE);
197             if tcx.sess.opts.actually_rustdoc {
198                 // rustdoc needs to be able to document functions that use all the features, so
199                 // whitelist them all
200                 rustc_codegen_ssa::target_features::all_known_features()
201                     .map(|(a, b)| (a.to_string(), b))
202                     .collect()
203             } else {
204                 rustc_codegen_ssa::target_features::supported_target_features(tcx.sess)
205                     .iter()
206                     .map(|&(a, b)| (a.to_string(), b))
207                     .collect()
208             }
209         };
210     }
211     fn provide_extern(&self, _providers: &mut Providers) {}
212
213     fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
214         vec![]
215     }
216
217     fn codegen_crate<'tcx>(
218         &self,
219         tcx: TyCtxt<'tcx>,
220         metadata: EncodedMetadata,
221         need_metadata_module: bool,
222     ) -> Box<dyn Any> {
223         let res = driver::codegen_crate(tcx, metadata, need_metadata_module, self.config);
224
225         rustc_symbol_mangling::test::report_symbol_names(tcx);
226
227         res
228     }
229
230     fn join_codegen(
231         &self,
232         ongoing_codegen: Box<dyn Any>,
233         sess: &Session,
234         dep_graph: &DepGraph,
235     ) -> Result<Box<dyn Any>, ErrorReported> {
236         let (codegen_results, work_products) = *ongoing_codegen
237             .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
238             .unwrap();
239
240         sess.time("serialize_work_products", move || {
241             rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
242         });
243
244         Ok(Box::new(codegen_results))
245     }
246
247     fn link(
248         &self,
249         sess: &Session,
250         res: Box<dyn Any>,
251         outputs: &OutputFilenames,
252     ) -> Result<(), ErrorReported> {
253         use rustc_codegen_ssa::back::link::link_binary;
254
255         sess.abort_if_errors();
256
257         let codegen_results = *res
258             .downcast::<CodegenResults>()
259             .expect("Expected CraneliftCodegenBackend's CodegenResult, found Box<Any>");
260
261         let _timer = sess.prof.generic_activity("link_crate");
262
263         sess.time("linking", || {
264             let target_cpu = crate::target_triple(sess).to_string();
265             link_binary::<crate::archive::ArArchiveBuilder<'_>>(
266                 sess,
267                 &codegen_results,
268                 outputs,
269                 &codegen_results.crate_name.as_str(),
270                 &target_cpu,
271             );
272         });
273
274         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
275
276         Ok(())
277     }
278 }
279
280 fn target_triple(sess: &Session) -> target_lexicon::Triple {
281     sess.target.target.llvm_target.parse().unwrap()
282 }
283
284 fn build_isa(sess: &Session, enable_pic: bool) -> Box<dyn isa::TargetIsa + 'static> {
285     use target_lexicon::BinaryFormat;
286
287     let target_triple = crate::target_triple(sess);
288
289     let mut flags_builder = settings::builder();
290     if enable_pic {
291         flags_builder.enable("is_pic").unwrap();
292     } else {
293         flags_builder.set("is_pic", "false").unwrap();
294     }
295     flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
296     flags_builder
297         .set(
298             "enable_verifier",
299             if cfg!(debug_assertions) {
300                 "true"
301             } else {
302                 "false"
303             },
304         )
305         .unwrap();
306
307     let tls_model = match target_triple.binary_format {
308         BinaryFormat::Elf => "elf_gd",
309         BinaryFormat::Macho => "macho",
310         BinaryFormat::Coff => "coff",
311         _ => "none",
312     };
313     flags_builder.set("tls_model", tls_model).unwrap();
314
315     flags_builder.set("enable_simd", "true").unwrap();
316
317     // FIXME(CraneStation/cranelift#732) fix LICM in presence of jump tables
318     /*
319     use rustc_session::config::OptLevel;
320     match sess.opts.optimize {
321         OptLevel::No => {
322             flags_builder.set("opt_level", "none").unwrap();
323         }
324         OptLevel::Less | OptLevel::Default => {}
325         OptLevel::Aggressive => {
326             flags_builder.set("opt_level", "speed_and_size").unwrap();
327         }
328         OptLevel::Size | OptLevel::SizeMin => {
329             sess.warn("Optimizing for size is not supported. Just ignoring the request");
330         }
331     }*/
332
333     let flags = settings::Flags::new(flags_builder);
334
335     let mut isa_builder = cranelift_codegen::isa::lookup(target_triple).unwrap();
336     // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
337     // is interpreted as `bsr`.
338     isa_builder.enable("nehalem").unwrap();
339     isa_builder.finish(flags)
340 }
341
342 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
343 #[no_mangle]
344 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
345     Box::new(CraneliftCodegenBackend {
346         config: BackendConfig { use_jit: false },
347     })
348 }