use super::*;
use crate::c::ast::{BinOp, Body, EK, Expr, Term, Type};
use crate::c::exec::CutSnap;
use crate::term::Node;
use crate::thumb::exec::MachSnap;
use std::collections::BTreeMap;
#[derive(Default)]
pub(super) struct Proof {
pub cov: Vec<u32>,
pub bytes: Vec<(u32, u8)>,
pub paths: usize,
pub object_size: bool,
}
#[derive(Clone, Debug)]
pub(super) struct Failure {
pub code: &'static str,
pub detail: String,
rank: u8,
}
impl Failure {
fn new(code: &'static str, detail: impl Into<String>, rank: u8) -> Failure {
Failure {
code,
detail: detail.into(),
rank,
}
}
fn of(stop: &Stop, step: bool, cuts: &[Cut]) -> Failure {
let at: Vec<String> = cuts.iter().map(|c| format!("{:#x}", c.m_pc)).collect();
let phase = if step { "step" } else { "base case" };
let place = format!("{phase}, cut at {}", at.join(" "));
let rank = 4 + u8::from(step);
match stop {
Stop::Truncated(w) if w.contains("did not stabilise") => {
Failure::new("no-relation", format!("{w} ({place})"), rank)
}
Stop::Truncated(w) if w.contains("branch depth") || w.contains("too many paths") => {
Failure::new("body-too-large", format!("{w} ({place})"), rank)
}
Stop::Truncated(w) => Failure::new("budget", format!("{w} ({place})"), rank),
Stop::Unsupported(w) => {
let w = w.strip_prefix("loop proof: ").unwrap_or(w);
let code = if w.contains("visible to external code") {
"exposed-local"
} else if w.contains("dynamic size") {
"dynamic-object"
} else if w.contains("loop head") || w.contains("different loops") {
"events"
} else {
"unsupported-shape"
};
Failure::new(code, format!("{w} ({place})"), rank)
}
Stop::Mismatch(w, _) | Stop::Inconclusive(w) => Failure::new(
if step { "step-failed" } else { "base-failed" },
format!("{w} ({place})"),
rank,
),
_ => Failure::new("unsupported-shape", format!("{stop:?} ({place})"), rank),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum View {
Same,
Zext,
Sext,
Part(u8),
}
#[derive(Clone, Debug)]
enum Cand {
Inv(T),
Rel(usize, View),
Lin(usize, View, u64, T),
Val(usize, View),
Lin2(usize, View, u64, Base, u64),
Two(usize, u64, usize, bool, Option<usize>, u64),
Obj(T, i64),
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Base {
Loc(usize),
Expr(usize),
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Place {
Reg(u8),
Mem { base: T, off: i64, size: u8 },
}
#[derive(Clone, Debug)]
struct Loc {
place: Place,
cands: Vec<Cand>,
active: usize,
refined: bool,
}
impl Loc {
fn width(&self) -> u8 {
match self.place {
Place::Reg(_) => 32,
Place::Mem { size, .. } => size * 8,
}
}
}
#[derive(Clone)]
struct Cut {
id: usize,
c_block: usize,
m_pc: u32,
lead: usize,
ratio: usize,
c_locs: Vec<Loc>,
m_locs: Vec<Loc>,
c_full: HashSet<T>,
exposed: Vec<ExposedLocal>,
stale: u16,
pred: Option<(usize, bool)>,
pred_exprs: Vec<(Expr, bool)>,
exprs: std::rc::Rc<Vec<Expr>>,
facts: Vec<(Expr, bool)>,
fail_facts: BTreeSet<usize>,
assumed: Vec<(Expr, bool)>,
world_same: bool,
c_world: Vec<Write>,
c_epoch: u32,
m_world: Vec<Write>,
m_epoch: u32,
fail_c: BTreeSet<(usize, usize)>,
fail_m: BTreeSet<(usize, usize)>,
fail_pred: bool,
fail_world: bool,
grew: bool,
}
impl Cut {
fn refuted(&self) -> bool {
!self.fail_c.is_empty()
|| !self.fail_m.is_empty()
|| !self.fail_facts.is_empty()
|| self.fail_pred
|| self.fail_world
|| self.grew
}
}
fn fail(what: &str) -> Stop {
cut_error(what)
}
fn successors(t: &Term) -> Vec<usize> {
match t {
Term::Jump(t) => vec![*t],
Term::Br(_, t, f) => vec![*t, *f],
Term::Switch(_, cases, d) => cases.iter().map(|c| c.2).chain([*d]).collect(),
Term::Ret(_) | Term::Unreachable => Vec::new(),
}
}
struct CLoop {
cands: Vec<usize>,
head: usize,
inside: Vec<usize>,
}
fn c_loops(body: &Body) -> Vec<CLoop> {
let n = body.blocks.len();
let succ: Vec<Vec<usize>> = body.blocks.iter().map(|b| successors(&b.term)).collect();
let mut state = vec![0u8; n];
let mut back: Vec<(usize, usize)> = Vec::new();
let mut stack: Vec<(usize, usize)> = vec![(0, 0)];
state[0] = 1;
while let Some(&mut (b, ref mut i)) = stack.last_mut() {
if *i < succ[b].len() {
let s = succ[b][*i];
*i += 1;
match state[s] {
0 => {
state[s] = 1;
stack.push((s, 0));
}
1 => back.push((b, s)),
_ => {}
}
} else {
state[b] = 2;
stack.pop();
}
}
let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
for (b, ss) in succ.iter().enumerate() {
if state[b] != 0 {
for &s in ss {
preds[s].push(b);
}
}
}
let mut heads: Vec<usize> = back.iter().map(|e| e.1).collect();
heads.sort_unstable();
heads.dedup();
let loops = heads
.into_iter()
.map(|head| {
let mut inside: HashSet<usize> = HashSet::from([head]);
let mut work: Vec<usize> = back.iter().filter(|e| e.1 == head).map(|e| e.0).collect();
while let Some(b) = work.pop() {
if inside.insert(b) {
work.extend(preds[b].iter().copied());
}
}
let mut cands: Vec<usize> = Vec::new();
if matches!(body.blocks[head].term, Term::Br(..)) {
for &s in &succ[head] {
if s != head && inside.contains(&s) && !cands.contains(&s) {
cands.push(s);
}
}
}
cands.push(head);
(cands, inside)
})
.collect::<Vec<_>>();
let sets: Vec<HashSet<usize>> = loops.iter().map(|l| l.1.clone()).collect();
loops
.into_iter()
.map(|(mut cands, inside)| {
let head = *cands.last().expect("the head");
let inner = |b: usize| {
sets.iter()
.any(|o| o.len() < inside.len() && o.contains(&b) && o.is_subset(&inside))
};
let mut more: Vec<usize> = Vec::new();
for &b in &inside {
if cands.contains(&b) || inner(b) {
continue;
}
let latch = succ[b].contains(&head);
let joined = preds[b].iter().filter(|q| inside.contains(q)).count() >= 2;
let after_br = preds[b]
.iter()
.any(|&q| inside.contains(&q) && matches!(body.blocks[q].term, Term::Br(..)));
if latch || joined || after_br {
more.push(b);
}
}
more.sort_unstable();
more.truncate(6);
cands.extend(more);
let mut inside: Vec<usize> = inside.into_iter().collect();
inside.sort_unstable();
CLoop { cands, head, inside }
})
.collect()
}
fn pure_conditions(p: &Program, e: &Expr, want: bool, out: &mut Vec<(Expr, bool)>) -> bool {
fn pure(p: &Program, e: &Expr) -> bool {
match &e.kind {
EK::Const(_) | EK::Local(_) | EK::Global(_) | EK::Func(_) | EK::Str(_) => true,
EK::Load(x) => !p.is_volatile(x.ty) && pure(p, x),
EK::Deref(x)
| EK::Member(x, _)
| EK::BitField(x, ..)
| EK::Addr(x)
| EK::Cast(x)
| EK::Neg(x)
| EK::BitNot(x)
| EK::LogNot(x) => pure(p, x),
EK::Bin(_, a, b) | EK::PtrAdd(a, b, _) | EK::PtrDiff(a, b, _) => pure(p, a) && pure(p, b),
_ => false,
}
}
match &e.kind {
EK::LogNot(x) => pure_conditions(p, x, !want, out),
EK::LogAnd(a, b) if want => pure_conditions(p, a, true, out) && pure_conditions(p, b, true, out),
EK::LogOr(a, b) if !want => pure_conditions(p, a, false, out) && pure_conditions(p, b, false, out),
_ => {
if p.is_float(e.ty) || !pure(p, e) {
return false;
}
out.push((e.clone(), want));
true
}
}
}
fn simple_facts(p: &Program, fid: u32, body: &Body) -> Vec<(Expr, bool)> {
fn leaf(p: &Program, e: &Expr) -> bool {
match &e.kind {
EK::Const(_) => true,
EK::Load(x) => matches!(x.kind, EK::Local(_)) && !p.is_volatile(x.ty) && !p.is_float(e.ty),
EK::Cast(x) => !p.is_float(e.ty) && leaf(p, x),
_ => false,
}
}
fn atoms<'e>(p: &Program, e: &'e Expr, out: &mut Vec<&'e Expr>) {
use crate::c::ast::BinOp::*;
match &e.kind {
EK::LogNot(x) => atoms(p, x, out),
EK::LogAnd(a, b) | EK::LogOr(a, b) => {
atoms(p, a, out);
atoms(p, b, out);
}
EK::Cast(x) if !leaf(p, e) => atoms(p, x, out),
EK::Bin(Eq | Ne | Lt | Le, a, b) if leaf(p, a) && leaf(p, b) => out.push(e),
_ if leaf(p, e) && !matches!(e.kind, EK::Const(_)) => out.push(e),
_ => {}
}
}
let mut found = Vec::new();
for b in &body.blocks {
if let Term::Br(e, ..) = &b.term {
atoms(p, e, &mut found);
}
}
let mut seen = HashSet::new();
let mut out = Vec::new();
for b in &body.blocks {
if let Term::Switch(e, cases, _) = &b.term
&& leaf(p, e)
&& !matches!(e.kind, EK::Const(_))
&& !cases.is_empty()
&& out.len() < 8
{
let signed = p.is_signed(e.ty);
let key = |v: u64| if signed { (v as i64) as i128 } else { v as i128 };
let (Some(lo), Some(hi)) = (
cases.iter().map(|c| c.0).min_by_key(|&v| key(v)),
cases.iter().map(|c| c.1).max_by_key(|&v| key(v)),
) else {
continue;
};
let konst = |v: u64| Expr {
kind: EK::Const(v),
ty: e.ty,
loc: e.loc,
};
let cmp = |op: BinOp, a: Expr, b: Expr| Expr {
kind: EK::Bin(op, Box::new(a), Box::new(b)),
ty: crate::c::ast::INT,
loc: e.loc,
};
out.push((cmp(BinOp::Le, e.clone(), konst(hi)), true));
out.push((cmp(BinOp::Lt, e.clone(), konst(lo)), false));
}
}
out.extend(constant_ranges(p, fid, body));
for e in found {
if seen.insert(format!("{:?}", e.kind)) && out.len() < 56 {
out.push((e.clone(), true));
out.push((e.clone(), false));
if let EK::Bin(op @ (BinOp::Lt | BinOp::Le), a, b) = &e.kind {
let other = if *op == BinOp::Lt { BinOp::Le } else { BinOp::Lt };
let mut weak = e.clone();
weak.kind = EK::Bin(other, a.clone(), b.clone());
out.push((weak.clone(), true));
out.push((weak, false));
}
}
}
out
}
fn constant_ranges(p: &Program, fid: u32, body: &Body) -> Vec<(Expr, bool)> {
fn op_loc(items: &[(u32, Expr)]) -> crate::c::lex::Loc {
items.first().map(|i| i.1.loc).unwrap_or_default()
}
let mut vars: BTreeMap<u32, Option<(Expr, Vec<u64>)>> = BTreeMap::new();
fn constant(e: &Expr) -> Option<u64> {
match &e.kind {
EK::Const(k) => Some(*k),
EK::Cast(x) => constant(x),
_ => None,
}
}
fn walk(e: &Expr, vars: &mut BTreeMap<u32, Option<(Expr, Vec<u64>)>>) {
match &e.kind {
EK::Assign(l, r) if matches!(l.kind, EK::Local(_)) => {
let EK::Local(v) = l.kind else { unreachable!() };
match (
constant(r),
vars.entry(v).or_insert_with(|| Some(((**l).clone(), Vec::new()))),
) {
(Some(k), Some((_, ks))) => ks.push(k),
(_, slot) => *slot = None,
}
walk(r, vars);
}
EK::Load(x) if matches!(x.kind, EK::Local(_)) => {}
EK::Local(v) => {
vars.insert(*v, None);
}
_ => e.children().into_iter().for_each(|c| walk(c, vars)),
}
}
for b in &body.blocks {
for op in &b.ops {
match &op.kind {
crate::c::ast::OpKind::Eval(e) => walk(e, &mut vars),
crate::c::ast::OpKind::Init { var, items, zero } => {
let local = &p.funcs[fid as usize].locals[*var as usize];
let lv = Expr {
kind: EK::Local(*var),
ty: local.ty,
loc: op_loc(items),
};
let k = match &items[..] {
[] if *zero => Some(0),
[(0, e)] => constant(e),
_ => None,
};
match (k, vars.entry(*var).or_insert_with(|| Some((lv, Vec::new())))) {
(Some(k), Some((_, ks))) => ks.push(k),
(_, slot) => *slot = None,
}
items.iter().for_each(|i| walk(&i.1, &mut vars));
}
}
}
match &b.term {
Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => walk(e, &mut vars),
_ => {}
}
}
let mut out = Vec::new();
for (lv, ks) in vars.into_values().flatten() {
let w = p.size_of(lv.ty).unwrap_or(0) * 8;
if ks.len() < 2 || !(8..=32).contains(&w) || p.is_volatile(lv.ty) || p.is_float(lv.ty) || out.len() >= 8 {
continue;
}
let signed = p.is_signed(lv.ty);
let key = |v: u64| {
let v = v & crate::term::mask(w as u8);
if signed {
crate::term::sext64(v, w as u8) as i128
} else {
v as i128
}
};
let (lo, hi) = (
ks.iter().copied().min_by_key(|&v| key(v)).expect("two constants"),
ks.iter().copied().max_by_key(|&v| key(v)).expect("two constants"),
);
let ty = lv.ty;
let loc = lv.loc;
let load = Expr {
kind: EK::Load(Box::new(lv)),
ty,
loc,
};
let cmp = |op: BinOp, k: u64| Expr {
kind: EK::Bin(
op,
Box::new(load.clone()),
Box::new(Expr {
kind: EK::Const(k),
ty,
loc,
}),
),
ty: crate::c::ast::INT,
loc,
};
out.push((cmp(BinOp::Le, hi), true));
out.push((cmp(BinOp::Lt, lo), false));
}
out
}
fn value_of(ctx: &mut Ctx, job: &Job, mem: &Mem, e: &Expr) -> Option<T> {
let p = job.prog;
let f = &p.funcs[job.fid as usize];
fn addr(ctx: &mut Ctx, job: &Job, mem: &Mem, e: &Expr) -> Option<T> {
let p = job.prog;
let f = &p.funcs[job.fid as usize];
match &e.kind {
EK::Local(i) => {
let l = f.locals.get(*i as usize)?;
Some(ctx.private_base(&format!("&{}.{}#{i}@1", f.name, l.name)))
}
EK::Global(g) => job.env.global_addr[*g as usize].map(|a| ctx.tm.konst(32, a as u64)),
EK::Deref(x) => value_of(ctx, job, mem, x),
EK::Member(x, off) => {
let a = addr(ctx, job, mem, x)?;
Some(ctx.tm.add_const(a, *off as u64))
}
_ => None,
}
}
let _ = f;
if p.is_float(e.ty) {
return None;
}
match &e.kind {
EK::Const(c) => Some(ctx.tm.konst(p.bits(e.ty), *c)),
EK::Addr(x) => addr(ctx, job, mem, x),
EK::Load(x) => {
if p.is_volatile(x.ty) || !p.is_scalar(e.ty) {
return None;
}
let size = p.size_of(e.ty).filter(|s| matches!(s, 1 | 2 | 4))?;
let a = addr(ctx, job, mem, x)?;
let env = job.env;
let epoch = mem.epoch;
let mut init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, epoch);
Some(ctx.mem_read(mem, a, size as u8, &mut init))
}
EK::Cast(x) => {
if p.is_float(x.ty) || !p.is_scalar(e.ty) || !p.is_scalar(x.ty) || matches!(p.ty(e.ty), Type::Bool) {
return None;
}
let v = value_of(ctx, job, mem, x)?;
Some(ctx.tm.resize(v, p.bits(e.ty), p.is_signed(x.ty)))
}
EK::Bin(op, a, b) => {
let (x, y) = (value_of(ctx, job, mem, a)?, value_of(ctx, job, mem, b)?);
if ctx.tm.width(x) != ctx.tm.width(y) {
return None;
}
Some(match op {
BinOp::Add => ctx.tm.add(x, y),
BinOp::Sub => ctx.tm.sub(x, y),
BinOp::Mul => ctx.tm.mul(x, y),
BinOp::And => ctx.tm.and(x, y),
BinOp::Or => ctx.tm.or(x, y),
BinOp::Xor => ctx.tm.xor(x, y),
_ => return None,
})
}
EK::PtrAdd(a, i, size) => {
let (x, y) = (value_of(ctx, job, mem, a)?, value_of(ctx, job, mem, i)?);
if ctx.tm.width(x) != 32 {
return None;
}
let y = ctx.tm.resize(y, 32, p.is_signed(i.ty));
let scaled = ctx.tm.scale(y, *size as u64);
Some(ctx.tm.add(x, scaled))
}
_ => None,
}
}
fn value_exprs(p: &Program, body: &Body) -> Vec<Expr> {
fn simple(p: &Program, e: &Expr) -> bool {
match &e.kind {
EK::Const(_) | EK::Local(_) | EK::Global(_) => true,
EK::Load(x) => !p.is_volatile(x.ty) && simple(p, x),
EK::Deref(x) | EK::Member(x, _) | EK::Addr(x) | EK::Cast(x) => simple(p, x),
EK::Bin(BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor, a, b) => {
simple(p, a) && simple(p, b)
}
EK::PtrAdd(a, b, _) => simple(p, a) && simple(p, b),
_ => false,
}
}
fn walk(p: &Program, e: &Expr, out: &mut Vec<Expr>) {
let children: Vec<&Expr> = match &e.kind {
EK::Deref(x)
| EK::Member(x, _)
| EK::BitField(x, ..)
| EK::Addr(x)
| EK::Load(x)
| EK::Cast(x)
| EK::Neg(x)
| EK::BitNot(x)
| EK::LogNot(x) => vec![x],
EK::Bin(_, a, b)
| EK::PtrAdd(a, b, _)
| EK::PtrDiff(a, b, _)
| EK::LogAnd(a, b)
| EK::LogOr(a, b)
| EK::Comma(a, b)
| EK::Assign(a, b)
| EK::AssignOp(a, b, _) => vec![a, b],
EK::Cond(a, b, c) => vec![a, b, c],
EK::Call(f, args) => std::iter::once(&**f).chain(args.iter()).collect(),
_ => Vec::new(),
};
for c in children {
walk(p, c, out);
}
if !simple(p, e) || p.is_float(e.ty) {
return;
}
match &e.kind {
EK::Deref(_) | EK::Member(..) => {
let mut a = e.clone();
a.kind = EK::Addr(Box::new(e.clone()));
out.push(a);
}
EK::Load(x) if !matches!(x.kind, EK::Local(_)) => out.push(e.clone()),
EK::Bin(..) | EK::PtrAdd(..) => out.push(e.clone()),
EK::Cast(x) if !matches!(x.kind, EK::Const(_)) && p.is_scalar(e.ty) && p.bits(e.ty) != p.bits(x.ty) => {
out.push(e.clone())
}
_ => {}
}
}
let mut found = Vec::new();
for b in &body.blocks {
for op in &b.ops {
match &op.kind {
crate::c::ast::OpKind::Eval(e) => walk(p, e, &mut found),
crate::c::ast::OpKind::Init { items, .. } => {
for (_, e) in items {
walk(p, e, &mut found);
}
}
}
}
match &b.term {
Term::Br(e, ..) | Term::Switch(e, ..) => walk(p, e, &mut found),
Term::Ret(Some(e)) => walk(p, e, &mut found),
_ => {}
}
}
let mut seen = HashSet::new();
found.retain(|e| seen.insert(format!("{:?}", e.kind)));
found.truncate(96);
found
}
fn may_point_private(ctx: &Ctx, t: T) -> bool {
let mut seen = HashSet::new();
let mut stack = vec![t];
while let Some(x) = stack.pop() {
if !seen.insert(x) {
continue;
}
if ctx.private_bases.contains(&x) {
return true;
}
if let Node::Load(m, _) = ctx.tm.node(x)
&& *m >= crate::sym::UNINIT_EPOCH
{
continue;
}
stack.extend(crate::bv::Prover::children_of(ctx.tm.node(x)));
}
false
}
fn apply_view(ctx: &mut Ctx, v: T, view: View, w: u8) -> Option<T> {
let vw = ctx.tm.width(v);
match view {
View::Same => (vw == w).then_some(v),
View::Zext => (vw < w).then(|| ctx.tm.resize(v, w, false)),
View::Sext => (vw < w).then(|| ctx.tm.resize(v, w, true)),
View::Part(lo) => (lo as u32 + w as u32 <= vw as u32 && vw > w).then(|| ctx.tm.extract(v, lo, w)),
}
}
fn views(vw: u8, w: u8) -> Vec<View> {
if vw == w {
vec![View::Same]
} else if vw < w {
vec![View::Zext, View::Sext]
} else if vw.is_multiple_of(w) {
(0..vw / w).map(|i| View::Part(i * w)).collect()
} else {
Vec::new()
}
}
fn c_read(ctx: &mut Ctx, job: &Job, mem: &Mem, place: Place) -> T {
let Place::Mem { base, off, size } = place else {
unreachable!("source locations are memory")
};
let addr = ctx.tm.add_const(base, off as u64);
let env = job.env;
let epoch = mem.epoch;
let mut init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, epoch);
ctx.mem_read(mem, addr, size, &mut init)
}
fn m_read(ctx: &mut Ctx, job: &Job, regs: &[T; 16], mem: &Mem, place: Place) -> T {
match place {
Place::Reg(r) => regs[r as usize],
Place::Mem { base, off, size } => {
let addr = ctx.tm.add_const(base, off as u64);
let mut init = image_init(job.image, mem.epoch, None);
ctx.mem_read(mem, addr, size, &mut init)
}
}
}
#[derive(Clone, Default)]
struct Cover(HashMap<T, BTreeSet<i64>>);
impl Cover {
fn add(&mut self, locs: &mut Vec<Loc>, base: T, off: i64, size: u32) -> bool {
let set = self.0.entry(base).or_default();
let whole = (0..size as i64).all(|i| !set.contains(&(off + i)));
let mut push = |off: i64, size: u8| {
locs.push(Loc {
place: Place::Mem { base, off, size },
cands: Vec::new(),
active: 0,
refined: false,
})
};
if whole && matches!(size, 1 | 2 | 4 | 8) {
push(off, size as u8);
set.extend(off..off + size as i64);
return true;
}
let mut any = false;
let mut i = 0i64;
while i < size as i64 {
let o = off + i;
if set.contains(&o) {
i += 1;
continue;
}
let word = o & 3 == 0 && i + 4 <= size as i64 && (0..4).all(|k| !set.contains(&(o + k)));
let n = if word { 4 } else { 1 };
push(o, n as u8);
set.extend(o..o + n);
any = true;
i += n;
}
any
}
}
fn extents(ctx: &mut Ctx, mem: &Mem, full: &HashSet<T>) -> Option<Vec<(T, i64, u32)>> {
let mut out = Vec::new();
let mut bases: Vec<&T> = mem.private.keys().collect();
bases.sort_unstable();
for &base in bases {
if full.contains(&base) {
continue;
}
for e in &mem.private[&base] {
let d = ctx.tm.const_diff(e.addr, base)?;
out.push((base, d as u32 as i32 as i64, e.size as u32));
}
}
Some(out)
}
fn same_log(a: &[Write], b: &[Write]) -> bool {
a.len() == b.len()
&& a.iter().zip(b).all(|(x, y)| {
x.addr == y.addr && x.size == y.size && x.val == y.val && x.guard == y.guard && x.havoc == y.havoc
})
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Pair {
block: usize,
pc: u32,
lead: usize,
ratio: usize,
}
struct Explored {
c: Vec<CutSnap>,
m: Vec<MachSnap>,
back: Vec<u32>,
known: Vec<T>,
bound: Vec<(T, i64, u32)>,
asked: std::cell::RefCell<HashMap<(T, T), bool>>,
}
fn explore(
ctx: &mut Ctx,
job: &Job,
pre: &[T],
loops: &[CLoop],
range: (u32, u32),
depths: &[usize],
) -> Result<Explored, Failure> {
let watch: Vec<usize> = loops.iter().flat_map(|l| l.cands.iter().copied()).collect();
#[allow(clippy::type_complexity)]
let mut best: Option<(usize, Vec<bool>, Vec<u32>, Vec<u32>)> = None;
'search: for &depth in depths {
ctx.limits.max_depth = depth;
ctx.decisions.clear();
let mut deeper = false;
for _ in 0..48 {
ctx.restart(pre);
let ctl = SegCtl {
c_cuts: &watch,
..Default::default()
};
match run_seg(ctx, job, &ctl) {
Ok(end) => {
let twice = loops
.iter()
.filter(|l| {
let at = |b: usize| end.cx.cut_snaps.iter().filter(|s| s.block == b).count();
at(l.cands[0]) >= 2 || at(l.head) >= 3
})
.count();
let within = |a: &u32| *a >= range.0 && *a < range.1;
let targets: Vec<u32> = end.m.back_targets.iter().copied().filter(within).collect();
let leaders: Vec<u32> = end.m.leaders.iter().copied().filter(within).collect();
let score = twice * 2 + usize::from(!targets.is_empty());
if twice > 0 && best.as_ref().is_none_or(|b| score > b.0) {
let done = twice == loops.len() && !targets.is_empty();
best = Some((score, ctx.decisions[..ctx.pos].to_vec(), targets, leaders));
if done {
break 'search;
}
}
}
Err(Stop::Truncated(why)) if why != "branch depth limit" => {
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
eprintln!("explore: {why}");
}
return Err(Failure::new(
"budget",
format!("{why} while looking for a path through the loop"),
1,
));
}
Err(e) => {
deeper |= matches!(&e, Stop::Truncated(_));
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
eprintln!("explore path: {e:?}");
}
}
}
if !ctx.next_path() {
if deeper {
break;
}
break 'search;
}
}
}
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
eprintln!("explore: best {best:x?}");
}
let Some((_, decisions, back, mut targets)) = best else {
return Err(Failure::new(
"no-looping-path",
"no explored path goes round a loop of the source twice",
0,
));
};
if back.is_empty() {
return Err(Failure::new(
"no-looping-path",
"the binary takes no backward jump where the source loops",
0,
));
}
for &a in &back {
if !targets.contains(&a) {
targets.push(a);
}
}
ctx.limits.max_depth = decisions.len();
ctx.decisions = decisions;
ctx.restart(pre);
let ctl = SegCtl {
c_cuts: &watch,
m_cuts: &targets,
..Default::default()
};
let end = run_seg(ctx, job, &ctl).map_err(|e| {
Failure::new(
"unsupported-shape",
format!("the looping path cannot be replayed: {e:?}"),
1,
)
})?;
let mut known = ctx.pc.clone();
known.extend_from_slice(&ctx.ub);
Ok(Explored {
c: end.cx.cut_snaps,
m: end.m.cut_snaps,
back,
known,
bound: end.bound,
asked: Default::default(),
})
}
fn explore_prefix(
ctx: &mut Ctx,
job: &Job,
pre: &[T],
loops: &[CLoop],
li: usize,
range: (u32, u32),
) -> Option<Explored> {
let watch: Vec<usize> = loops.iter().flat_map(|l| l.cands.iter().copied()).collect();
let target = loops[li].cands[0];
let within = |a: &u32| *a >= range.0 && *a < range.1;
let mut found: Option<(Vec<bool>, Vec<u32>, Vec<u32>)> = None;
'search: for depth in [4usize, 8, 14, 24] {
ctx.limits.max_depth = depth;
ctx.decisions.clear();
let mut deeper = false;
for _ in 0..40 {
ctx.restart(pre);
let ctl = SegCtl {
c_cuts: &watch,
stop: 2,
prefix: Some(target),
..Default::default()
};
match run_seg(ctx, job, &ctl) {
Ok(end) if end.cut.is_some() => {
let back: Vec<u32> = end.m.back_targets.iter().copied().filter(within).collect();
let leaders: Vec<u32> = end.m.leaders.iter().copied().filter(within).collect();
if !back.is_empty() {
found = Some((ctx.decisions[..ctx.pos].to_vec(), back, leaders));
break 'search;
}
}
Ok(_) => {}
Err(Stop::Truncated(why)) if why != "branch depth limit" => return None,
Err(e) => deeper |= matches!(&e, Stop::Truncated(_)),
}
if !ctx.next_path() {
if deeper {
break;
}
break 'search;
}
}
}
let (decisions, back, mut targets) = found?;
for &a in &back {
if !targets.contains(&a) {
targets.push(a);
}
}
ctx.limits.max_depth = decisions.len();
ctx.decisions = decisions;
ctx.restart(pre);
let ctl = SegCtl {
c_cuts: &watch,
m_cuts: &targets,
stop: 2,
prefix: Some(target),
..Default::default()
};
let end = run_seg(ctx, job, &ctl).ok()?;
let mut known = ctx.pc.clone();
known.extend_from_slice(&ctx.ub);
Some(Explored {
c: end.cx.cut_snaps,
m: end.m.cut_snaps,
back,
known,
bound: end.bound,
asked: Default::default(),
})
}
fn prefix_plan(
ctx: &mut Ctx,
job: &Job,
pre: &[T],
loops: &[CLoop],
range: (u32, u32),
debug: bool,
) -> Option<Vec<Cut>> {
let mut cuts: Vec<Cut> = Vec::new();
for li in 0..loops.len() {
ctx.check_deadline().ok()?;
let Some(ex) = explore_prefix(ctx, job, pre, loops, li, range) else {
if debug {
eprintln!("no path prefix goes round loop {li}");
}
continue;
};
let block = loops[li].cands[0];
let c_ev: Vec<u32> = ex.c.iter().filter(|s| s.block == block).map(|s| s.nev).collect();
let Some(last) = ex.m.last() else { continue };
let pc = last.pc;
if cuts.iter().any(|c| c.m_pc == pc || c.c_block == block) {
continue;
}
let m_ev: Vec<u32> = ex.m.iter().filter(|s| s.pc == pc).map(|s| s.nev).collect();
let Some(lead) =
(1..=2usize).find(|&lead| c_ev.len() >= lead && c_ev[lead - 1..].iter().zip(&m_ev).all(|(a, b)| a == b))
else {
continue;
};
let pair = Pair {
block,
pc,
lead,
ratio: 1,
};
if debug {
eprintln!("path prefix: loop {li} cut at block {block}, {pc:#x}, lead {lead}");
}
if let Some(cut) = build_cut(ctx, job, &ex, cuts.len(), pair) {
cuts.push(cut);
}
}
(!cuts.is_empty()).then_some(cuts)
}
fn two_term(ctx: &mut Ctx, t: T, dt: i64, cv: &[T], dc: &[Option<i64>], n: usize) -> Vec<Cand> {
let mut out = Vec::new();
let mut tried = 0;
for j in 0..n {
let Some(dj) = dc[j].filter(|&d| d != 0) else { continue };
for k in 0..n {
let Some(dk) = dc[k] else { continue };
if k == j || ctx.tm.as_const(cv[k]).is_some() {
continue;
}
for neg in [false, true] {
if dk == 0 && !neg {
continue;
}
let rest = dt - if neg { -dk } else { dk };
if rest == 0 || rest % dj != 0 || !(-16..=16).contains(&(rest / dj)) || tried >= 48 {
continue;
}
tried += 1;
let a = (rest / dj) as u64 & 0xffff_ffff;
let scaled = ctx.tm.scale(cv[j], a);
let part = if neg {
ctx.tm.sub(scaled, cv[k])
} else {
ctx.tm.add(scaled, cv[k])
};
let rest = ctx.tm.sub(t, part);
if let Some(d) = ctx.tm.as_const(rest) {
out.push(Cand::Two(j, a, k, neg, None, d));
} else if let Some((x, d)) = (0..n).find_map(|x| {
let fixed = x != j && x != k && dc[x] == Some(0) && ctx.tm.as_const(cv[x]).is_none();
let d = if fixed { ctx.tm.const_diff(rest, cv[x]) } else { None };
d.map(|d| (x, d))
}) {
out.push(Cand::Two(j, a, k, neg, Some(x), d));
}
}
}
}
out.truncate(3);
out
}
fn expose(m_locs: &mut Vec<Loc>, m_cover: &mut Cover, sp0: T, e: &ExposedLocal) {
m_cover.add(m_locs, sp0, e.at, e.size);
for l in m_locs.iter_mut() {
if let Place::Mem { base, off, size } = l.place
&& base == sp0
&& off >= e.at
&& off + size as i64 <= e.at + e.size as i64
{
l.cands = vec![Cand::Obj(e.base, off - e.at)];
l.active = 0;
}
}
}
fn build_cut(ctx: &mut Ctx, job: &Job, ex: &Explored, id: usize, plan: Pair) -> Option<Cut> {
let p = job.prog;
let f = &p.funcs[job.fid as usize];
let (c_block, m_pc) = (plan.block, plan.pc);
let all: Vec<&CutSnap> = ex.c.iter().filter(|s| s.block == c_block).collect();
let cs: Vec<&CutSnap> = [plan.lead - 1, plan.lead - 1 + plan.ratio]
.into_iter()
.filter_map(|i| all.get(i).copied())
.collect();
let ms: Vec<&MachSnap> = ex.m.iter().filter(|s| s.pc == m_pc).take(2).collect();
let (c1, m1) = (*cs.first()?, *ms.first()?);
let second = match (cs.get(1), ms.get(1)) {
(Some(c), Some(m)) => Some((*c, *m)),
_ => None,
};
let mut c_locs = Vec::new();
let mut c_cover = Cover::default();
let mut c_full = HashSet::new();
for (i, l) in f.locals.iter().enumerate() {
let base = ctx.private_base(&format!("&{}.{}#{i}@1", f.name, l.name));
let size = p.size_of(l.ty).unwrap_or(0);
if size == 0 {
continue;
}
if size > 256 {
return None; }
c_cover.add(&mut c_locs, base, 0, size);
c_full.insert(base);
}
for (base, words) in &job.struct_args {
c_cover.add(&mut c_locs, *base, 0, 4 * words.len() as u32);
c_full.insert(*base);
}
let mut m_locs: Vec<Loc> = (0..15)
.map(|r| Loc {
place: Place::Reg(r),
cands: Vec::new(),
active: 0,
refined: false,
})
.collect();
let mut m_cover = Cover::default();
let none = HashSet::new();
for (c, m) in [Some((c1, m1)), second].into_iter().flatten() {
for (base, off, size) in extents(ctx, &c.mem, &c_full)? {
c_cover.add(&mut c_locs, base, off, size);
}
for (base, off, size) in extents(ctx, &m.mem, &none)? {
m_cover.add(&mut m_locs, base, off, size);
}
}
let mut exposed: Vec<ExposedLocal> = Vec::new();
for c in &all {
for e in &c.mem.exposed {
if exposed.iter().any(|x| x.base == e.base) {
continue;
}
let (_, at, size) = *ex.bound.iter().find(|b| b.0 == e.base)?;
let i = (0..f.locals.len())
.find(|&i| ctx.private_base(&format!("&{}.{}#{i}@1", f.name, f.locals[i].name)) == e.base)?;
if e.dyn_size.is_some() || !c_full.contains(&e.base) {
return None;
}
exposed.push(ExposedLocal {
base: e.base,
at,
size,
align: p.align_of(f.locals[i].ty).clamp(1, 8),
name: format!("&{}.{}#{i}@1", f.name, f.locals[i].name),
});
}
}
for e in &exposed {
expose(&mut m_locs, &mut m_cover, job.regs[13], e);
}
let cv1: Vec<T> = c_locs.iter().map(|l| c_read(ctx, job, &c1.mem, l.place)).collect();
let mv1: Vec<T> = m_locs
.iter()
.map(|l| m_read(ctx, job, &m1.regs, &m1.mem, l.place))
.collect();
let (cv2, mv2) = match second {
Some((c2, m2)) => (
Some(
c_locs
.iter()
.map(|l| c_read(ctx, job, &c2.mem, l.place))
.collect::<Vec<T>>(),
),
Some(
m_locs
.iter()
.map(|l| m_read(ctx, job, &m2.regs, &m2.mem, l.place))
.collect::<Vec<T>>(),
),
),
None => (None, None),
};
let exprs = std::rc::Rc::new(value_exprs(p, f.body.as_ref()?));
let ev1: Vec<Option<T>> = exprs.iter().map(|e| value_of(ctx, job, &c1.mem, e)).collect();
let ev2: Option<Vec<Option<T>>> =
second.map(|(c2, _)| exprs.iter().map(|e| value_of(ctx, job, &c2.mem, e)).collect());
let dc: Vec<Option<i64>> = (0..c_locs.len())
.map(|i| {
let c2 = cv2.as_ref()?;
if ctx.tm.width(cv1[i]) != 32 {
return None;
}
ctx.tm.const_diff(c2[i], cv1[i]).map(|d| crate::term::sext64(d, 32))
})
.collect();
for i in 0..c_locs.len() {
if cv2.as_ref().is_none_or(|v| v[i] == cv1[i]) {
c_locs[i].cands.push(Cand::Inv(cv1[i]));
continue;
}
let Some(c2) = &cv2 else { continue };
let w = c_locs[i].width();
let Some(di) = ctx.tm.const_diff(c2[i], cv1[i]) else {
continue;
};
for j in 0..i {
if ctx.tm.width(cv1[j]) != w || c_locs[j].cands.iter().any(|c| matches!(c, Cand::Inv(_))) {
continue;
}
let Some(dj) = ctx.tm.const_diff(c2[j], cv1[j]) else {
continue;
};
let (di, dj) = (crate::term::sext64(di, w), crate::term::sext64(dj, w));
if dj == 0 || di % dj != 0 {
continue;
}
let a = (di / dj) as u64 & crate::term::mask(w);
let scaled = ctx.tm.scale(cv1[j], a);
let b = ctx.tm.sub(cv1[i], scaled);
c_locs[i].cands.push(Cand::Lin(j, View::Same, a, b));
}
if w == 32 {
let more = two_term(ctx, cv1[i], crate::term::sext64(di, 32), &cv1, &dc, i);
c_locs[i].cands.extend(more);
}
}
let mut asks = 0;
for (i, l) in m_locs.iter_mut().enumerate() {
let w = l.width();
let steady = mv2.as_ref().is_none_or(|v| v[i] == mv1[i]);
if matches!(l.cands.first(), Some(Cand::Obj(..))) {
continue;
}
if steady {
l.cands.push(Cand::Inv(mv1[i]));
}
for (j, &c) in cv1.iter().enumerate() {
for view in views(ctx.tm.width(c), w) {
let Some(t1) = apply_view(ctx, c, view, w) else {
continue;
};
if t1 != mv1[i] {
continue;
}
let also = match (&cv2, &mv2) {
(Some(c2), Some(m2)) => match apply_view(ctx, c2[j], view, w) {
Some(t2) => same_on_path(ctx, ex, t2, m2[i]),
None => false,
},
_ => true,
};
if also {
l.cands.push(Cand::Rel(j, view));
}
}
}
let kept = matches!(l.place, Place::Reg(4..=11) | Place::Mem { .. });
if kept && ctx.tm.as_const(mv1[i]).is_none() && asks < 64 {
for (j, &c) in cv1.iter().enumerate() {
if ctx.tm.width(c) != w
|| ctx.mentions_uninit(c)
|| l.cands.iter().any(|x| matches!(x, Cand::Rel(k, _) if *k == j))
|| (ctx.tm.as_const(c).is_some()
&& !matches!((&cv2, &mv2), (Some(c2), Some(m2)) if c2[j] == m2[i] && c2[j] != c))
{
continue;
}
asks += 1;
if !same_on_path(ctx, ex, c, mv1[i]) {
continue;
}
let also = match (&cv2, &mv2) {
(Some(c2), Some(m2)) => same_on_path(ctx, ex, c2[j], m2[i]),
_ => true,
};
if also {
l.cands.push(Cand::Rel(j, View::Same));
}
}
}
if matches!(l.place, Place::Reg(_)) || w == 32 {
for (k, v1) in ev1.iter().enumerate() {
let Some(v1) = *v1 else { continue };
for view in views(ctx.tm.width(v1), w) {
if !matches!(view, View::Same | View::Zext | View::Sext) {
continue;
}
if apply_view(ctx, v1, view, w) != Some(mv1[i]) || ctx.tm.as_const(mv1[i]).is_some() {
continue;
}
let also = match (&ev2, &mv2) {
(Some(e2), Some(m2)) => match e2[k].and_then(|v| apply_view(ctx, v, view, w)) {
Some(t2) => same_on_path(ctx, ex, t2, m2[i]),
None => false,
},
_ => true,
};
if also && l.cands.iter().filter(|c| matches!(c, Cand::Val(..))).count() < 3 {
l.cands.push(Cand::Val(k, view));
}
}
}
}
if w == 32
&& let Some(m2) = &mv2
&& ctx.tm.as_const(mv1[i]).is_none()
&& let Some(dm) = ctx.tm.const_diff(m2[i], mv1[i])
{
let more = two_term(ctx, mv1[i], crate::term::sext64(dm, 32), &cv1, &dc, cv1.len());
l.cands.extend(more);
}
if let (Some(c2), Some(m2), 32) = (&cv2, &mv2, w)
&& let Some(dm) = ctx.tm.const_diff(m2[i], mv1[i])
&& dm != 0
{
for (j, &c) in cv1.iter().enumerate() {
let cw = ctx.tm.width(c);
let Some(dc) = ctx.tm.const_diff(c2[j], c) else {
continue;
};
let view = match cw {
32 => View::Same,
8 | 16 => View::Zext,
_ => continue,
};
let (dm, dc) = (dm as u32 as i32 as i64, crate::term::sext64(dc, cw));
if dc == 0 || dm % dc != 0 {
continue;
}
let a = (dm / dc) as u64 & 0xffff_ffff;
let Some(v1) = apply_view(ctx, c, view, 32) else {
continue;
};
let scaled = ctx.tm.scale(v1, a);
let b = ctx.tm.sub(mv1[i], scaled);
if a == 1 && ctx.tm.as_const(b) == Some(0) {
continue; }
l.cands.push(Cand::Lin(j, view, a, b));
if ctx.tm.as_const(b).is_some() {
continue;
}
let mut more = Vec::new();
for (k, &ck) in cv1.iter().enumerate() {
if k != j
&& ctx.tm.width(ck) == 32
&& ctx.tm.as_const(ck).is_none()
&& let Some(d) = ctx.tm.const_diff(b, ck)
&& c2[k] == ck
{
more.push(Cand::Lin2(j, view, a, Base::Loc(k), d));
}
}
for (k, &ek) in ev1.iter().enumerate() {
if let Some(ek) = ek
&& ctx.tm.width(ek) == 32
&& ctx.tm.as_const(ek).is_none()
&& let Some(d) = ctx.tm.const_diff(b, ek)
&& ev2.as_ref().is_some_and(|e| e[k] == Some(ek))
{
more.push(Cand::Lin2(j, view, a, Base::Expr(k), d));
}
}
if asks < 64 {
for (k, &ck) in cv1.iter().enumerate() {
if k == j
|| more
.iter()
.any(|c| matches!(c, Cand::Lin2(_, _, _, Base::Loc(x), _) if *x == k))
|| ctx.tm.width(ck) != 32
|| ctx.tm.as_const(ck).is_some()
|| c2[k] != ck
|| ctx.mentions_uninit(ck)
{
continue;
}
asks += 1;
if same_on_path(ctx, ex, b, ck) {
more.push(Cand::Lin2(j, view, a, Base::Loc(k), 0));
}
}
}
more.truncate(4);
l.cands.extend(more);
}
}
}
let mut pred = None;
let mut pred_exprs = Vec::new();
if let Some((b, taken)) = c1.last_br
&& cs.iter().all(|s| s.last_br == c1.last_br)
&& let Some(body) = &f.body
&& let Term::Br(e, ..) = &body.blocks[b].term
&& pure_conditions(p, e, taken, &mut pred_exprs)
{
pred = Some((b, taken));
} else {
pred_exprs.clear();
}
let world_same = second.is_none_or(|(c2, m2)| {
same_log(&c1.mem.world, &c2.mem.world)
&& same_log(&m1.mem.world, &m2.mem.world)
&& c1.mem.epoch == c2.mem.epoch
&& m1.mem.epoch == m2.mem.epoch
});
Some(Cut {
id,
c_block,
m_pc,
lead: plan.lead,
ratio: plan.ratio,
c_locs,
m_locs,
c_full,
exposed,
stale: 0,
pred,
pred_exprs,
exprs,
facts: simple_facts(p, job.fid, f.body.as_ref()?),
fail_facts: BTreeSet::new(),
assumed: Vec::new(),
world_same,
c_world: c1.mem.world.clone(),
c_epoch: c1.mem.epoch,
m_world: m1.mem.world.clone(),
m_epoch: m1.mem.epoch,
fail_c: BTreeSet::new(),
fail_m: BTreeSet::new(),
fail_pred: false,
fail_world: false,
grew: false,
})
}
fn same_on_path(ctx: &mut Ctx, ex: &Explored, a: T, b: T) -> bool {
if a == b {
return true;
}
if ctx.tm.width(a) != ctx.tm.width(b) || ctx.check_deadline().is_err() {
return false;
}
if let Some(&r) = ex.asked.borrow().get(&(a, b)) {
return r;
}
let e = ctx.tm.eq(a, b);
let r = matches!(ctx.prover.prove(&mut ctx.tm, &ex.known, e), crate::bv::Verdict::Proved);
ex.asked.borrow_mut().insert((a, b), r);
r
}
fn expr_values(ctx: &mut Ctx, job: &Job, cut: &Cut, mem: &Mem) -> Vec<Option<T>> {
let mut used = vec![false; cut.exprs.len()];
for l in &cut.m_locs {
for cand in &l.cands {
if let Cand::Val(k, _) | Cand::Lin2(_, _, _, Base::Expr(k), _) = cand {
used[*k] = true;
}
}
}
(0..cut.exprs.len())
.map(|k| {
if used[k] {
value_of(ctx, job, mem, &cut.exprs[k])
} else {
None
}
})
.collect()
}
fn expected(ctx: &mut Ctx, cand: &Cand, cvals: &[T], evals: &[Option<T>], w: u8) -> Option<T> {
match cand {
Cand::Inv(v) => Some(*v),
Cand::Obj(..) => None,
Cand::Val(k, view) => apply_view(ctx, (*evals.get(*k)?)?, *view, w),
Cand::Rel(j, view) => apply_view(ctx, cvals[*j], *view, w),
Cand::Lin(j, view, a, b) => {
let v = apply_view(ctx, cvals[*j], *view, w)?;
let s = ctx.tm.scale(v, *a);
Some(ctx.tm.add(s, *b))
}
Cand::Two(j, a, k, neg, x, d) => {
if w != 32 || ctx.tm.width(cvals[*j]) != 32 || ctx.tm.width(cvals[*k]) != 32 {
return None;
}
let s = ctx.tm.scale(cvals[*j], *a);
let mut t = if *neg {
ctx.tm.sub(s, cvals[*k])
} else {
ctx.tm.add(s, cvals[*k])
};
if let Some(x) = x {
if ctx.tm.width(cvals[*x]) != 32 {
return None;
}
t = ctx.tm.add(t, cvals[*x]);
}
Some(ctx.tm.add_const(t, *d))
}
Cand::Lin2(j, view, a, base, d) => {
let v = apply_view(ctx, cvals[*j], *view, w)?;
let s = ctx.tm.scale(v, *a);
let b = match base {
Base::Loc(k) => cvals[*k],
Base::Expr(k) => (*evals.get(*k)?)?,
};
if ctx.tm.width(b) != w {
return None;
}
let t = ctx.tm.add(s, b);
Some(ctx.tm.add_const(t, *d))
}
}
}
fn holds(ctx: &mut Ctx, a: T, b: T) -> bool {
if a == b {
return true;
}
let e = ctx.tm.eq(a, b);
ctx.implied(e)
}
fn arrive(ctx: &mut Ctx, job: &Job, cut: &mut Cut, end: &mut SegEnd) -> R<()> {
if end.bound_dynamic {
return Err(fail(
"an object of dynamic size is visible to external code at the loop head",
));
}
for (base, dynamic) in end.cx.escaped_objects() {
let place = end.bound.iter().find(|b| b.0 == base);
if let Some(e) = cut.exposed.iter().find(|e| e.base == base) {
if place.is_some_and(|b| b.1 != e.at) {
return Err(fail(
"a local object visible to external code is at another place in the frame",
));
}
continue;
}
let (Some(&(_, at, size)), None, true) = (place, dynamic, cut.c_full.contains(&base)) else {
return Err(fail("a local object is visible to external code at the loop head"));
};
let Some((_, align, name)) = end.cx.object(base) else {
return Err(fail("a local object is visible to external code at the loop head"));
};
let e = ExposedLocal {
base,
at,
size,
align,
name,
};
let mut m_cover = Cover::default();
for l in &cut.m_locs {
if let Place::Mem { base, off, size } = l.place {
m_cover.0.entry(base).or_default().extend(off..off + size as i64);
}
}
expose(&mut cut.m_locs, &mut m_cover, job.regs[13], &e);
cut.exposed.push(e);
cut.grew = true;
}
let Some(c_ext) = extents(ctx, &end.cx.mem, &cut.c_full) else {
return Err(fail("the source writes a local object at a computed offset"));
};
let Some(m_ext) = extents(ctx, &end.m.mem, &HashSet::new()) else {
return Err(fail("the binary writes its stack frame at a computed offset"));
};
let mut c_cover = Cover::default();
let mut m_cover = Cover::default();
for l in &cut.c_locs {
if let Place::Mem { base, off, size } = l.place {
c_cover.0.entry(base).or_default().extend(off..off + size as i64);
}
}
for l in &cut.m_locs {
if let Place::Mem { base, off, size } = l.place {
m_cover.0.entry(base).or_default().extend(off..off + size as i64);
}
}
for (base, off, size) in c_ext {
cut.grew |= c_cover.add(&mut cut.c_locs, base, off, size);
}
for (base, off, size) in m_ext {
cut.grew |= m_cover.add(&mut cut.m_locs, base, off, size);
}
if cut.grew {
return Ok(());
}
let cvals: Vec<T> = cut
.c_locs
.iter()
.map(|l| c_read(ctx, job, &end.cx.mem, l.place))
.collect();
let evals = expr_values(ctx, job, cut, &end.cx.mem);
let mut c_moved: Vec<(usize, T, i64)> = Vec::new();
let mut m_moved: Vec<(usize, T, i64)> = Vec::new();
for (i, l) in cut.c_locs.iter().enumerate() {
for (n, cand) in l.cands.iter().enumerate() {
let ok = match expected(ctx, cand, &cvals, &evals, l.width()) {
Some(want) => holds(ctx, cvals[i], want),
None => false,
};
if !ok {
cut.fail_c.insert((i, n));
if let Cand::Inv(v) = cand
&& let Some(d) = ctx.tm.const_diff(cvals[i], *v)
&& d != 0
{
c_moved.push((i, *v, crate::term::sext64(d, l.width())));
}
}
}
match l.cands.first() {
Some(_) => {}
None => {
if may_point_private(ctx, cvals[i]) {
return Err(fail(
"a pointer to a local object changes in the loop in a way that is not understood",
));
}
}
}
}
for i in 0..cut.m_locs.len() {
let l = &cut.m_locs[i];
let got = m_read(ctx, job, &end.m.regs, &end.m.mem, l.place);
for (n, cand) in l.cands.iter().enumerate() {
if let &Cand::Obj(base, off) = cand {
let Place::Mem { size, .. } = l.place else {
unreachable!("a cell of the frame")
};
let want = c_read(ctx, job, &end.cx.mem, Place::Mem { base, off, size });
if !ctx.mentions_uninit(want) && !holds(ctx, got, want) {
cut.fail_m.insert((i, n));
}
continue;
}
let ok = match expected(ctx, cand, &cvals, &evals, l.width()) {
Some(want) => holds(ctx, got, want),
None => false,
};
if !ok {
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() && !cut.fail_m.contains(&(i, n)) {
let want = expected(ctx, cand, &cvals, &evals, l.width());
eprintln!(
" machine {i}.{n} refuted: holds {} wanted {:?}",
ctx.tm.show(got),
want.map(|w| ctx.tm.show(w))
);
}
cut.fail_m.insert((i, n));
if let Cand::Inv(v) = cand
&& l.width() == 32
&& let Some(d) = ctx.tm.const_diff(got, *v)
&& d != 0
{
m_moved.push((i, *v, d as u32 as i32 as i64));
}
}
}
match l.cands.first() {
Some(_) => {}
None => {
if may_point_private(ctx, got) {
match l.place {
Place::Reg(r @ (0..=12 | 14)) => {
if cut.stale >> r & 1 == 0 {
cut.stale |= 1 << r;
cut.grew = true;
}
}
_ => {
return Err(fail(
"a stack address changes in the loop in a way that is not understood",
));
}
}
}
}
}
}
for &(i, v, d) in &m_moved {
if cut.m_locs[i].refined {
continue;
}
cut.m_locs[i].refined = true;
for &(j, cv, dc) in &c_moved {
let view = match cut.c_locs[j].width() {
32 => View::Same,
8 | 16 => View::Zext,
_ => continue,
};
if d % dc != 0 {
continue;
}
let a = (d / dc) as u64 & 0xffff_ffff;
let Some(c32) = apply_view(ctx, cv, view, 32) else {
continue;
};
let scaled = ctx.tm.scale(c32, a);
let b = ctx.tm.sub(v, scaled);
cut.m_locs[i].cands.push(Cand::Lin(j, view, a, b));
}
}
for &(i, v, d) in &c_moved {
if cut.c_locs[i].refined {
continue;
}
cut.c_locs[i].refined = true;
let w = cut.c_locs[i].width();
for &(j, cv, dc) in &c_moved {
if j >= i || cut.c_locs[j].width() != w || d % dc != 0 {
continue;
}
let a = (d / dc) as u64 & crate::term::mask(w);
let scaled = ctx.tm.scale(cv, a);
let b = ctx.tm.sub(v, scaled);
cut.c_locs[i].cands.push(Cand::Lin(j, View::Same, a, b));
}
}
for (k, (e, want)) in cut.facts.iter().enumerate() {
let (npc, nub) = (ctx.pc.len(), ctx.ub.len());
let v = end.cx.eval(ctx, e);
let clean = ctx.pc.len() == npc && ctx.ub.len() == nub;
ctx.pc.truncate(npc);
ctx.ub.truncate(nub);
let ok = match v {
Ok(v) if clean => {
let nz = ctx.tm.nonzero(v);
let c = if *want { nz } else { ctx.tm.not(nz) };
ctx.tm.is_true(c) || ctx.implied(c)
}
_ => false,
};
if !ok {
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() && !cut.fail_facts.contains(&k) && k < 2 {
eprintln!(
" fact {k} refuted: {:?} clean {clean}",
v.as_ref().map(|v| ctx.tm.show(*v))
);
}
cut.fail_facts.insert(k);
}
}
if cut.pred.is_some() && end.cx.last_br != cut.pred {
cut.fail_pred = true;
}
if cut.world_same {
let same = same_log(&end.cx.mem.world, &cut.c_world)
&& same_log(&end.m.mem.world, &cut.m_world)
&& end.cx.mem.epoch == cut.c_epoch
&& end.m.mem.epoch == cut.m_epoch;
if !same {
cut.fail_world = true;
}
} else {
compare_world(
ctx,
job,
&end.cx.mem.world,
end.cx.mem.epoch,
&end.cx.mem.exposed,
&end.m,
"memory at a loop head",
&mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
)?;
}
Ok(())
}
fn start_state(ctx: &mut Ctx, job: &Job, cut: &Cut) -> Option<SegInit> {
let tag = format!("hv{}", cut.id);
let fresh_epoch = 0x4000_0000 + ((cut.id as u32) << 16);
let mut c_mem = Mem::default();
let mut m_mem = Mem::default();
if cut.world_same {
c_mem.world = cut.c_world.clone();
c_mem.epoch = cut.c_epoch;
m_mem.world = cut.m_world.clone();
m_mem.epoch = cut.m_epoch;
} else {
c_mem.epoch = fresh_epoch;
m_mem.epoch = fresh_epoch;
}
let open = !cut.exposed.is_empty();
for e in &cut.exposed {
c_mem.exposed.push(Exposed {
base: e.base,
size: e.size,
dyn_size: None,
since: 0,
});
}
let mut also: Vec<T> = Vec::new();
let mut cvals = Vec::with_capacity(cut.c_locs.len());
for (i, l) in cut.c_locs.iter().enumerate() {
let Place::Mem { base, off, size } = l.place else {
unreachable!()
};
let v = match l.cands.first() {
Some(cand) => {
let v = expected(ctx, cand, &cvals, &[], size * 8)?;
for other in &l.cands[1..] {
if let Some(w) = expected(ctx, other, &cvals, &[], size * 8) {
also.push(ctx.tm.eq(v, w));
}
}
v
}
None => {
let v = ctx.named_sym(&format!("{tag}.c{i}.{}", size * 8), size * 8);
if open {
ctx.mark_young(v);
}
v
}
};
let a = ctx.tm.add_const(base, off as u64);
ctx.mem_write(&mut c_mem, a, size, v);
cvals.push(v);
}
let evals = expr_values(ctx, job, cut, &c_mem);
let mut regs = [ctx.tm.konst(32, 0); 16];
for (i, l) in cut.m_locs.iter().enumerate() {
let w = l.width();
let v = match l.cands.first() {
Some(&Cand::Obj(base, off)) => {
let Place::Mem { size, .. } = l.place else {
unreachable!("a cell of the frame")
};
c_read(ctx, job, &c_mem, Place::Mem { base, off, size })
}
Some(cand) => {
let v = expected(ctx, cand, &cvals, &evals, w)?;
for other in &l.cands[1..] {
if let Some(x) = expected(ctx, other, &cvals, &evals, w) {
also.push(ctx.tm.eq(v, x));
}
}
v
}
None => {
let v = ctx.named_sym(&format!("{tag}.m{i}.{w}"), w);
if open {
ctx.mark_young(v);
}
v
}
};
match l.place {
Place::Reg(r) => regs[r as usize] = v,
Place::Mem { base, off, size } => {
let a = ctx.tm.add_const(base, off as u64);
ctx.mem_write(&mut m_mem, a, size, v);
}
}
}
Some(SegInit {
c_block: cut.c_block,
c_mem,
m_pc: cut.m_pc,
m_regs: regs,
m_mem,
also,
tag,
exposed: cut.exposed.clone(),
})
}
fn attempt(ctx: &mut Ctx, job: &Job, pre: &[T], cuts: &mut [Cut], depth: usize) -> Result<Proof, Failure> {
let mut step = false;
let r = attempt_in(ctx, job, pre, cuts, depth, &mut step);
r.map_err(|e| Failure::of(&e, step, cuts))
}
fn attempt_in(ctx: &mut Ctx, job: &Job, pre: &[T], cuts: &mut [Cut], depth: usize, step: &mut bool) -> R<Proof> {
let blocks: Vec<usize> = cuts.iter().map(|c| c.c_block).collect();
let pcs: Vec<u32> = cuts.iter().map(|c| c.m_pc).collect();
ctx.limits.max_depth = depth;
for _round in 0..60 {
let mut proof = Proof {
object_size: cuts.iter().any(|c| !c.assumed.is_empty()),
..Proof::default()
};
let mut pending: Option<Stop> = None;
for start in std::iter::once(None).chain((0..cuts.len()).map(Some)) {
ctx.seg = start.map_or(0, |j| j as u32 + 1);
*step = start.is_some();
let init = match start {
Some(j) => Some(start_state(ctx, job, &cuts[j]).ok_or_else(|| fail("no start state"))?),
None => None,
};
let mut exprs: Vec<(Expr, bool)> = Vec::new();
if let Some(j) = start {
if cuts.iter().any(|c| c.refuted()) {
break;
}
if cuts[j].pred.is_some() {
exprs.extend(cuts[j].pred_exprs.iter().cloned());
}
exprs.extend(cuts[j].facts.iter().cloned());
exprs.extend(cuts[j].assumed.iter().cloned());
}
ctx.decisions.clear();
let mut n = 0;
loop {
ctx.restart(pre);
let ctl = SegCtl {
init: init.as_ref(),
assume: exprs.iter().map(|(e, w)| (e, *w)).collect(),
c_cuts: &blocks,
m_cuts: &pcs,
stop: match start {
None => cuts[0].lead,
Some(j) => cuts[j].ratio,
},
m_stop: 1,
prefix: None,
};
match run_seg(ctx, job, &ctl) {
Ok(mut end) => {
if let Some(j) = start
&& end.m.first_reads.get() & cuts[j].stale != 0
{
return Err(fail(
"a stack address changes in the loop in a way that is not understood",
));
}
if let Some((b, pc)) = end.cut {
let j = blocks.iter().position(|&x| x == b).expect("a cut block");
if cuts[j].m_pc != pc {
return Err(fail("the two sides arrive at different loops"));
}
match arrive(ctx, job, &mut cuts[j], &mut end) {
Err(e @ (Stop::Mismatch(..) | Stop::Inconclusive(_))) if start.is_some() => {
pending.get_or_insert(e);
}
r => r?,
}
}
proof.paths += 1;
proof.cov.extend(end.res.cov);
proof.bytes.extend(end.res.insns);
proof.bytes.extend(end.res.data);
}
Err(Stop::Undefined) => {}
Err(e @ (Stop::Mismatch(..) | Stop::Inconclusive(_) | Stop::Unsupported(_))) if start.is_some() => {
pending.get_or_insert(e);
}
Err(e) => return Err(e),
}
n += 1;
if n > 400 {
return Err(Stop::Truncated("too many paths through a loop body".into()));
}
if !ctx.next_path() {
break;
}
}
}
let mut changed = false;
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
for cut in cuts.iter() {
eprintln!(
" round {_round} cut ({}, {:#x}): refuted source {:?} machine {:?} facts {:?} pred {} world {} grew {}",
cut.c_block,
cut.m_pc,
cut.fail_c,
cut.fail_m,
cut.fail_facts,
cut.fail_pred,
cut.fail_world,
cut.grew
);
}
}
for cut in cuts.iter_mut() {
for (i, n) in std::mem::take(&mut cut.fail_c).into_iter().rev() {
cut.c_locs[i].cands.remove(n);
changed = true;
}
for (i, n) in std::mem::take(&mut cut.fail_m).into_iter().rev() {
cut.m_locs[i].cands.remove(n);
changed = true;
}
let dead = std::mem::take(&mut cut.fail_facts);
if !dead.is_empty() {
let mut k = 0;
cut.facts.retain(|_| {
k += 1;
!dead.contains(&(k - 1))
});
changed = true;
}
if std::mem::take(&mut cut.fail_pred) {
cut.pred = None;
changed = true;
}
if std::mem::take(&mut cut.fail_world) {
cut.world_same = false;
changed = true;
}
changed |= std::mem::take(&mut cut.grew);
}
if !changed {
return match pending {
Some(e) => Err(e),
None => Ok(proof),
};
}
}
Err(Stop::Truncated("the loop relation did not stabilise".into()))
}
fn size_assumption(p: &Program, body: &Body, l: &CLoop) -> Option<(Expr, bool)> {
use crate::c::ast::OpKind;
let Term::Br(cond, t, e) = &body.blocks[l.head].term else {
return None;
};
if !l.inside.contains(t) || l.inside.contains(e) {
return None;
}
let EK::Bin(BinOp::Lt, a, b) = &cond.kind else {
return None;
};
let local = |x: &Expr| match &x.kind {
EK::Load(v) => match v.kind {
EK::Local(i) if p.bits(x.ty) == 32 && !p.is_signed(x.ty) && !p.is_volatile(x.ty) => Some(i),
_ => None,
},
_ => None,
};
let (i, n) = (local(a)?, local(b)?);
struct Seen {
i: u32,
n: u32,
bad: bool,
steps: usize,
size: Option<u32>,
}
fn walk(p: &Program, e: &Expr, always: bool, in_loop: bool, s: &mut Seen) {
let is = |x: &Expr, v: u32| matches!(x.kind, EK::Local(w) if w == v);
match &e.kind {
EK::Addr(x) if is(x, s.i) || is(x, s.n) => s.bad = true,
_ if !in_loop => {}
EK::Call(..) | EK::Asm(..) | EK::VaArg(..) | EK::VaStart(..) | EK::Alloca(..) | EK::Compound { .. } => {
s.bad = true
}
EK::Assign(x, _) if is(x, s.i) || is(x, s.n) => s.bad = true,
EK::AssignOp(x, v, _) if is(x, s.n) || (is(x, s.i) && !always) => {
let _ = v;
s.bad = true
}
EK::AssignOp(x, v, _) if is(x, s.i) => match &v.kind {
EK::Bin(BinOp::Add, a, b) if matches!(a.kind, EK::Prev) => {
let mut one: &Expr = b;
while let EK::Cast(y) = &one.kind {
one = y;
}
if matches!(one.kind, EK::Const(1)) {
s.steps += 1
} else {
s.bad = true
}
}
_ => s.bad = true,
},
EK::PtrAdd(_, idx, size) if always => {
let mut x: &Expr = idx;
let mut whole = true;
while let EK::Cast(y) = &x.kind {
whole &= p.bits(x.ty) == 32;
x = y;
}
if let EK::Load(v) = &x.kind
&& is(v, s.i)
&& whole
{
s.size = Some(s.size.map_or(*size, |z| z.max(*size)));
}
}
_ => {}
}
match &e.kind {
EK::LogAnd(a, b) | EK::LogOr(a, b) => {
walk(p, a, always, in_loop, s);
walk(p, b, false, in_loop, s);
}
EK::Cond(a, b, c) => {
walk(p, a, always, in_loop, s);
walk(p, b, false, in_loop, s);
walk(p, c, false, in_loop, s);
}
_ => e.children().into_iter().for_each(|c| walk(p, c, always, in_loop, s)),
}
}
let mut s = Seen {
i,
n,
bad: false,
steps: 0,
size: None,
};
for (k, b) in body.blocks.iter().enumerate() {
let in_loop = l.inside.contains(&k);
if in_loop && k != l.head && !matches!(b.term, Term::Jump(_)) {
return None;
}
for op in &b.ops {
match &op.kind {
OpKind::Eval(e) => walk(p, e, true, in_loop, &mut s),
OpKind::Init { var, items, .. } => {
s.bad |= in_loop && (*var == i || *var == n);
items.iter().for_each(|x| walk(p, &x.1, true, in_loop, &mut s));
}
}
}
match &b.term {
Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => walk(p, e, true, in_loop, &mut s),
_ => {}
}
}
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
eprintln!(
"counted loop at block {}: size {:?} bad {} steps {}",
l.head, s.size, s.bad, s.steps
);
}
let size = s.size.filter(|&z| z >= 2 && !s.bad && s.steps == 1)?;
let with = |kind: EK| Expr {
kind,
ty: cond.ty,
loc: cond.loc,
};
let limit = Expr {
kind: EK::Const(((1u64 << 31) - 1) / size as u64 + 1),
ty: b.ty,
loc: b.loc,
};
let done = with(EK::Bin(BinOp::Le, b.clone(), a.clone()));
let small = with(EK::Bin(BinOp::Le, b.clone(), Box::new(limit)));
Some((with(EK::Bin(BinOp::Or, Box::new(done), Box::new(small))), true))
}
fn callee_with_loop(p: &Program, fid: u32) -> Option<&str> {
use crate::c::ast::OpKind;
fn mentions(e: &Expr, out: &mut Vec<u32>) {
if let EK::Func(id) = e.kind {
out.push(id);
}
for c in e.children() {
mentions(c, out);
}
}
let mut seen = HashSet::from([fid]);
let mut work = vec![(fid, 0)];
while let Some((f, depth)) = work.pop() {
let Some(body) = &p.funcs[f as usize].body else {
continue;
};
if body.blocks.is_empty() {
continue;
}
if f != fid && !c_loops(body).is_empty() {
return Some(&p.funcs[f as usize].name);
}
if depth >= 4 {
continue;
}
let mut found = Vec::new();
for b in &body.blocks {
for op in &b.ops {
match &op.kind {
OpKind::Eval(e) => mentions(e, &mut found),
OpKind::Init { items, .. } => items.iter().for_each(|i| mentions(&i.1, &mut found)),
}
}
match &b.term {
Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => mentions(e, &mut found),
_ => {}
}
}
for g in found {
if seen.insert(g) {
work.push((g, depth + 1));
}
}
}
None
}
pub(super) fn prove(ctx: &mut Ctx, job: &Job, pre: &[T], range: (u32, u32)) -> Result<Proof, Failure> {
let debug = std::env::var_os("CVERIF_DEBUG").is_some();
let no_loop = || match callee_with_loop(job.prog, job.fid) {
Some(g) => Failure::new(
"callee-loop",
format!("the function's own body has no loop; {g}, which it calls, has one"),
0,
),
None => Failure::new("no-source-loop", "neither the function nor what it calls has a loop", 0),
};
let body = job.prog.funcs[job.fid as usize].body.as_ref().ok_or_else(no_loop)?;
let loops = c_loops(body);
if loops.is_empty() {
return Err(no_loop());
}
let sizes: Vec<(usize, (Expr, bool))> = (0..loops.len())
.filter_map(|l| Some((l, size_assumption(job.prog, body, &loops[l])?)))
.collect();
let mut worst: Option<Failure> = None;
let note = |f: Failure, worst: &mut Option<Failure>| {
if worst.as_ref().is_none_or(|w| f.rank > w.rank) {
*worst = Some(f);
}
};
let saved = (ctx.limits, ctx.seg);
let work0 = ctx.work();
let result = (|| {
let mut short = false;
for (stage, depths) in [&[3usize, 5, 8][..], &[12, 20][..]].into_iter().enumerate() {
let ex = match explore(ctx, job, pre, &loops, range, depths) {
Ok(ex) => ex,
Err(f) => {
note(f, &mut worst);
continue;
}
};
let plain = !short;
short = true;
let mut per_loop: Vec<Vec<Pair>> = Vec::new();
for l in &loops {
let mut pairs: Vec<(usize, Pair)> = Vec::new();
for (order, &block) in l.cands.iter().enumerate() {
let nc = ex.c.iter().filter(|s| s.block == block).count();
if nc == 0 {
continue;
}
let mut counts: BTreeMap<u32, usize> = BTreeMap::new();
for s in &ex.m {
*counts.entry(s.pc).or_default() += 1;
}
let c_ev: Vec<u32> = ex.c.iter().filter(|s| s.block == block).map(|s| s.nev).collect();
for (pc, nm) in counts {
let is_back = ex.back.contains(&pc);
if plain && (nm >= 2 || is_back) {
let m_ev: Vec<u32> = ex.m.iter().filter(|s| s.pc == pc).map(|s| s.nev).collect();
for lead in 1..=2usize {
if nc < lead || !c_ev[lead - 1..].iter().zip(&m_ev).all(|(a, b)| a == b) {
continue;
}
let pair = Pair {
block,
pc,
lead,
ratio: 1,
};
let score = (nc + 1 - lead).abs_diff(nm) * 4 + order + 3 * usize::from(!is_back);
pairs.push((score + 2 * (lead - 1), pair));
break;
}
}
if stage == 1 && is_back && nm >= 2 && nc > nm {
let (low, high) = (nc.div_ceil(nm + 1).max(2), (nc - 1) / (nm - 1));
for ratio in (low..=high).rev().take(4) {
let span = (nm - 1) * ratio;
for lead in 1..=ratio {
if lead + span <= nc {
let pair = Pair { block, pc, lead, ratio };
pairs.push((100 + order + 2 * lead, pair));
}
}
}
}
}
}
pairs.sort_by_key(|p| (p.0, p.1.pc, p.1.ratio, p.1.lead));
pairs.truncate(if stage == 0 { 8 } else { 30 });
if !pairs.is_empty() {
per_loop.push(pairs.into_iter().map(|p| p.1).collect());
}
}
let mut plans: Vec<Vec<Pair>> = per_loop.iter().flatten().map(|&p| vec![p]).collect();
if per_loop.len() >= 2 && plain {
let first: Vec<Pair> = per_loop.iter().map(|p| p[0]).collect();
if (0..first.len())
.all(|i| (0..i).all(|j| first[i].pc != first[j].pc && first[i].block != first[j].block))
{
plans.insert(0, first);
}
let mut combos: Vec<Vec<Pair>> = vec![Vec::new()];
for pairs in &per_loop {
let mut next = Vec::new();
for c in &combos {
for &p in pairs.iter().take(4) {
if c.iter().any(|q: &Pair| q.pc == p.pc) {
continue;
}
let mut c = c.clone();
c.push(p);
next.push(c);
}
}
combos = next;
combos.truncate(24);
}
plans.extend(combos);
}
if plans.is_empty() {
let f = Failure::new(
"no-cut-pair",
"no address of the binary is reached as often as a loop head of the source, with the same calls made",
2,
);
note(f, &mut worst);
}
for plan in plans.into_iter().take(64) {
if let Err(e) = ctx.check_deadline() {
let w = match e {
Stop::Truncated(w) => w,
e => format!("{e:?}"),
};
note(Failure::new("budget", format!("{w} before any attempt"), 3), &mut worst);
return None;
}
let mut cuts = Vec::new();
for (id, &pair) in plan.iter().enumerate() {
let Some(cut) = build_cut(ctx, job, &ex, id, pair) else {
break;
};
cuts.push(cut);
}
if cuts.len() != plan.len() {
let f = Failure::new(
"no-cut-pair",
"no relation can be set up at the candidate cut points",
3,
);
note(f, &mut worst);
continue;
}
if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
for cut in &cuts {
eprintln!(
"cut ({}, {:#x}) lead {} ratio {} pred {:?} world_same {}",
cut.c_block, cut.m_pc, cut.lead, cut.ratio, cut.pred, cut.world_same
);
for (side, locs) in [("source", &cut.c_locs), ("machine", &cut.m_locs)] {
for (i, l) in locs.iter().enumerate() {
let cands: Vec<String> = l
.cands
.iter()
.map(|c| match c {
Cand::Inv(v) => format!("= {}", ctx.tm.show(*v)),
Cand::Rel(j, view) => format!("= {view:?}(source {j})"),
Cand::Val(k, view) => format!("= {view:?}(expr {k})"),
Cand::Two(j, a, k, neg, x, d) => format!(
"= {}*source {j} {} source {k} + {x:?} + {}",
*a as u32 as i32,
if *neg { "-" } else { "+" },
*d as u32 as i32
),
Cand::Lin2(j, _, a, base, d) => {
format!(
"= {}*source {j} + {base:?} + {}",
*a as u32 as i32, *d as u32 as i32
)
}
Cand::Obj(b, off) => format!("= object {} + {off}", ctx.tm.show(*b)),
Cand::Lin(j, _, a, b) => {
format!("= {}*source {j} + {}", *a as u32 as i32, ctx.tm.show(*b))
}
})
.collect();
eprintln!(" {side} {i} {:?}: {}", l.place, cands.join(" | "));
}
}
}
}
let fresh = cuts.clone();
let mut r = attempt(ctx, job, pre, &mut cuts, 16);
if r.is_err() && !sizes.is_empty() {
cuts = fresh;
let mut any = false;
for cut in cuts.iter_mut() {
for (l, a) in &sizes {
if loops[*l].inside.contains(&cut.c_block) {
cut.assumed.push(a.clone());
any = true;
}
}
}
if any {
r = attempt(ctx, job, pre, &mut cuts, 16);
}
}
match r {
Ok(proof) => return Some(proof),
Err(e) => {
if debug {
eprintln!("loop proof with cuts {plan:x?} failed: {e:?}");
}
note(e, &mut worst);
}
}
}
}
let whole = (ctx.work_limit, ctx.max_terms, ctx.deadline);
if whole.0 != u64::MAX {
let more = ctx.work() + whole.0.saturating_sub(work0) / 2;
ctx.set_budget(whole.0.max(more), whole.1, whole.2);
ctx.prover.forget_unknown();
}
let r = prefix_plan(ctx, job, pre, &loops, range, debug).map(|mut cuts| attempt(ctx, job, pre, &mut cuts, 16));
ctx.set_budget(whole.0, whole.1, whole.2);
match r? {
Ok(proof) => return Some(proof),
Err(e) => {
if debug {
eprintln!("loop proof with cuts from path prefixes failed: {e:?}");
}
note(e, &mut worst);
}
}
None
})();
ctx.limits = saved.0;
ctx.seg = saved.1;
ctx.decisions.clear();
result.ok_or_else(|| worst.unwrap_or_else(|| Failure::new("unsupported-shape", "no attempt was made", 0)))
}