5 associated_type_bounds,
11 #![warn(rust_2018_idioms)]
12 #![warn(unused_lifetimes)]
13 #![warn(unreachable_pub)]
15 #[cfg(feature = "jit")]
19 extern crate rustc_middle;
20 extern crate rustc_ast;
21 extern crate rustc_codegen_ssa;
22 extern crate rustc_data_structures;
23 extern crate rustc_errors;
24 extern crate rustc_fs_util;
25 extern crate rustc_hir;
26 extern crate rustc_incremental;
27 extern crate rustc_index;
28 extern crate rustc_session;
29 extern crate rustc_span;
30 extern crate rustc_target;
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;
37 use std::str::FromStr;
39 use rustc_codegen_ssa::traits::CodegenBackend;
40 use rustc_codegen_ssa::CodegenResults;
41 use rustc_errors::ErrorReported;
42 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
43 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoader};
44 use rustc_middle::ty::query::Providers;
45 use rustc_session::config::OutputFilenames;
46 use rustc_session::Session;
48 use cranelift_codegen::settings::{self, Configurable};
50 use crate::constant::ConstantCx;
51 use crate::prelude::*;
83 pub(crate) use std::convert::{TryFrom, TryInto};
85 pub(crate) use rustc_ast::ast::{FloatTy, IntTy, UintTy};
86 pub(crate) use rustc_span::Span;
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, Instance, InstanceDef, ParamEnv, Ty, TyCtxt, TypeAndMut, TypeFoldable,
95 pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
97 pub(crate) use rustc_data_structures::fx::FxHashMap;
99 pub(crate) use rustc_index::vec::Idx;
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,
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::{self, DataContext, DataId, FuncId, Linkage, Module};
114 pub(crate) use crate::abi::*;
115 pub(crate) use crate::base::{codegen_operand, codegen_place};
116 pub(crate) use crate::cast::*;
117 pub(crate) use crate::common::*;
118 pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
119 pub(crate) use crate::pointer::Pointer;
120 pub(crate) use crate::trap::*;
121 pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
124 struct PrintOnPanic<F: Fn() -> String>(F);
125 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
127 if ::std::thread::panicking() {
128 println!("{}", (self.0)());
133 struct CodegenCx<'tcx, M: Module> {
137 constants_cx: ConstantCx,
138 cached_context: Context,
139 vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
140 debug_context: Option<DebugContext<'tcx>>,
141 unwind_context: UnwindContext<'tcx>,
144 impl<'tcx, M: Module> CodegenCx<'tcx, M> {
145 fn new(tcx: TyCtxt<'tcx>, module: M, debug_info: bool, pic_eh_frame: bool) -> Self {
146 let unwind_context = UnwindContext::new(tcx, module.isa(), pic_eh_frame);
147 let debug_context = if debug_info {
148 Some(DebugContext::new(tcx, module.isa()))
155 global_asm: String::new(),
156 constants_cx: ConstantCx::default(),
157 cached_context: Context::new(),
158 vtables: FxHashMap::default(),
164 fn finalize(mut self) -> (M, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
165 self.constants_cx.finalize(self.tcx, &mut self.module);
175 #[derive(Copy, Clone, Debug)]
176 pub enum CodegenMode {
182 impl Default for CodegenMode {
183 fn default() -> Self {
188 impl FromStr for CodegenMode {
191 fn from_str(s: &str) -> Result<Self, Self::Err> {
193 "aot" => Ok(CodegenMode::Aot),
194 "jit" => Ok(CodegenMode::Jit),
195 "jit-lazy" => Ok(CodegenMode::JitLazy),
196 _ => Err(format!("Unknown codegen mode `{}`", s)),
201 #[derive(Copy, Clone, Debug, Default)]
202 pub struct BackendConfig {
203 pub codegen_mode: CodegenMode,
207 fn from_opts(opts: &[String]) -> Result<Self, String> {
208 let mut config = BackendConfig::default();
210 if let Some((name, value)) = opt.split_once('=') {
212 "mode" => config.codegen_mode = value.parse()?,
213 _ => return Err(format!("Unknown option `{}`", name)),
216 return Err(format!("Invalid option `{}`", opt));
223 pub struct CraneliftCodegenBackend {
224 pub config: Option<BackendConfig>,
227 impl CodegenBackend for CraneliftCodegenBackend {
228 fn init(&self, sess: &Session) {
229 if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
230 sess.warn("LTO is not supported. You may get a linker error.");
234 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
235 Box::new(crate::metadata::CraneliftMetadataLoader)
238 fn provide(&self, _providers: &mut Providers) {}
239 fn provide_extern(&self, _providers: &mut Providers) {}
241 fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
245 fn codegen_crate<'tcx>(
248 metadata: EncodedMetadata,
249 need_metadata_module: bool,
251 let config = if let Some(config) = self.config {
254 BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
255 .unwrap_or_else(|err| tcx.sess.fatal(&err))
257 let res = driver::codegen_crate(tcx, metadata, need_metadata_module, config);
264 ongoing_codegen: Box<dyn Any>,
266 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
268 .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
275 codegen_results: CodegenResults,
276 outputs: &OutputFilenames,
277 ) -> Result<(), ErrorReported> {
278 use rustc_codegen_ssa::back::link::link_binary;
280 let target_cpu = crate::target_triple(sess).to_string();
281 link_binary::<crate::archive::ArArchiveBuilder<'_>>(
285 &codegen_results.crate_name.as_str(),
293 fn target_triple(sess: &Session) -> target_lexicon::Triple {
294 sess.target.llvm_target.parse().unwrap()
297 fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
298 use target_lexicon::BinaryFormat;
300 let target_triple = crate::target_triple(sess);
302 let mut flags_builder = settings::builder();
303 flags_builder.enable("is_pic").unwrap();
304 flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
308 if cfg!(debug_assertions) {
316 let tls_model = match target_triple.binary_format {
317 BinaryFormat::Elf => "elf_gd",
318 BinaryFormat::Macho => "macho",
319 BinaryFormat::Coff => "coff",
322 flags_builder.set("tls_model", tls_model).unwrap();
324 flags_builder.set("enable_simd", "true").unwrap();
326 use rustc_session::config::OptLevel;
327 match sess.opts.optimize {
329 flags_builder.set("opt_level", "none").unwrap();
331 OptLevel::Less | OptLevel::Default => {}
332 OptLevel::Aggressive => {
333 flags_builder.set("opt_level", "speed_and_size").unwrap();
335 OptLevel::Size | OptLevel::SizeMin => {
336 sess.warn("Optimizing for size is not supported. Just ignoring the request");
340 let flags = settings::Flags::new(flags_builder);
342 let variant = if cfg!(feature = "oldbe") {
343 cranelift_codegen::isa::BackendVariant::Legacy
345 cranelift_codegen::isa::BackendVariant::MachInst
347 let mut isa_builder = cranelift_codegen::isa::lookup_variant(target_triple, variant).unwrap();
348 // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
349 // is interpreted as `bsr`.
350 isa_builder.enable("nehalem").unwrap();
351 isa_builder.finish(flags)
354 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
356 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
357 Box::new(CraneliftCodegenBackend { config: None })