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