Skip to main content

logicaffeine_verify/
multiclock.rs

1//! Multi-Clock Domain Modeling
2//!
3//! Real designs have multiple clock domains. Each domain unrolls independently.
4//! Cross-domain references use interleaved scheduling based on clock ratios.
5//!
6//! The schedule is computed from each domain's ratio (numerator, denominator).
7//! Within one LCM period, each domain fires proportionally to its normalized rate.
8//! On global steps where a domain does NOT fire, a frame condition holds its
9//! state variables unchanged.
10
11use 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
54/// Compute the interleaved firing schedule for a set of clock domains.
55///
56/// Returns a `Vec<Vec<bool>>` where `schedule[global_step][domain_index]`
57/// indicates whether that domain fires at that global step.
58///
59/// The schedule covers one full LCM period. Ratios are interpreted as
60/// (numerator, denominator) meaning the domain fires `numerator` times
61/// per `denominator`-unit base period. Domains without a ratio default
62/// to (1, 1).
63///
64/// Within the LCM period, the fastest domain fires every step. Slower
65/// domains fire at evenly-spaced intervals proportional to their rates.
66pub 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    // Normalize rates to a common denominator, then the period is the max
74    // scaled numerator. Each domain fires scaled_rate times in period steps.
75    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                // Bresenham-style even distribution starting at step 0.
93                // Domain fires at step s if (s * fire_count) % period < fire_count.
94                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
104/// Extract the set of "next-state" variable base names from a transition expression.
105///
106/// Looks for variables matching `<name>@t1` and returns the base names.
107fn 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
119/// Build a frame condition for a domain: all its next-state variables equal current-state.
120/// `var@t1 <=> var@t` for each variable in the domain's transition.
121fn 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    // Sort for determinism
133    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
144/// Verify a multi-clock domain design.
145///
146/// For single domain (or zero domains), delegates to standard k-induction.
147/// For multiple domains, computes an interleaved schedule from clock ratios
148/// and builds per-step transitions that apply each domain's transition on its
149/// fire steps and a frame condition (state held) on non-fire steps.
150pub 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
171/// Multi-domain verification with interleaved scheduling.
172///
173/// Algorithm:
174/// 1. Compute the schedule from domain ratios.
175/// 2. For each global step in the schedule period, build a combined transition:
176///    - If domain fires: apply its transition
177///    - If domain does not fire: apply frame condition (state held)
178/// 3. Use BMC-style unrolling with the schedule-aware transitions and
179///    check the property at each step.
180fn verify_multiclock_interleaved(model: &MultiClockModel, bound: u32) -> MultiClockResult {
181    let schedule = compute_schedule(&model.domains);
182    let period = schedule.len() as u32;
183
184    // Build per-domain frame conditions
185    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    // Build the transition for each global step within one period.
193    // Each step's transition is the conjunction of all domains' contributions:
194    // - fire => domain's transition
195    // - !fire => frame condition
196    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    // Now run k-induction where each step uses the schedule-appropriate transition.
227    // We pass the schedule-aware transitions to a custom k-induction loop that
228    // cycles through the schedule period.
229    k_induction_with_schedule(&model.init, &step_transitions, &model.property, bound)
230}
231
232/// K-induction that cycles through a vector of transitions (one per schedule step).
233///
234/// This is like standard k-induction but the transition at global step `t` is
235/// `step_transitions[t % period]` instead of a single uniform transition.
236fn 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        // ---- Base case ----
251        // init(0) AND T_0(0,1) AND T_1(1,2) AND ... AND T_{k-2}(k-2,k-1) AND NOT P(i) for some i
252        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(&not_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        // ---- Inductive step ----
290        // P(0) AND P(1) AND ... AND P(k-1) AND T_0(0,1) AND ... AND T_{k-1}(k-1,k) AND NOT P(k)
291        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
326/// Encode a VerifyExpr to Z3 Bool for multi-clock verification.
327fn 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}