use crate::address::PcRead;
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BranchKind {
#[default]
None = 0,
Direct = 1,
Indirect = 2,
DirectCall = 3,
IndirectCall = 4,
Return = 5,
ExceptionReturn = 6,
SystemCall = 7,
Exception = 8,
Halt = 9,
}
impl BranchKind {
pub const fn names_target(self) -> bool {
matches!(self, BranchKind::Direct | BranchKind::DirectCall)
}
pub const fn sets_the_pc(self) -> bool {
!matches!(
self,
BranchKind::None | BranchKind::SystemCall | BranchKind::Exception | BranchKind::Halt
)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct BranchEffect {
pub kind: BranchKind,
pub conditional: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Branch {
pub kind: BranchKind,
pub conditional: bool,
pub target: Option<u64>,
}
impl BranchEffect {
pub const NONE: BranchEffect = BranchEffect {
kind: BranchKind::None,
conditional: false,
};
pub fn at(self, address: u64, label: Option<(i64, PcRead)>, bits: u32) -> Branch {
Branch {
kind: self.kind,
conditional: self.conditional,
target: match self.kind.names_target() {
true => label.map(|(offset, pc)| pc.target(address, offset, bits)),
false => None,
},
}
}
}
#[cfg(test)]
mod tests {
use super::{BranchEffect, BranchKind};
use crate::address::PcRead;
const A64: PcRead = PcRead { ahead: 0, align: 1 };
fn effect(kind: BranchKind, conditional: bool) -> BranchEffect {
BranchEffect { kind, conditional }
}
#[test]
fn a_direct_branch_names_where_it_goes() {
let forward = effect(BranchKind::Direct, false).at(0x1000, Some((0x20, A64)), 64);
assert_eq!(forward.target, Some(0x1020));
let back = effect(BranchKind::Direct, true).at(0x1000, Some((-0x10, A64)), 64);
assert_eq!(back.target, Some(0xff0));
assert!(back.conditional);
}
#[test]
fn an_indirect_branch_names_no_target() {
for kind in [
BranchKind::Indirect,
BranchKind::IndirectCall,
BranchKind::Return,
] {
let branch = effect(kind, false).at(0x1000, Some((0x20, A64)), 64);
assert_eq!(branch.target, None, "{kind:?} names no target");
}
}
#[test]
fn a_target_wraps_within_the_instruction_sets_reach() {
let a32 = PcRead { ahead: 8, align: 1 };
let branch = effect(BranchKind::Direct, true).at(0xffff_fffc, Some((0x10, a32)), 32);
assert_eq!(branch.target, Some(0x14));
}
#[test]
fn an_exception_leaves_where_it_goes_on_to_its_handler() {
for kind in [
BranchKind::Direct,
BranchKind::Indirect,
BranchKind::DirectCall,
BranchKind::IndirectCall,
BranchKind::Return,
BranchKind::ExceptionReturn,
] {
assert!(kind.sets_the_pc(), "{kind:?} sets the PC");
}
for kind in [
BranchKind::None,
BranchKind::SystemCall,
BranchKind::Exception,
BranchKind::Halt,
] {
assert!(!kind.sets_the_pc(), "{kind:?} does not set the PC");
}
}
}