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