Skip to main content

rustc_codegen_ssa/traits/
backend.rs

1use std::any::Any;
2use std::hash::Hash;
3
4use rustc_ast::expand::allocator::AllocatorMethod;
5use rustc_data_structures::sync::{DynSend, DynSync};
6use rustc_metadata::EncodedMetadata;
7use rustc_metadata::creader::MetadataLoaderDyn;
8use rustc_middle::dep_graph::WorkProductMap;
9use rustc_middle::ty::TyCtxt;
10use rustc_middle::util::Providers;
11use rustc_session::config::{OutputFilenames, PrintRequest};
12use rustc_session::{CodegenBackendInit, EarlySession, IncrCompSession, Session};
13use rustc_span::Symbol;
14use rustc_structures::CrateType;
15
16use super::CodegenObject;
17use crate::back::archive::ArArchiveBuilderBuilder;
18use crate::back::link::link_binary;
19use crate::{CompiledModules, CrateInfo, ModuleCodegen, TargetConfig};
20
21pub trait BackendTypes {
22    type Function: CodegenObject;
23    type BasicBlock: Copy;
24    type Funclet;
25
26    type Value: CodegenObject + PartialEq;
27    type Type: CodegenObject + PartialEq;
28    type FunctionSignature: CodegenObject + PartialEq;
29
30    // FIXME(eddyb) find a common convention for all of the debuginfo-related
31    // names (choose between `Dbg`, `Debug`, `DebugInfo`, `DI` etc.).
32    type DIScope: Copy + Hash + PartialEq + Eq;
33    type DILocation: Copy;
34    type DIVariable: Copy;
35}
36
37pub trait CodegenBackend {
38    fn name(&self) -> &'static str;
39
40    fn init(&mut self, _sess: &EarlySession) -> CodegenBackendInit {
41        Default::default()
42    }
43
44    fn print(&self, _req: &PrintRequest, _out: &mut String, _sess: &Session) {}
45
46    /// Collect target-specific options that should be set in `cfg(...)`, including
47    /// `target_feature` and support for unstable float types.
48    fn target_config(&self, _sess: &EarlySession) -> TargetConfig {
49        TargetConfig {
50            internal_target_features: Default::default(),
51            // `true` is used as a default so backends need to acknowledge when they do not
52            // support the float types, rather than accidentally quietly skipping all tests.
53            has_reliable_f16: true,
54            has_reliable_f16_math: true,
55            has_reliable_f128: true,
56            has_reliable_f128_math: true,
57        }
58    }
59
60    fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
61        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CrateType::Executable, CrateType::Dylib, CrateType::Rlib,
                CrateType::StaticLib, CrateType::Cdylib, CrateType::ProcMacro,
                CrateType::Sdylib]))vec![
62            CrateType::Executable,
63            CrateType::Dylib,
64            CrateType::Rlib,
65            CrateType::StaticLib,
66            CrateType::Cdylib,
67            CrateType::ProcMacro,
68            CrateType::Sdylib,
69        ]
70    }
71
72    fn print_passes(&self) {}
73
74    fn print_version(&self) {}
75
76    /// Value printed by `--print=backend-has-zstd`.
77    ///
78    /// Used by compiletest to determine whether tests involving zstd compression
79    /// (e.g. `-Zdebuginfo-compression=zstd`) should be executed or skipped.
80    fn has_zstd(&self) -> bool {
81        false
82    }
83
84    /// Value printed by `--print=backend-has-mnemonic:...`.
85    ///
86    /// Used by compiletest to determine whether tests involving `asm!()` should
87    /// be executed or skipped.
88    fn has_mnemonic(&self, _sess: &Session, _mnemonic: &str) -> bool {
89        false
90    }
91
92    /// The metadata loader used to load rlib and dylib metadata.
93    ///
94    /// Alternative codegen backends may want to use different rlib or dylib formats than the
95    /// default native static archives and dynamic libraries.
96    fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
97        Box::new(crate::back::metadata::DefaultMetadataLoader)
98    }
99
100    /// Allows queries to be overridden. Not used by any in-tree backends, but rustc_codegen_spirv
101    /// and rustc_codegen_nvvm use it.
102    fn provide(&self, _providers: &mut Providers) {}
103
104    fn target_cpu(&self, sess: &Session) -> String;
105
106    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any>;
107
108    /// This is called on the returned `Box<dyn Any>` from [`codegen_crate`](Self::codegen_crate)
109    ///
110    /// # Panics
111    ///
112    /// Panics when the passed `Box<dyn Any>` was not returned by [`codegen_crate`](Self::codegen_crate).
113    fn join_codegen(
114        &self,
115        ongoing_codegen: Box<dyn Any>,
116        sess: &Session,
117        incr_comp_session: Option<&IncrCompSession>,
118        outputs: &OutputFilenames,
119        crate_info: &CrateInfo,
120    ) -> (CompiledModules, WorkProductMap);
121
122    fn print_pass_timings(&self) {}
123
124    fn print_statistics(&self) {}
125
126    fn print_statistics_json(&self) -> String {
127        String::new()
128    }
129
130    /// This is called on the returned [`CompiledModules`] from [`join_codegen`](Self::join_codegen).
131    fn link(
132        &self,
133        sess: &Session,
134        compiled_modules: CompiledModules,
135        crate_info: CrateInfo,
136        metadata: EncodedMetadata,
137        outputs: &OutputFilenames,
138    ) {
139        link_binary(
140            sess,
141            &ArArchiveBuilderBuilder,
142            compiled_modules,
143            crate_info,
144            metadata,
145            outputs,
146            self.name(),
147        );
148    }
149}
150
151pub trait ExtraBackendMethods: Send + Sync + DynSend + DynSync {
152    type Module;
153
154    fn codegen_allocator<'tcx>(
155        &self,
156        tcx: TyCtxt<'tcx>,
157        module_name: &str,
158        methods: &[AllocatorMethod],
159    ) -> Self::Module;
160
161    /// This generates the codegen unit and returns it along with
162    /// a `u64` giving an estimate of the unit's processing cost.
163    fn compile_codegen_unit(
164        &self,
165        tcx: TyCtxt<'_>,
166        cgu_name: Symbol,
167        bitcode_needed: bool,
168    ) -> (ModuleCodegen<Self::Module>, u64);
169}