5 associated_type_bounds,
10 #![warn(rust_2018_idioms)]
11 #![warn(unused_lifetimes)]
12 #![warn(unreachable_pub)]
14 #[cfg(feature = "jit")]
18 extern crate rustc_middle;
19 extern crate rustc_ast;
20 extern crate rustc_codegen_ssa;
21 extern crate rustc_data_structures;
22 extern crate rustc_errors;
23 extern crate rustc_fs_util;
24 extern crate rustc_hir;
25 extern crate rustc_incremental;
26 extern crate rustc_index;
27 extern crate rustc_session;
28 extern crate rustc_span;
29 extern crate rustc_target;
31 // This prevents duplicating functions and statics that are already part of the host rustc process.
32 #[allow(unused_extern_crates)]
33 extern crate rustc_driver;
36 use std::str::FromStr;
38 use rustc_codegen_ssa::traits::CodegenBackend;
39 use rustc_codegen_ssa::CodegenResults;
40 use rustc_errors::ErrorReported;
41 use rustc_middle::dep_graph::{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;
47 use cranelift_codegen::settings::{self, Configurable};
49 use crate::constant::ConstantCx;
50 use crate::prelude::*;
82 pub(crate) use std::convert::{TryFrom, TryInto};
84 pub(crate) use rustc_span::Span;
86 pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
87 pub(crate) use rustc_middle::bug;
88 pub(crate) use rustc_middle::mir::{self, *};
89 pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
90 pub(crate) use rustc_middle::ty::{
91 self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
94 pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
96 pub(crate) use rustc_data_structures::fx::FxHashMap;
98 pub(crate) use rustc_index::vec::Idx;
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,
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};
113 pub(crate) use crate::abi::*;
114 pub(crate) use crate::base::{codegen_operand, codegen_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};
123 struct PrintOnPanic<F: Fn() -> String>(F);
124 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
126 if ::std::thread::panicking() {
127 println!("{}", (self.0)());
132 struct CodegenCx<'tcx, M: Module> {
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>,
143 impl<'tcx, M: Module> CodegenCx<'tcx, M> {
144 fn new(tcx: TyCtxt<'tcx>, module: M, debug_info: bool, pic_eh_frame: bool) -> Self {
145 let unwind_context = UnwindContext::new(tcx, module.isa(), pic_eh_frame);
146 let debug_context = if debug_info {
147 Some(DebugContext::new(tcx, module.isa()))
154 global_asm: String::new(),
155 constants_cx: ConstantCx::default(),
156 cached_context: Context::new(),
157 vtables: FxHashMap::default(),
163 fn finalize(mut self) -> (M, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
164 self.constants_cx.finalize(self.tcx, &mut self.module);
174 #[derive(Copy, Clone, Debug)]
175 pub enum CodegenMode {
181 impl Default for CodegenMode {
182 fn default() -> Self {
187 impl FromStr for CodegenMode {
190 fn from_str(s: &str) -> Result<Self, Self::Err> {
192 "aot" => Ok(CodegenMode::Aot),
193 "jit" => Ok(CodegenMode::Jit),
194 "jit-lazy" => Ok(CodegenMode::JitLazy),
195 _ => Err(format!("Unknown codegen mode `{}`", s)),
200 #[derive(Copy, Clone, Debug, Default)]
201 pub struct BackendConfig {
202 pub codegen_mode: CodegenMode,
206 fn from_opts(opts: &[String]) -> Result<Self, String> {
207 let mut config = BackendConfig::default();
209 if let Some((name, value)) = opt.split_once('=') {
211 "mode" => config.codegen_mode = value.parse()?,
212 _ => return Err(format!("Unknown option `{}`", name)),
215 return Err(format!("Invalid option `{}`", opt));
222 pub struct CraneliftCodegenBackend {
223 pub config: Option<BackendConfig>,
226 impl CodegenBackend for CraneliftCodegenBackend {
227 fn init(&self, sess: &Session) {
228 if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
229 sess.warn("LTO is not supported. You may get a linker error.");
233 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
234 Box::new(crate::metadata::CraneliftMetadataLoader)
237 fn provide(&self, _providers: &mut Providers) {}
238 fn provide_extern(&self, _providers: &mut Providers) {}
240 fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
244 fn codegen_crate<'tcx>(
247 metadata: EncodedMetadata,
248 need_metadata_module: bool,
250 let config = if let Some(config) = self.config {
253 BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
254 .unwrap_or_else(|err| tcx.sess.fatal(&err))
256 let res = driver::codegen_crate(tcx, metadata, need_metadata_module, config);
263 ongoing_codegen: Box<dyn Any>,
265 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
267 .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
274 codegen_results: CodegenResults,
275 outputs: &OutputFilenames,
276 ) -> Result<(), ErrorReported> {
277 use rustc_codegen_ssa::back::link::link_binary;
279 let target_cpu = crate::target_triple(sess).to_string();
280 link_binary::<crate::archive::ArArchiveBuilder<'_>>(
284 &codegen_results.crate_name.as_str(),
292 fn target_triple(sess: &Session) -> target_lexicon::Triple {
293 sess.target.llvm_target.parse().unwrap()
296 fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
297 use target_lexicon::BinaryFormat;
299 let target_triple = crate::target_triple(sess);
301 let mut flags_builder = settings::builder();
302 flags_builder.enable("is_pic").unwrap();
303 flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
307 if cfg!(debug_assertions) {
315 let tls_model = match target_triple.binary_format {
316 BinaryFormat::Elf => "elf_gd",
317 BinaryFormat::Macho => "macho",
318 BinaryFormat::Coff => "coff",
321 flags_builder.set("tls_model", tls_model).unwrap();
323 flags_builder.set("enable_simd", "true").unwrap();
325 use rustc_session::config::OptLevel;
326 match sess.opts.optimize {
328 flags_builder.set("opt_level", "none").unwrap();
330 OptLevel::Less | OptLevel::Default => {}
331 OptLevel::Aggressive => {
332 flags_builder.set("opt_level", "speed_and_size").unwrap();
334 OptLevel::Size | OptLevel::SizeMin => {
335 sess.warn("Optimizing for size is not supported. Just ignoring the request");
339 let flags = settings::Flags::new(flags_builder);
341 let variant = if cfg!(feature = "oldbe") {
342 cranelift_codegen::isa::BackendVariant::Legacy
344 cranelift_codegen::isa::BackendVariant::MachInst
346 let mut isa_builder = cranelift_codegen::isa::lookup_variant(target_triple, variant).unwrap();
347 // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
348 // is interpreted as `bsr`.
349 isa_builder.enable("nehalem").unwrap();
350 isa_builder.finish(flags)
353 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
355 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
356 Box::new(CraneliftCodegenBackend { config: None })