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)]
7 #[cfg(feature = "jit")]
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;
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;
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;
39 use cranelift_codegen::settings::{self, Configurable};
41 use crate::constant::ConstantCx;
42 use crate::prelude::*;
66 mod target_features_whitelist;
74 pub(crate) use std::convert::{TryFrom, TryInto};
76 pub(crate) use rustc_ast::ast::{FloatTy, IntTy, UintTy};
77 pub(crate) use rustc_span::Span;
79 pub(crate) use rustc_middle::bug;
80 pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
81 pub(crate) use rustc_middle::mir::{self, *};
82 pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
83 pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
84 pub(crate) use rustc_middle::ty::{
85 self, FnSig, Instance, InstanceDef, ParamEnv, Ty, TyCtxt, TypeAndMut, TypeFoldable,
88 pub(crate) use rustc_data_structures::fx::FxHashMap;
90 pub(crate) use rustc_index::vec::Idx;
92 pub(crate) use cranelift_codegen::Context;
93 pub(crate) use cranelift_codegen::entity::EntitySet;
94 pub(crate) use cranelift_codegen::ir::{AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc, StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value};
95 pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
96 pub(crate) use cranelift_codegen::ir::function::Function;
97 pub(crate) use cranelift_codegen::ir::types;
98 pub(crate) use cranelift_codegen::isa::{self, CallConv};
99 pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
100 pub(crate) use cranelift_module::{
101 self, Backend, DataContext, DataId, FuncId, Linkage, Module,
104 pub(crate) use crate::abi::*;
105 pub(crate) use crate::base::{trans_operand, trans_place};
106 pub(crate) use crate::cast::*;
107 pub(crate) use crate::common::*;
108 pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
109 pub(crate) use crate::pointer::Pointer;
110 pub(crate) use crate::trap::*;
111 pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
114 struct PrintOnPanic<F: Fn() -> String>(F);
115 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
117 if ::std::thread::panicking() {
118 println!("{}", (self.0)());
123 struct CodegenCx<'tcx, B: Backend + 'static> {
126 constants_cx: ConstantCx,
127 cached_context: Context,
128 vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
129 debug_context: Option<DebugContext<'tcx>>,
130 unwind_context: UnwindContext<'tcx>,
133 impl<'tcx, B: Backend + 'static> CodegenCx<'tcx, B> {
139 let unwind_context = UnwindContext::new(tcx, module.isa());
140 let debug_context = if debug_info {
141 Some(DebugContext::new(
151 constants_cx: ConstantCx::default(),
152 cached_context: Context::new(),
153 vtables: FxHashMap::default(),
159 fn finalize(mut self) -> (Module<B>, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
160 self.constants_cx.finalize(self.tcx, &mut self.module);
161 (self.module, self.debug_context, self.unwind_context)
165 struct CraneliftCodegenBackend;
167 impl CodegenBackend for CraneliftCodegenBackend {
168 fn init(&self, sess: &Session) {
169 if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
170 sess.warn("LTO is not supported. You may get a linker error.");
174 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
175 Box::new(crate::metadata::CraneliftMetadataLoader)
178 fn provide(&self, providers: &mut Providers<'_>) {
179 providers.target_features_whitelist = |tcx, cnum| {
180 assert_eq!(cnum, LOCAL_CRATE);
181 if tcx.sess.opts.actually_rustdoc {
182 // rustdoc needs to be able to document functions that use all the features, so
183 // whitelist them all
184 target_features_whitelist::all_known_features()
185 .chain(Some(("cg_clif", None)))
186 .map(|(a, b)| (a.to_string(), b))
189 target_features_whitelist::target_feature_whitelist(tcx.sess)
191 .chain(&Some(("cg_clif", None)))
192 .map(|&(a, b)| (a.to_string(), b))
197 fn provide_extern(&self, _providers: &mut Providers<'_>) {}
199 fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
200 vec![rustc_span::Symbol::intern("cg_clif")]
203 fn codegen_crate<'tcx>(
206 metadata: EncodedMetadata,
207 need_metadata_module: bool,
209 let res = driver::codegen_crate(tcx, metadata, need_metadata_module);
211 rustc_symbol_mangling::test::report_symbol_names(tcx);
218 ongoing_codegen: Box<dyn Any>,
220 dep_graph: &DepGraph,
221 ) -> Result<Box<dyn Any>, ErrorReported> {
222 let (codegen_results, work_products) = *ongoing_codegen.downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>().unwrap();
224 sess.time("serialize_work_products", move || {
225 rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
228 Ok(Box::new(codegen_results))
235 outputs: &OutputFilenames,
236 ) -> Result<(), ErrorReported> {
237 use rustc_codegen_ssa::back::link::link_binary;
239 sess.abort_if_errors();
241 let codegen_results = *res
242 .downcast::<CodegenResults>()
243 .expect("Expected CraneliftCodegenBackend's CodegenResult, found Box<Any>");
245 let _timer = sess.prof.generic_activity("link_crate");
247 sess.time("linking", || {
248 let target_cpu = crate::target_triple(sess).to_string();
249 link_binary::<crate::archive::ArArchiveBuilder<'_>>(
253 &codegen_results.crate_name.as_str(),
258 rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
264 fn target_triple(sess: &Session) -> target_lexicon::Triple {
265 sess.target.target.llvm_target.parse().unwrap()
268 fn build_isa(sess: &Session, enable_pic: bool) -> Box<dyn isa::TargetIsa + 'static> {
269 use target_lexicon::BinaryFormat;
271 let target_triple = crate::target_triple(sess);
273 let mut flags_builder = settings::builder();
275 flags_builder.enable("is_pic").unwrap();
277 flags_builder.set("is_pic", "false").unwrap();
279 flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
283 if cfg!(debug_assertions) {
291 let tls_model = match target_triple.binary_format {
292 BinaryFormat::Elf => "elf_gd",
293 BinaryFormat::Macho => "macho",
294 BinaryFormat::Coff => "coff",
297 flags_builder.set("tls_model", tls_model).unwrap();
299 // FIXME(CraneStation/cranelift#732) fix LICM in presence of jump tables
301 use rustc_session::config::OptLevel;
302 match sess.opts.optimize {
304 flags_builder.set("opt_level", "none").unwrap();
306 OptLevel::Less | OptLevel::Default => {}
307 OptLevel::Aggressive => {
308 flags_builder.set("opt_level", "speed_and_size").unwrap();
310 OptLevel::Size | OptLevel::SizeMin => {
311 sess.warn("Optimizing for size is not supported. Just ignoring the request");
315 let flags = settings::Flags::new(flags_builder);
316 cranelift_codegen::isa::lookup(target_triple)
321 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
323 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
324 Box::new(CraneliftCodegenBackend)