cranelift_codegen/isa/x64/inst/unwind/
systemv.rs

1//! Unwind information for System V ABI (x86-64).
2
3use crate::isa::unwind::systemv::RegisterMappingError;
4use crate::machinst::{Reg, RegClass};
5use gimli::{write::CommonInformationEntry, Encoding, Format, Register, X86_64};
6
7/// Creates a new x86-64 common information entry (CIE).
8pub fn create_cie() -> CommonInformationEntry {
9    use gimli::write::CallFrameInstruction;
10
11    let mut entry = CommonInformationEntry::new(
12        Encoding {
13            address_size: 8,
14            format: Format::Dwarf32,
15            version: 1,
16        },
17        1,  // Code alignment factor
18        -8, // Data alignment factor
19        X86_64::RA,
20    );
21
22    // Every frame will start with the call frame address (CFA) at RSP+8
23    // It is +8 to account for the push of the return address by the call instruction
24    entry.add_instruction(CallFrameInstruction::Cfa(X86_64::RSP, 8));
25
26    // Every frame will start with the return address at RSP (CFA-8 = RSP+8-8 = RSP)
27    entry.add_instruction(CallFrameInstruction::Offset(X86_64::RA, -8));
28
29    entry
30}
31
32/// Map Cranelift registers to their corresponding Gimli registers.
33pub fn map_reg(reg: Reg) -> Result<Register, RegisterMappingError> {
34    // Mapping from https://github.com/bytecodealliance/cranelift/pull/902 by @iximeow
35    const X86_GP_REG_MAP: [gimli::Register; 16] = [
36        X86_64::RAX,
37        X86_64::RCX,
38        X86_64::RDX,
39        X86_64::RBX,
40        X86_64::RSP,
41        X86_64::RBP,
42        X86_64::RSI,
43        X86_64::RDI,
44        X86_64::R8,
45        X86_64::R9,
46        X86_64::R10,
47        X86_64::R11,
48        X86_64::R12,
49        X86_64::R13,
50        X86_64::R14,
51        X86_64::R15,
52    ];
53    const X86_XMM_REG_MAP: [gimli::Register; 16] = [
54        X86_64::XMM0,
55        X86_64::XMM1,
56        X86_64::XMM2,
57        X86_64::XMM3,
58        X86_64::XMM4,
59        X86_64::XMM5,
60        X86_64::XMM6,
61        X86_64::XMM7,
62        X86_64::XMM8,
63        X86_64::XMM9,
64        X86_64::XMM10,
65        X86_64::XMM11,
66        X86_64::XMM12,
67        X86_64::XMM13,
68        X86_64::XMM14,
69        X86_64::XMM15,
70    ];
71
72    match reg.class() {
73        RegClass::Int => {
74            // x86 GP registers have a weird mapping to DWARF registers, so we use a
75            // lookup table.
76            Ok(X86_GP_REG_MAP[reg.to_real_reg().unwrap().hw_enc() as usize])
77        }
78        RegClass::Float => Ok(X86_XMM_REG_MAP[reg.to_real_reg().unwrap().hw_enc() as usize]),
79    }
80}
81
82pub(crate) struct RegisterMapper;
83
84impl crate::isa::unwind::systemv::RegisterMapper<Reg> for RegisterMapper {
85    fn map(&self, reg: Reg) -> Result<u16, RegisterMappingError> {
86        Ok(map_reg(reg)?.0)
87    }
88    fn sp(&self) -> u16 {
89        X86_64::RSP.0
90    }
91    fn fp(&self) -> Option<u16> {
92        Some(X86_64::RBP.0)
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use crate::cursor::{Cursor, FuncCursor};
99    use crate::ir::{
100        types, AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind,
101    };
102    use crate::isa::{lookup, CallConv};
103    use crate::settings::{builder, Flags};
104    use crate::Context;
105    use gimli::write::Address;
106    use std::str::FromStr;
107    use target_lexicon::triple;
108
109    #[test]
110    fn test_simple_func() {
111        let isa = lookup(triple!("x86_64"))
112            .expect("expect x86 ISA")
113            .finish(Flags::new(builder()))
114            .expect("expect backend creation to succeed");
115
116        let mut context = Context::for_function(create_function(
117            CallConv::SystemV,
118            Some(StackSlotData::new(StackSlotKind::ExplicitSlot, 64)),
119        ));
120
121        let code = context.compile(&*isa).expect("expected compilation");
122
123        let fde = match code
124            .create_unwind_info(isa.as_ref())
125            .expect("can create unwind info")
126        {
127            Some(crate::isa::unwind::UnwindInfo::SystemV(info)) => {
128                info.to_fde(Address::Constant(1234))
129            }
130            _ => panic!("expected unwind information"),
131        };
132
133        assert_eq!(format!("{:?}", fde), "FrameDescriptionEntry { address: Constant(1234), length: 17, lsda: None, instructions: [(1, CfaOffset(16)), (1, Offset(Register(6), -16)), (4, CfaRegister(Register(6)))] }");
134    }
135
136    fn create_function(call_conv: CallConv, stack_slot: Option<StackSlotData>) -> Function {
137        let mut func = Function::with_name_signature(Default::default(), Signature::new(call_conv));
138
139        let block0 = func.dfg.make_block();
140        let mut pos = FuncCursor::new(&mut func);
141        pos.insert_block(block0);
142        pos.ins().return_(&[]);
143
144        if let Some(stack_slot) = stack_slot {
145            func.sized_stack_slots.push(stack_slot);
146        }
147
148        func
149    }
150
151    #[test]
152    fn test_multi_return_func() {
153        let isa = lookup(triple!("x86_64"))
154            .expect("expect x86 ISA")
155            .finish(Flags::new(builder()))
156            .expect("expect backend creation to succeed");
157
158        let mut context = Context::for_function(create_multi_return_function(CallConv::SystemV));
159
160        let code = context.compile(&*isa).expect("expected compilation");
161
162        let fde = match code
163            .create_unwind_info(isa.as_ref())
164            .expect("can create unwind info")
165        {
166            Some(crate::isa::unwind::UnwindInfo::SystemV(info)) => {
167                info.to_fde(Address::Constant(4321))
168            }
169            _ => panic!("expected unwind information"),
170        };
171
172        assert_eq!(format!("{:?}", fde), "FrameDescriptionEntry { address: Constant(4321), length: 22, lsda: None, instructions: [(1, CfaOffset(16)), (1, Offset(Register(6), -16)), (4, CfaRegister(Register(6)))] }");
173    }
174
175    fn create_multi_return_function(call_conv: CallConv) -> Function {
176        let mut sig = Signature::new(call_conv);
177        sig.params.push(AbiParam::new(types::I32));
178        let mut func = Function::with_name_signature(Default::default(), sig);
179
180        let block0 = func.dfg.make_block();
181        let v0 = func.dfg.append_block_param(block0, types::I32);
182        let block1 = func.dfg.make_block();
183        let block2 = func.dfg.make_block();
184
185        let mut pos = FuncCursor::new(&mut func);
186        pos.insert_block(block0);
187        pos.ins().brif(v0, block2, &[], block1, &[]);
188
189        pos.insert_block(block1);
190        pos.ins().return_(&[]);
191
192        pos.insert_block(block2);
193        pos.ins().return_(&[]);
194
195        func
196    }
197}