use core::fmt;
use super::Instruction;
use crate::generated::flags::FLAG_RECORDS;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Flag {
Cf,
Pf,
Af,
Zf,
Sf,
Tf,
If,
Df,
Of,
Iopl,
Nt,
Rf,
Vm,
Ac,
Vif,
Vip,
Id,
Fc0,
Fc1,
Fc2,
Fc3,
}
impl Flag {
pub const fn bits(self) -> u32 {
match self {
Self::Cf => 1 << 0,
Self::Pf => 1 << 2,
Self::Af => 1 << 4,
Self::Zf => 1 << 6,
Self::Sf => 1 << 7,
Self::Tf => 1 << 8,
Self::If => 1 << 9,
Self::Df => 1 << 10,
Self::Of => 1 << 11,
Self::Iopl => 3 << 12,
Self::Nt => 1 << 14,
Self::Rf => 1 << 16,
Self::Vm => 1 << 17,
Self::Ac => 1 << 18,
Self::Vif => 1 << 19,
Self::Vip => 1 << 20,
Self::Id => 1 << 21,
Self::Fc0 => 1 << 28,
Self::Fc1 => 1 << 29,
Self::Fc2 => 1 << 30,
Self::Fc3 => 1 << 31,
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Cf => "cf",
Self::Pf => "pf",
Self::Af => "af",
Self::Zf => "zf",
Self::Sf => "sf",
Self::Tf => "tf",
Self::If => "if",
Self::Df => "df",
Self::Of => "of",
Self::Iopl => "iopl",
Self::Nt => "nt",
Self::Rf => "rf",
Self::Vm => "vm",
Self::Ac => "ac",
Self::Vif => "vif",
Self::Vip => "vip",
Self::Id => "id",
Self::Fc0 => "fc0",
Self::Fc1 => "fc1",
Self::Fc2 => "fc2",
Self::Fc3 => "fc3",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct FlagSet(pub u32);
impl FlagSet {
pub const fn contains(self, flag: Flag) -> bool {
self.0 & flag.bits() != 0
}
pub const fn is_empty(self) -> bool {
self.0 == 0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FlagAction {
Modify,
Test,
Undefined,
Clear,
Set,
FromAh,
Pop,
}
impl FlagAction {
pub const fn as_str(self) -> &'static str {
match self {
Self::Modify => "mod",
Self::Test => "tst",
Self::Undefined => "u",
Self::Clear => "0",
Self::Set => "1",
Self::FromAh => "ah",
Self::Pop => "pop",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FlagEffect {
pub flag: Flag,
pub action: FlagAction,
}
impl fmt::Display for FlagEffect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}", self.flag.as_str(), self.action.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Flags {
pub read: FlagSet,
pub written: FlagSet,
pub undefined: FlagSet,
pub may_write: bool,
pub must_write: bool,
pub effects: &'static [FlagEffect],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FlagsRule {
None,
Always(u16),
Count { zero: u16, one: u16, other: u16 },
}
impl Instruction {
pub fn flags(&self) -> Option<&'static Flags> {
let s = &self.fields;
let record = match self.info().flags {
FlagsRule::None => 0,
FlagsRule::Always(record) => record,
FlagsRule::Count { zero, one, other } => {
let mask = if s.eosz == 3 { 0x3f } else { 0x1f };
#[expect(
clippy::cast_possible_truncation,
reason = "XED reads the immediate's low byte"
)]
match s.uimm0 as u8 & mask {
0 => zero,
1 => one,
_ => other,
}
}
};
FLAG_RECORDS.get(usize::from(record).checked_sub(1)?)
}
}