| 1 |
use super::unwindregs::Reg; |
| 2 |
use arrayvec::ArrayVec; |
| 3 |
|
| 4 |
const ENCODE_REGISTERS: [Reg; 8] = [ |
| 5 |
Reg::RBX, |
| 6 |
Reg::RBP, |
| 7 |
Reg::RDI, |
| 8 |
Reg::RSI, |
| 9 |
Reg::R12, |
| 10 |
Reg::R13, |
| 11 |
Reg::R14, |
| 12 |
Reg::R15, |
| 13 |
]; |
| 14 |
|
| 15 |
pub fn decode(count: u8, encoded_ordering: u16) -> ArrayVec<Reg, 8> { |
| 16 |
let mut regs: ArrayVec<Reg, 8> = ENCODE_REGISTERS.into(); |
| 17 |
let mut r = encoded_ordering; |
| 18 |
let mut n: u16 = 8; |
| 19 |
while r != 0 { |
| 20 |
let index = r % n; |
| 21 |
if index != 0 { |
| 22 |
regs[(8 - n as usize)..].swap(index as usize, 0); |
| 23 |
} |
| 24 |
r /= n; |
| 25 |
n -= 1; |
| 26 |
} |
| 27 |
regs.truncate(count as usize); |
| 28 |
regs |
| 29 |
} |
| 30 |
|
| 31 |
pub fn encode(registers: &[Reg]) -> Option<(u8, u16)> { |
| 32 |
if registers.len() > ENCODE_REGISTERS.len() { |
| 33 |
return None; |
| 34 |
} |
| 35 |
|
| 36 |
let count = registers.len() as u8; |
| 37 |
let mut r: u16 = 0; |
| 38 |
let mut reg_order: ArrayVec<Reg, 8> = ENCODE_REGISTERS.into(); |
| 39 |
|
| 40 |
let mut scale: u16 = 1; |
| 41 |
for (i, reg) in registers.iter().enumerate() { |
| 42 |
let index = reg_order[i..].iter().position(|r| r == reg)?; |
| 43 |
if index as u16 != 0 { |
| 44 |
reg_order[i..].swap(index, 0); |
| 45 |
} |
| 46 |
r += index as u16 * scale; |
| 47 |
scale *= 8 - i as u16; |
| 48 |
} |
| 49 |
Some((count, r)) |
| 50 |
} |
| 51 |
|
| 52 |
#[cfg(test)] |
| 53 |
mod test { |
| 54 |
use super::*; |
| 55 |
|
| 56 |
#[test] |
| 57 |
fn unhandled_orderings() { |
| 58 |
use super::Reg::*; |
| 59 |
|
| 60 |
assert_eq!(encode(&[RAX]), None, "RAX is a volatile register, i.e. not a callee-save register, so it does not need to be restored during epilogs and is not covered by the encoding."); |
| 61 |
assert_eq!(encode(&[RSI, RSI]), None, "Valid register orderings only contain each register (at most) once, so there is no encoding for a sequence with repeated registers."); |
| 62 |
} |
| 63 |
|
| 64 |
#[test] |
| 65 |
fn roundtrip_all() { |
| 66 |
// Test all possible register orderings. |
| 67 |
// That is, for all permutations of length 0 to 8 of the ENCODE_REGISTERS array, check that |
| 68 |
// the register ordering rountrips successfully through encoding and decoding. |
| 69 |
use itertools::Itertools; |
| 70 |
for permutation in (0..=8).flat_map(|k| ENCODE_REGISTERS.iter().cloned().permutations(k)) { |
| 71 |
let permutation = permutation.as_slice(); |
| 72 |
let encoding = encode(permutation); |
| 73 |
if let Some((count, encoded)) = encoding { |
| 74 |
assert_eq!( |
| 75 |
decode(count, encoded).as_slice(), |
| 76 |
permutation, |
| 77 |
"Register permutation should roundtrip correctly", |
| 78 |
); |
| 79 |
} else { |
| 80 |
panic!("Register permutation failed to encode: {permutation:?}"); |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
} |