logicaffeine_verify/
multiclock.rs1use crate::equivalence::Trace;
12use crate::ir::VerifyExpr;
13use crate::kinduction;
14use std::collections::{HashMap, HashSet};
15
16#[derive(Debug, Clone)]
17pub struct ClockDomain {
18 pub name: String,
19 pub frequency: Option<u64>,
20 pub ratio: Option<(u32, u32)>,
21}
22
23#[derive(Debug, Clone)]
24pub struct MultiClockModel {
25 pub domains: Vec<ClockDomain>,
26 pub init: VerifyExpr,
27 pub transitions: HashMap<String, VerifyExpr>,
28 pub property: VerifyExpr,
29}
30
31#[derive(Debug)]
32pub enum MultiClockResult {
33 Safe,
34 Unsafe { trace: Trace },
35 Unknown,
36}
37
38fn gcd(a: u32, b: u32) -> u32 {
39 if b == 0 {
40 a
41 } else {
42 gcd(b, a % b)
43 }
44}
45
46fn lcm(a: u32, b: u32) -> u32 {
47 if a == 0 || b == 0 {
48 1
49 } else {
50 a / gcd(a, b) * b
51 }
52}
53
54pub fn compute_schedule(domains: &[ClockDomain]) -> Vec<Vec<bool>> {
67 if domains.is_empty() {
68 return vec![vec![]];
69 }
70
71 let rates: Vec<(u32, u32)> = domains.iter().map(|d| d.ratio.unwrap_or((1, 1))).collect();
72
73 let common_denom: u32 = rates.iter().fold(1u32, |acc, &(_, d)| lcm(acc, d));
76 let scaled: Vec<u32> = rates.iter().map(|&(n, d)| n * (common_denom / d)).collect();
77 let period = *scaled.iter().max().unwrap_or(&1);
78
79 if period == 0 {
80 return vec![vec![false; domains.len()]];
81 }
82
83 let mut schedule = Vec::with_capacity(period as usize);
84 for step in 0..period {
85 let mut fires = Vec::with_capacity(domains.len());
86 for &fire_count in &scaled {
87 if fire_count == 0 {
88 fires.push(false);
89 } else if fire_count >= period {
90 fires.push(true);
91 } else {
92 let remainder = (step as u64 * fire_count as u64) % period as u64;
95 fires.push(remainder < fire_count as u64);
96 }
97 }
98 schedule.push(fires);
99 }
100
101 schedule
102}
103
104fn extract_next_state_vars(expr: &VerifyExpr) -> HashSet<String> {
108 let mut all_vars = HashSet::new();
109 crate::equivalence::collect_vars_pub(expr, &mut all_vars);
110 let mut bases = HashSet::new();
111 for v in &all_vars {
112 if let Some(base) = v.strip_suffix("@t1") {
113 bases.insert(base.to_string());
114 }
115 }
116 bases
117}
118
119fn build_frame_condition(transition: &VerifyExpr) -> VerifyExpr {
122 let bases = extract_next_state_vars(transition);
123 let mut conditions: Vec<VerifyExpr> = bases
124 .into_iter()
125 .map(|base| {
126 VerifyExpr::iff(
127 VerifyExpr::var(format!("{}@t1", base)),
128 VerifyExpr::var(format!("{}@t", base)),
129 )
130 })
131 .collect();
132 conditions.sort_by(|a, b| format!("{:?}", a).cmp(&format!("{:?}", b)));
134 if conditions.is_empty() {
135 VerifyExpr::bool(true)
136 } else {
137 conditions
138 .into_iter()
139 .reduce(|a, b| VerifyExpr::and(a, b))
140 .unwrap()
141 }
142}
143
144pub fn verify_multiclock(model: &MultiClockModel, bound: u32) -> MultiClockResult {
151 if model.domains.len() <= 1 {
152 let transition = model
153 .transitions
154 .values()
155 .next()
156 .cloned()
157 .unwrap_or(VerifyExpr::bool(true));
158 let result = kinduction::k_induction(&model.init, &transition, &model.property, &[], bound);
159 match result {
160 kinduction::KInductionResult::Proven { .. } => MultiClockResult::Safe,
161 kinduction::KInductionResult::Counterexample { trace, .. } => {
162 MultiClockResult::Unsafe { trace }
163 }
164 _ => MultiClockResult::Unknown,
165 }
166 } else {
167 verify_multiclock_interleaved(model, bound)
168 }
169}
170
171fn verify_multiclock_interleaved(model: &MultiClockModel, bound: u32) -> MultiClockResult {
181 let schedule = compute_schedule(&model.domains);
182 let period = schedule.len() as u32;
183
184 let mut frame_conditions: HashMap<String, VerifyExpr> = HashMap::new();
186 for domain in &model.domains {
187 if let Some(trans) = model.transitions.get(&domain.name) {
188 frame_conditions.insert(domain.name.clone(), build_frame_condition(trans));
189 }
190 }
191
192 let mut step_transitions: Vec<VerifyExpr> = Vec::with_capacity(period as usize);
197 for step_idx in 0..period as usize {
198 let mut parts: Vec<VerifyExpr> = Vec::new();
199 for (domain_idx, domain) in model.domains.iter().enumerate() {
200 let fires = schedule
201 .get(step_idx)
202 .and_then(|s| s.get(domain_idx))
203 .copied()
204 .unwrap_or(true);
205 if fires {
206 if let Some(trans) = model.transitions.get(&domain.name) {
207 parts.push(trans.clone());
208 }
209 } else {
210 if let Some(frame) = frame_conditions.get(&domain.name) {
211 parts.push(frame.clone());
212 }
213 }
214 }
215 let combined = if parts.is_empty() {
216 VerifyExpr::bool(true)
217 } else {
218 parts
219 .into_iter()
220 .reduce(|a, b| VerifyExpr::and(a, b))
221 .unwrap()
222 };
223 step_transitions.push(combined);
224 }
225
226 k_induction_with_schedule(&model.init, &step_transitions, &model.property, bound)
230}
231
232fn k_induction_with_schedule(
237 init: &VerifyExpr,
238 step_transitions: &[VerifyExpr],
239 property: &VerifyExpr,
240 max_k: u32,
241) -> MultiClockResult {
242 use z3::{ast::Bool, SatResult};
243
244 let period = step_transitions.len() as u32;
245 if period == 0 {
246 return MultiClockResult::Safe;
247 }
248
249 for k in 1..=max_k {
250 let base_result = {
253 let solver = crate::solver::new_solver();
254
255 let init_0 = kinduction::instantiate_at(init, 0);
256 let init_z3 = encode_to_bool_mc(&init_0);
257 solver.assert(&init_z3);
258
259 for t in 0..k.saturating_sub(1) {
260 let sched_idx = (t % period) as usize;
261 let trans = kinduction::instantiate_transition(&step_transitions[sched_idx], t);
262 let trans_z3 = encode_to_bool_mc(&trans);
263 solver.assert(&trans_z3);
264 }
265
266 let mut not_props: Vec<Bool> = Vec::new();
267 for t in 0..k {
268 let prop_t = kinduction::instantiate_at(property, t);
269 let prop_z3 = encode_to_bool_mc(&prop_t);
270 not_props.push(prop_z3.not());
271 }
272 let not_prop_refs: Vec<&Bool> = not_props.iter().collect();
273 let some_violation = Bool::or(¬_prop_refs);
274 solver.assert(&some_violation);
275
276 solver.check()
277 };
278
279 match base_result {
280 SatResult::Sat => {
281 return MultiClockResult::Unsafe {
282 trace: Trace { cycles: vec![] },
283 };
284 }
285 SatResult::Unknown => return MultiClockResult::Unknown,
286 SatResult::Unsat => {}
287 }
288
289 let step_result = {
292 let solver = crate::solver::new_solver();
293
294 for t in 0..k {
295 let prop_t = kinduction::instantiate_at(property, t);
296 let prop_z3 = encode_to_bool_mc(&prop_t);
297 solver.assert(&prop_z3);
298 }
299
300 for t in 0..k {
301 let sched_idx = (t % period) as usize;
302 let trans = kinduction::instantiate_transition(&step_transitions[sched_idx], t);
303 let trans_z3 = encode_to_bool_mc(&trans);
304 solver.assert(&trans_z3);
305 }
306
307 let prop_k = kinduction::instantiate_at(property, k);
308 let prop_k_z3 = encode_to_bool_mc(&prop_k);
309 solver.assert(&prop_k_z3.not());
310
311 solver.check()
312 };
313
314 match step_result {
315 SatResult::Unsat => {
316 return MultiClockResult::Safe;
317 }
318 SatResult::Unknown => return MultiClockResult::Unknown,
319 SatResult::Sat => {}
320 }
321 }
322
323 MultiClockResult::Unknown
324}
325
326fn encode_to_bool_mc(expr: &VerifyExpr) -> z3::ast::Bool {
328 let mut all_vars = HashSet::new();
329 crate::equivalence::collect_vars_pub(expr, &mut all_vars);
330
331 let mut bool_vars: HashMap<String, z3::ast::Bool> = HashMap::new();
332 let mut int_vars: HashMap<String, z3::ast::Int> = HashMap::new();
333
334 for name in &all_vars {
335 bool_vars.insert(name.clone(), z3::ast::Bool::new_const(name.as_str()));
336 }
337 crate::equivalence::collect_int_vars_pub(expr, &mut int_vars);
338
339 kinduction::encode_expr_bool(expr, &bool_vars, &int_vars)
340}