rustc_codegen_ssa/traits/
backend.rs

1use std::any::Any;
2use std::hash::Hash;
3
4use rustc_ast::expand::allocator::AllocatorKind;
5use rustc_data_structures::fx::FxIndexMap;
6use rustc_data_structures::sync::{DynSend, DynSync};
7use rustc_metadata::EncodedMetadata;
8use rustc_metadata::creader::MetadataLoaderDyn;
9use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
10use rustc_middle::ty::TyCtxt;
11use rustc_middle::util::Providers;
12use rustc_session::Session;
13use rustc_session::config::{self, OutputFilenames, PrintRequest};
14use rustc_span::Symbol;
15
16use super::CodegenObject;
17use super::write::WriteBackendMethods;
18use crate::back::archive::ArArchiveBuilderBuilder;
19use crate::back::link::link_binary;
20use crate::back::write::TargetMachineFactoryFn;
21use crate::{CodegenResults, ModuleCodegen, TargetConfig};
22
23pub trait BackendTypes {
24    type Value: CodegenObject + PartialEq;
25    type Metadata: CodegenObject;
26    type Function: CodegenObject;
27
28    type BasicBlock: Copy;
29    type Type: CodegenObject + PartialEq;
30    type Funclet;
31
32    // FIXME(eddyb) find a common convention for all of the debuginfo-related
33    // names (choose between `Dbg`, `Debug`, `DebugInfo`, `DI` etc.).
34    type DIScope: Copy + Hash + PartialEq + Eq;
35    type DILocation: Copy;
36    type DIVariable: Copy;
37}
38
39pub trait CodegenBackend {
40    /// Locale resources for diagnostic messages - a string the content of the Fluent resource.
41    /// Called before `init` so that all other functions are able to emit translatable diagnostics.
42    fn locale_resource(&self) -> &'static str;
43
44    fn name(&self) -> &'static str;
45
46    fn init(&self, _sess: &Session) {}
47
48    fn print(&self, _req: &PrintRequest, _out: &mut String, _sess: &Session) {}
49
50    /// Collect target-specific options that should be set in `cfg(...)`, including
51    /// `target_feature` and support for unstable float types.
52    fn target_config(&self, _sess: &Session) -> TargetConfig {
53        TargetConfig {
54            target_features: vec![],
55            unstable_target_features: vec![],
56            // `true` is used as a default so backends need to acknowledge when they do not
57            // support the float types, rather than accidentally quietly skipping all tests.
58            has_reliable_f16: true,
59            has_reliable_f16_math: true,
60            has_reliable_f128: true,
61            has_reliable_f128_math: true,
62        }
63    }
64
65    fn print_passes(&self) {}
66
67    fn print_version(&self) {}
68
69    /// The metadata loader used to load rlib and dylib metadata.
70    ///
71    /// Alternative codegen backends may want to use different rlib or dylib formats than the
72    /// default native static archives and dynamic libraries.
73    fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
74        Box::new(crate::back::metadata::DefaultMetadataLoader)
75    }
76
77    fn provide(&self, _providers: &mut Providers) {}
78
79    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any>;
80
81    /// This is called on the returned `Box<dyn Any>` from [`codegen_crate`](Self::codegen_crate)
82    ///
83    /// # Panics
84    ///
85    /// Panics when the passed `Box<dyn Any>` was not returned by [`codegen_crate`](Self::codegen_crate).
86    fn join_codegen(
87        &self,
88        ongoing_codegen: Box<dyn Any>,
89        sess: &Session,
90        outputs: &OutputFilenames,
91    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>);
92
93    /// This is called on the returned [`CodegenResults`] from [`join_codegen`](Self::join_codegen).
94    fn link(
95        &self,
96        sess: &Session,
97        codegen_results: CodegenResults,
98        metadata: EncodedMetadata,
99        outputs: &OutputFilenames,
100    ) {
101        link_binary(
102            sess,
103            &ArArchiveBuilderBuilder,
104            codegen_results,
105            metadata,
106            outputs,
107            self.name(),
108        );
109    }
110}
111
112pub trait ExtraBackendMethods:
113    CodegenBackend + WriteBackendMethods + Sized + Send + Sync + DynSend + DynSync
114{
115    fn codegen_allocator<'tcx>(
116        &self,
117        tcx: TyCtxt<'tcx>,
118        module_name: &str,
119        kind: AllocatorKind,
120        alloc_error_handler_kind: AllocatorKind,
121    ) -> Self::Module;
122
123    /// This generates the codegen unit and returns it along with
124    /// a `u64` giving an estimate of the unit's processing cost.
125    fn compile_codegen_unit(
126        &self,
127        tcx: TyCtxt<'_>,
128        cgu_name: Symbol,
129    ) -> (ModuleCodegen<Self::Module>, u64);
130
131    fn target_machine_factory(
132        &self,
133        sess: &Session,
134        opt_level: config::OptLevel,
135        target_features: &[String],
136    ) -> TargetMachineFactoryFn<Self>;
137
138    fn spawn_named_thread<F, T>(
139        _time_trace: bool,
140        name: String,
141        f: F,
142    ) -> std::io::Result<std::thread::JoinHandle<T>>
143    where
144        F: FnOnce() -> T,
145        F: Send + 'static,
146        T: Send + 'static,
147    {
148        std::thread::Builder::new().name(name).spawn(f)
149    }
150
151    /// Returns `true` if this backend can be safely called from multiple threads.
152    ///
153    /// Defaults to `true`.
154    fn supports_parallel(&self) -> bool {
155        true
156    }
157}