use super::ast::{EK, Expr, OpKind, Program, Term, Type};
use std::collections::BTreeSet;
const MAX_VALUES: usize = 16;
pub type Given = Vec<Vec<Option<BTreeSet<u64>>>>;
#[derive(Default, Clone, Debug)]
pub struct Callers {
pub given: Given,
pub below: Vec<Vec<Option<u64>>>,
pub private: Vec<bool>,
pub callers: Vec<Vec<u32>>,
pub result_unused: Vec<bool>,
}
#[derive(Clone, Debug)]
enum Arg {
Const(u64),
Param(u32),
Narrow(u32),
Unknown,
}
struct Scan<'a> {
prog: &'a Program,
taken: Vec<bool>,
calls: Vec<(u32, u32, Vec<Arg>)>,
caller: u32,
dirty: Vec<BTreeSet<u32>>,
used: Vec<bool>,
statement: bool,
}
fn direct(e: &Expr) -> Option<u32> {
match &e.kind {
EK::Func(f) => Some(*f),
EK::Addr(f) | EK::Cast(f) => direct(f),
_ => None,
}
}
fn convert(p: &Program, v: u64, from: super::ast::TypeId, to: super::ast::TypeId) -> u64 {
let mask = |w: u8| if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
let (wf, wt) = (p.bits(from), p.bits(to));
let mut v = v & mask(wf);
if matches!(p.ty(p.unqual(to)), Type::Bool) {
return (v != 0) as u64;
}
if p.is_signed(from) && wf < 64 && v >> (wf - 1) & 1 == 1 {
v |= !mask(wf);
}
v & mask(wt)
}
impl Scan<'_> {
fn konst(&self, e: &Expr) -> Option<u64> {
let p = self.prog;
let int = |t| matches!(p.ty(p.unqual(t)), Type::Int { .. } | Type::Bool);
if !int(e.ty) || p.bits(e.ty) > 32 {
return None;
}
let w = p.bits(e.ty);
let mask = (1u64 << w) - 1;
match &e.kind {
EK::Const(c) => Some(convert(p, *c, e.ty, e.ty)),
EK::Cast(inner) => Some(convert(p, self.konst(inner)?, inner.ty, e.ty)),
EK::Bin(op, a, b) if p.bits(a.ty) == w && p.bits(b.ty) == w => {
use super::ast::BinOp as B;
let (x, y) = (self.konst(a)?, self.konst(b)?);
let v = match op {
B::Add => x.wrapping_add(y),
B::Sub => x.wrapping_sub(y),
B::Mul => x.wrapping_mul(y),
B::And => x & y,
B::Or => x | y,
B::Xor => x ^ y,
_ => return None,
};
Some(v & mask)
}
_ => None,
}
}
}
impl Scan<'_> {
fn arg(&self, e: &Expr, to: super::ast::TypeId) -> Arg {
let p = self.prog;
let int = |t| matches!(p.ty(p.unqual(t)), Type::Int { .. } | Type::Bool);
if !int(to) || !int(e.ty) || p.bits(to) > 32 || p.bits(e.ty) > 32 {
return Arg::Unknown;
}
if let Some(c) = self.konst(e) {
return Arg::Const(convert(p, c, e.ty, to));
}
let narrow = |e: &Expr| {
let mut x = e;
loop {
let unsigned = matches!(p.ty(p.unqual(x.ty)), Type::Bool)
|| (matches!(p.ty(p.unqual(x.ty)), Type::Int { .. }) && !p.is_signed(x.ty));
let bits = if matches!(p.ty(p.unqual(x.ty)), Type::Bool) {
1
} else {
p.bits(x.ty) as u32
};
if unsigned && bits < p.bits(to) as u32 && bits <= 16 {
return Some(bits);
}
match &x.kind {
EK::Cast(inner)
if int(inner.ty)
&& p.bits(x.ty) >= p.bits(inner.ty)
&& !matches!(p.ty(p.unqual(x.ty)), Type::Bool) =>
{
x = inner
}
_ => return None,
}
}
};
let fallback = || narrow(e).map_or(Arg::Unknown, Arg::Narrow);
match &e.kind {
EK::Cast(inner) => match self.arg(inner, to) {
Arg::Param(i)
if p.bits(e.ty) >= p.bits(inner.ty)
&& !p.is_signed(inner.ty)
&& !matches!(p.ty(p.unqual(e.ty)), Type::Bool) =>
{
Arg::Param(i)
}
_ => fallback(),
},
EK::Load(l) => match &l.kind {
EK::Local(i)
if (*i as usize) < p.funcs[self.caller as usize].nparams
&& p.bits(e.ty) == p.bits(to)
&& matches!(p.ty(p.unqual(e.ty)), Type::Bool) == matches!(p.ty(p.unqual(to)), Type::Bool) =>
{
Arg::Param(*i)
}
_ => fallback(),
},
_ => fallback(),
}
}
fn lvalue_root(&mut self, e: &Expr) {
match &e.kind {
EK::Local(i) => {
self.dirty[self.caller as usize].insert(*i);
}
EK::Member(b, _) | EK::BitField(b, ..) | EK::Bits(b, ..) => self.lvalue_root(b),
_ => {}
}
}
fn expr(&mut self, e: &Expr) {
let statement = std::mem::take(&mut self.statement);
match &e.kind {
EK::Cast(a) if statement && matches!(a.kind, EK::Call(..)) => {
self.statement = true;
self.expr(a);
}
EK::Func(f) => self.taken[*f as usize] = true,
EK::Const(_) | EK::FConst(_) | EK::Str(_) | EK::Local(_) | EK::Global(_) | EK::Prev | EK::VlaLive(_) => {}
EK::Addr(a) => {
self.lvalue_root(a);
self.expr(a);
}
EK::VaStart(a) | EK::VaArg(a) => {
self.lvalue_root(a);
self.expr(a);
}
EK::Deref(a)
| EK::Member(a, _)
| EK::BitField(a, ..)
| EK::Bits(a, ..)
| EK::Load(a)
| EK::Cast(a)
| EK::Neg(a)
| EK::BitNot(a)
| EK::Alloca(a, ..)
| EK::LogNot(a) => self.expr(a),
EK::Asm(a) => {
if let Some(x) = &a.input {
self.expr(x);
}
}
EK::Assign(a, b) | EK::AssignOp(a, b, _) => {
self.lvalue_root(a);
self.expr(a);
self.expr(b);
}
EK::Bin(_, a, b)
| EK::PtrAdd(a, b, _)
| EK::PtrDiff(a, b, _)
| EK::LogAnd(a, b)
| EK::LogOr(a, b)
| EK::Comma(a, b) => {
self.expr(a);
self.expr(b);
}
EK::Cond(a, b, c) => {
self.expr(a);
self.expr(b);
self.expr(c);
}
EK::Compound { items, .. } => items.iter().for_each(|(_, x)| self.expr(x)),
EK::Call(f, args) => {
match direct(f) {
Some(callee) => {
if !statement {
self.used[callee as usize] = true;
}
let params = &self.prog.funcs[callee as usize].ty.params;
let vals = (args.iter().enumerate())
.map(|(i, a)| params.get(i).map_or(Arg::Unknown, |&t| self.arg(a, t)))
.collect();
self.calls.push((self.caller, callee, vals));
}
None => self.expr(f),
}
args.iter().for_each(|x| self.expr(x));
}
}
}
}
pub fn callers(prog: &Program) -> Callers {
callers_except(prog, &[])
}
pub fn callers_except(prog: &Program, exported: &[bool]) -> Callers {
let n = prog.funcs.len();
let mut scan = Scan {
prog,
taken: (0..n).map(|i| exported.get(i).copied().unwrap_or(false)).collect(),
calls: Vec::new(),
caller: 0,
dirty: vec![BTreeSet::new(); n],
used: vec![false; n],
statement: false,
};
for g in &prog.globals {
if let Some(init) = &g.init {
for (_, sym, _) in &init.relocs {
if let super::ast::SymRef::Func(f) = sym {
scan.taken[*f as usize] = true;
}
}
}
}
let mut unread = BTreeSet::new();
let mut unread_funcs = Vec::new();
for (i, f) in prog.funcs.iter().enumerate() {
if f.unsupported.is_some() || f.opaque {
unread_funcs.push(i);
}
let Some(body) = &f.body else { continue };
scan.caller = i as u32;
for b in &body.blocks {
for op in &b.ops {
match &op.kind {
OpKind::Eval(e) => {
scan.statement = true;
scan.expr(e);
}
OpKind::Init { items, .. } => items.iter().for_each(|(_, e)| scan.expr(e)),
}
}
match &b.term {
Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => scan.expr(e),
Term::Jump(_) | Term::Ret(None) | Term::Unreachable => {}
}
}
}
let mentioned = |i: usize| scan.taken[i] || scan.calls.iter().any(|c| c.1 == i as u32);
for &i in &unread_funcs {
if !prog.funcs[i].is_static || mentioned(i) {
unread.insert(prog.func_unit[i]);
}
}
let eligible: Vec<bool> = (0..n)
.map(|i| {
let f = &prog.funcs[i];
f.is_static
&& f.body.is_some()
&& !f.variadic_def
&& !scan.taken[i]
&& !unread.contains(&prog.func_unit[i])
&& scan.calls.iter().any(|c| c.1 == i as u32)
})
.collect();
let mut sets: Given = (0..n)
.map(|i| vec![eligible[i].then(BTreeSet::new); prog.funcs[i].ty.params.len()])
.collect();
loop {
let mut changed = false;
for (caller, callee, args) in &scan.calls {
let (caller, callee) = (*caller as usize, *callee as usize);
if !eligible[callee] {
continue;
}
for k in 0..sets[callee].len() {
if sets[callee][k].is_none() {
continue;
}
let add: Option<BTreeSet<u64>> = match args.get(k) {
Some(Arg::Const(c)) => Some([*c].into()),
Some(Arg::Param(i)) if !scan.dirty[caller].contains(i) => {
sets[caller].get(*i as usize).cloned().flatten()
}
_ => None,
};
let cur = sets[callee][k].as_mut().unwrap();
match add {
Some(vals) if cur.len() + vals.len() <= 2 * MAX_VALUES => {
for v in vals {
changed |= cur.insert(v);
}
if cur.len() > MAX_VALUES {
sets[callee][k] = None;
changed = true;
}
}
_ => {
sets[callee][k] = None;
changed = true;
}
}
}
}
if !changed {
break;
}
}
let mut below: Vec<Vec<Option<u64>>> = (0..n)
.map(|i| vec![eligible[i].then_some(0); prog.funcs[i].ty.params.len()])
.collect();
loop {
let mut changed = false;
for (caller, callee, args) in &scan.calls {
let (caller, callee) = (*caller as usize, *callee as usize);
if !eligible[callee] {
continue;
}
for k in 0..below[callee].len() {
let Some(cur) = below[callee][k] else { continue };
let add: Option<u64> = match args.get(k) {
Some(Arg::Const(c)) if *c < 1 << 16 => Some(*c + 1),
Some(Arg::Narrow(bits)) => Some(1 << *bits),
Some(Arg::Param(i)) if !scan.dirty[caller].contains(i) => {
below[caller].get(*i as usize).copied().flatten()
}
_ => None,
};
let next = add.map(|a| a.max(cur));
if next != Some(cur) {
below[callee][k] = next;
changed = true;
}
}
}
if !changed {
break;
}
}
for f in &mut below {
for b in f.iter_mut() {
if *b == Some(0) {
*b = None;
}
}
}
for f in &mut sets {
for s in f.iter_mut() {
if s.as_ref().is_some_and(|s| s.is_empty()) {
*s = None;
}
}
}
if std::env::var_os("CVERIF_DEBUG").is_some() {
for (i, f) in prog.funcs.iter().enumerate() {
if f.is_static && f.body.is_some() {
eprintln!(
"callers of {}: eligible={} taken={} calls={:?} sets={:?}",
f.name,
eligible[i],
scan.taken[i],
scan.calls
.iter()
.filter(|c| c.1 == i as u32)
.map(|c| &c.2)
.collect::<Vec<_>>(),
sets[i]
);
}
}
}
let mut callers = vec![Vec::new(); n];
for (caller, callee, _) in &scan.calls {
if !callers[*callee as usize].contains(caller) {
callers[*callee as usize].push(*caller);
}
}
let void = |i: usize| prog.funcs[i].ty.ret == super::ast::VOID;
Callers {
given: sets,
below,
result_unused: (0..n).map(|i| eligible[i] && !scan.used[i] && !void(i)).collect(),
private: eligible,
callers,
}
}