use std::collections::HashSet;
use super::decode::{self, Alu, Branch, FloatFormat, Instruction, Op};
use super::{Step, text};
use crate::lift::Decoded;
pub(super) fn written_register(instruction: &Instruction) -> Option<u8> {
let Instruction { op, rt, rd, .. } = *instruction;
Some(match op {
Op::Register(_)
| Op::Shift(_)
| Op::MultiplyLow
| Op::MoveFromHi
| Op::MoveFromLo
| Op::MoveIfZero
| Op::MoveIfNotZero
| Op::CountLeadingZeros
| Op::CountLeadingOnes
| Op::SignExtendByte
| Op::SignExtendHalf
| Op::SwapBytesInHalves => rd,
Op::Immediate(_)
| Op::Lui
| Op::Extract
| Op::Insert
| Op::Load { .. }
| Op::LoadLeft
| Op::LoadRight
| Op::LoadLinked
| Op::StoreConditional
| Op::ReadHardware => rt,
_ => return None,
})
}
pub(super) fn unaligned_pair(
first: &Instruction,
second: &Instruction,
big: bool,
) -> Option<Instruction> {
let (right, left) = match (first.op, second.op) {
(Op::LoadRight, Op::LoadLeft) | (Op::StoreRight, Op::StoreLeft) => (first, second),
(Op::LoadLeft, Op::LoadRight) | (Op::StoreLeft, Op::StoreRight) => (second, first),
_ => return None,
};
let (low, high) = if big { (left, right) } else { (right, left) };
(right.rs == left.rs
&& right.rt == left.rt
&& high.imm == low.imm + 3
&& (right.rs != right.rt || matches!(right.op, Op::StoreRight)))
.then_some(Instruction {
imm: low.imm,
..*right
})
}
pub(super) fn shared_pairs(instruction: &Instruction) -> u16 {
let Instruction {
op,
rs,
rt,
rd,
imm,
..
} = *instruction;
let (fr, ft, fs, fd) = (i64::from(rs), i64::from(rt), i64::from(rd), imm);
let operands: &[(i64, bool)] = match op {
Op::FloatArithmetic { double, .. } => &[(fd, double), (fs, double), (ft, double)],
Op::FloatMultiplyAdd { double, .. } => {
&[(fd, double), (fr, double), (fs, double), (ft, double)]
}
Op::FloatConvert { from, double } => &[(fd, double), (fs, from == FloatFormat::Double)],
Op::FloatToWord { double, .. } => &[(fd, false), (fs, double)],
Op::FloatCompare { double, .. } => &[(fs, double), (ft, double)],
Op::FloatSelect { double, .. } => &[(fd, double), (fs, double)],
Op::FloatTransfer { high, .. } => &[(fs, high)],
Op::FloatLoad { double } | Op::FloatStore { double } => &[(ft, double)],
Op::FloatLoadIndexed { double } => &[(fd, double)],
Op::FloatStoreIndexed { double } => &[(fs, double)],
_ => &[],
};
operands
.iter()
.filter(|(register, double)| *double || register & 1 == 1)
.fold(0, |pairs, (register, _)| pairs | 1 << ((register & 31) / 2))
}
pub(super) const NOP: Instruction = Instruction {
op: Op::Shift(Alu::ShiftLeft),
rs: 0,
rt: 0,
rd: 0,
imm: 0,
word: 0,
};
pub(super) fn bytes_reached(instruction: &Instruction, big: bool) -> Option<std::ops::Range<i64>> {
let imm = instruction.imm;
let first = match instruction.op {
Op::LoadLeft | Op::StoreLeft => big,
_ => !big,
};
match instruction.op {
Op::Load { bytes, .. } | Op::Store { bytes } => Some(imm..imm + i64::from(bytes)),
Op::LoadLeft | Op::StoreLeft | Op::LoadRight | Op::StoreRight if first => {
Some(imm..imm + 4)
}
Op::LoadLeft | Op::StoreLeft | Op::LoadRight | Op::StoreRight => Some(imm - 3..imm + 1),
_ => None,
}
}
pub(super) const PAIR_REACH: usize = 8;
pub(super) fn separated_pair(
at: &impl Fn(usize) -> Option<Instruction>,
index: usize,
first: &Instruction,
big: bool,
) -> Option<(usize, Instruction)> {
let store = match first.op {
Op::LoadLeft | Op::LoadRight => false,
Op::StoreLeft | Op::StoreRight => true,
_ => return None,
};
for other in index + 2..=index + PAIR_REACH {
let between = at(other - 1)?;
let registers = [between.rs, between.rt, between.rd];
let apart = between.rs == first.rs
&& match (bytes_reached(first, big), bytes_reached(&between, big)) {
(Some(access), Some(other)) => {
access.end <= other.start || other.end <= access.start
}
_ => false,
};
let quiet = match between.op {
Op::Register(_) | Op::Immediate(_) | Op::Shift(_) | Op::Lui => true,
Op::Load { .. } | Op::LoadLeft | Op::LoadRight => !store || apart,
Op::Store { .. } | Op::StoreLeft | Op::StoreRight => apart,
_ => false,
};
if !quiet
|| (!store && registers.contains(&first.rt))
|| written_register(&between)
.is_some_and(|written| written != 0 && (written == first.rt || written == first.rs))
{
return None;
}
if let Some(whole) = unaligned_pair(first, &at(other)?, big) {
return Some((other, whole));
}
}
None
}
pub(in crate::lift) fn decode(bytes: &[u8], addr: u64) -> (Vec<Decoded<Step>>, Option<String>) {
decode_ordered(bytes, addr, false)
}
pub(in crate::lift) fn decode_big(bytes: &[u8], addr: u64) -> (Vec<Decoded<Step>>, Option<String>) {
decode_ordered(bytes, addr, true)
}
pub(super) fn decode_ordered(
bytes: &[u8],
addr: u64,
big: bool,
) -> (Vec<Decoded<Step>>, Option<String>) {
let mut decoded = Vec::new();
let words = bytes.as_chunks::<4>().0;
let at = |index: usize| words.get(index).and_then(|word| decode::decode(word, big));
let targets: HashSet<usize> = (0..words.len())
.filter_map(|index| {
let pc = addr.wrapping_add(index as u64 * 4);
let target = text::target(&at(index)?, pc)?;
usize::try_from(target.checked_sub(addr)? / 4).ok()
})
.collect();
let mut joined: HashSet<usize> = HashSet::new();
let shared_pairs = (0..words.len())
.filter_map(&at)
.fold(0, |pairs, instruction| pairs | shared_pairs(&instruction));
let mut index = 0;
let mut then = None;
while index < words.len() {
let pc = addr.wrapping_add(index as u64 * 4);
let Some(instruction) = at(index) else {
return (
decoded,
Some(format!("undecodable instruction at 0x{pc:x}")),
);
};
let after = then.take();
let instruction = if joined.contains(&index) {
NOP
} else {
instruction
};
let likely = matches!(
instruction.op,
Op::Branch { likely: true, .. } | Op::FloatBranch { likely: true, .. }
);
let (step, length) = if instruction.has_delay_slot() && !likely && after.is_none() {
match at(index + 1) {
Some(slot) if !slot.has_delay_slot() => (
Step {
instruction,
slot: Some(slot),
then: None,
unaligned: false,
shared_pairs,
},
2,
),
_ => {
return (
decoded,
Some(format!("no delay slot for the transfer at 0x{pc:x}")),
);
}
}
} else if let Some(next) = at(index + 1)
&& after.is_none()
&& !targets.contains(&(index + 1))
&& let Some(joined) = unaligned_pair(&instruction, &next, big)
{
(
Step {
instruction: joined,
slot: None,
then: None,
unaligned: true,
shared_pairs,
},
2,
)
} else if after.is_none()
&& let Some((other, whole)) = separated_pair(&at, index, &instruction, big)
&& !targets
.iter()
.any(|target| (index + 1..=other).contains(target))
{
joined.insert(other);
(
Step {
instruction: whole,
slot: None,
then: None,
unaligned: true,
shared_pairs,
},
1,
)
} else {
if likely {
then = text::target(&instruction, pc);
}
(
Step {
instruction,
slot: None,
then: after,
unaligned: false,
shared_pairs,
},
1,
)
};
let Some(next) = pc.checked_add(length * 4) else {
return (
decoded,
Some(format!("instruction address overflows at 0x{pc:x}")),
);
};
decoded.push(Decoded {
pc,
next,
instruction: step,
});
index += length as usize;
}
(decoded, None)
}
pub(super) fn always_taken(instruction: &Instruction) -> bool {
match instruction.op {
Op::Branch {
test: Branch::Equal,
..
} => instruction.rs == 0 && instruction.rt == 0,
Op::Branch {
test: Branch::GreaterEqualZero,
..
} => instruction.rs == 0,
_ => false,
}
}