cranelift_codegen/isa/s390x/
mod.rs

1//! IBM Z 64-bit Instruction Set Architecture.
2
3use crate::dominator_tree::DominatorTree;
4use crate::ir::{self, Function, Type};
5use crate::isa::s390x::settings as s390x_settings;
6#[cfg(feature = "unwind")]
7use crate::isa::unwind::systemv::RegisterMappingError;
8use crate::isa::{Builder as IsaBuilder, FunctionAlignment, TargetIsa};
9use crate::machinst::{
10    compile, CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet,
11    TextSectionBuilder, VCode,
12};
13use crate::result::CodegenResult;
14use crate::settings as shared_settings;
15use alloc::{boxed::Box, vec::Vec};
16use core::fmt;
17use cranelift_control::ControlPlane;
18use std::string::String;
19use target_lexicon::{Architecture, Triple};
20
21// New backend:
22mod abi;
23pub(crate) mod inst;
24mod lower;
25mod settings;
26
27use self::inst::EmitInfo;
28
29/// A IBM Z backend.
30pub struct S390xBackend {
31    triple: Triple,
32    flags: shared_settings::Flags,
33    isa_flags: s390x_settings::Flags,
34}
35
36impl S390xBackend {
37    /// Create a new IBM Z backend with the given (shared) flags.
38    pub fn new_with_flags(
39        triple: Triple,
40        flags: shared_settings::Flags,
41        isa_flags: s390x_settings::Flags,
42    ) -> S390xBackend {
43        S390xBackend {
44            triple,
45            flags,
46            isa_flags,
47        }
48    }
49
50    /// This performs lowering to VCode, register-allocates the code, computes block layout and
51    /// finalizes branches. The result is ready for binary emission.
52    fn compile_vcode(
53        &self,
54        func: &Function,
55        domtree: &DominatorTree,
56        ctrl_plane: &mut ControlPlane,
57    ) -> CodegenResult<(VCode<inst::Inst>, regalloc2::Output)> {
58        let emit_info = EmitInfo::new(self.isa_flags.clone());
59        let sigs = SigSet::new::<abi::S390xMachineDeps>(func, &self.flags)?;
60        let abi = abi::S390xCallee::new(func, self, &self.isa_flags, &sigs)?;
61        compile::compile::<S390xBackend>(func, domtree, self, abi, emit_info, sigs, ctrl_plane)
62    }
63}
64
65impl TargetIsa for S390xBackend {
66    fn compile_function(
67        &self,
68        func: &Function,
69        domtree: &DominatorTree,
70        want_disasm: bool,
71        ctrl_plane: &mut ControlPlane,
72    ) -> CodegenResult<CompiledCodeStencil> {
73        let flags = self.flags();
74        let (vcode, regalloc_result) = self.compile_vcode(func, domtree, ctrl_plane)?;
75
76        let emit_result = vcode.emit(&regalloc_result, want_disasm, flags, ctrl_plane);
77        let frame_size = emit_result.frame_size;
78        let value_labels_ranges = emit_result.value_labels_ranges;
79        let buffer = emit_result.buffer;
80        let sized_stackslot_offsets = emit_result.sized_stackslot_offsets;
81        let dynamic_stackslot_offsets = emit_result.dynamic_stackslot_offsets;
82
83        if let Some(disasm) = emit_result.disasm.as_ref() {
84            log::debug!("disassembly:\n{}", disasm);
85        }
86
87        Ok(CompiledCodeStencil {
88            buffer,
89            frame_size,
90            vcode: emit_result.disasm,
91            value_labels_ranges,
92            sized_stackslot_offsets,
93            dynamic_stackslot_offsets,
94            bb_starts: emit_result.bb_offsets,
95            bb_edges: emit_result.bb_edges,
96        })
97    }
98
99    fn name(&self) -> &'static str {
100        "s390x"
101    }
102
103    fn triple(&self) -> &Triple {
104        &self.triple
105    }
106
107    fn flags(&self) -> &shared_settings::Flags {
108        &self.flags
109    }
110
111    fn isa_flags(&self) -> Vec<shared_settings::Value> {
112        self.isa_flags.iter().collect()
113    }
114
115    fn dynamic_vector_bytes(&self, _dyn_ty: Type) -> u32 {
116        16
117    }
118
119    #[cfg(feature = "unwind")]
120    fn emit_unwind_info(
121        &self,
122        result: &CompiledCode,
123        kind: crate::isa::unwind::UnwindInfoKind,
124    ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
125        use crate::isa::unwind::UnwindInfo;
126        use crate::isa::unwind::UnwindInfoKind;
127        Ok(match kind {
128            UnwindInfoKind::SystemV => {
129                let mapper = self::inst::unwind::systemv::RegisterMapper;
130                Some(UnwindInfo::SystemV(
131                    crate::isa::unwind::systemv::create_unwind_info_from_insts(
132                        &result.buffer.unwind_info[..],
133                        result.buffer.data().len(),
134                        &mapper,
135                    )?,
136                ))
137            }
138            _ => None,
139        })
140    }
141
142    #[cfg(feature = "unwind")]
143    fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
144        Some(inst::unwind::systemv::create_cie())
145    }
146
147    #[cfg(feature = "unwind")]
148    fn map_regalloc_reg_to_dwarf(&self, reg: Reg) -> Result<u16, RegisterMappingError> {
149        inst::unwind::systemv::map_reg(reg).map(|reg| reg.0)
150    }
151
152    fn text_section_builder(&self, num_funcs: usize) -> Box<dyn TextSectionBuilder> {
153        Box::new(MachTextSectionBuilder::<inst::Inst>::new(num_funcs))
154    }
155
156    fn function_alignment(&self) -> FunctionAlignment {
157        inst::Inst::function_alignment()
158    }
159
160    fn page_size_align_log2(&self) -> u8 {
161        debug_assert_eq!(1 << 12, 0x1000);
162        12
163    }
164
165    #[cfg(feature = "disas")]
166    fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
167        use capstone::prelude::*;
168        let mut cs = Capstone::new()
169            .sysz()
170            .mode(arch::sysz::ArchMode::Default)
171            .build()?;
172
173        cs.set_skipdata(true)?;
174
175        Ok(cs)
176    }
177
178    fn pretty_print_reg(&self, reg: Reg, _size: u8) -> String {
179        inst::regs::pretty_print_reg(reg)
180    }
181
182    fn has_native_fma(&self) -> bool {
183        true
184    }
185
186    fn has_x86_blendv_lowering(&self, _: Type) -> bool {
187        false
188    }
189
190    fn has_x86_pshufb_lowering(&self) -> bool {
191        false
192    }
193
194    fn has_x86_pmulhrsw_lowering(&self) -> bool {
195        false
196    }
197
198    fn has_x86_pmaddubsw_lowering(&self) -> bool {
199        false
200    }
201
202    fn default_argument_extension(&self) -> ir::ArgumentExtension {
203        // This is copied/carried over from a historical piece of code in
204        // Wasmtime:
205        //
206        // https://github.com/bytecodealliance/wasmtime/blob/a018a5a9addb77d5998021a0150192aa955c71bf/crates/cranelift/src/lib.rs#L366-L374
207        //
208        // Whether or not it is still applicable here is unsure, but it's left
209        // the same as-is for now to reduce the likelihood of problems arising.
210        ir::ArgumentExtension::Uext
211    }
212}
213
214impl fmt::Display for S390xBackend {
215    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
216        f.debug_struct("MachBackend")
217            .field("name", &self.name())
218            .field("triple", &self.triple())
219            .field("flags", &format!("{}", self.flags()))
220            .finish()
221    }
222}
223
224/// Create a new `isa::Builder`.
225pub fn isa_builder(triple: Triple) -> IsaBuilder {
226    assert!(triple.architecture == Architecture::S390x);
227    IsaBuilder {
228        triple,
229        setup: s390x_settings::builder(),
230        constructor: |triple, shared_flags, builder| {
231            let isa_flags = s390x_settings::Flags::new(&shared_flags, builder);
232            let backend = S390xBackend::new_with_flags(triple, shared_flags, isa_flags);
233            Ok(backend.wrapped())
234        },
235    }
236}