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