vj 0.2.0

vj: a SystemVerilog (IEEE 1800-2023) simulator built on slang and LLVM.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Clocking blocks (LRM 1800-2023 ยง14).
//!
//! The planner's side: [`samplers`] describes each block's sampler as image
//! data (`vj_sim::image::verif::ClockingImage`), and the slang-free
//! `vj_exec::clocking` registers it, for `vj run` and an AOT `.so`
//! alike (see its module doc for what a sampler does). `default_clocking`,
//! `checker_inferred_clock` and `global_clock_event` find the clocking events
//! the lowering needs.

use std::collections::HashMap;

use sv_lang::kinds::SymbolKind;
use sv_lang::{Symbol, SyntaxTree};
use vj_codegen::error::LoweringError;
use vj_codegen::pipeline::CovergroupLoweringSpec;
use vj_codegen::process_lower::{SignalSlot, to_state_edge_kind};
use vj_sim::image::verif::{ClockingImage, SKEW_EDGE_OPP, SKEW_STEP};
use vj_sim::netlist::InstanceId;
use vj_sim::state::EdgeKind as StateEdgeKind;
use vj_sim::symid::{SymbolId, SymbolUid};

/// The input ports a clocking event may be traced through (see
/// [`through_ports`]): `(child instance, port signal) -> (parent instance,
/// parent signal, its slot)`, for a port connected whole to a parent variable of
/// the same width (`run.rs` `clock_port_sources`).
pub(crate) type PortSources = HashMap<(InstanceId, SymbolId), (InstanceId, SymbolId, u32)>;

/// Follows `sig` of `inst` up through input port connections to the parent
/// signal that drives it: LRM 14.13 makes the clocking event and the parent's
/// `@(posedge clk)` one event, but the port's own copy of `clk` is updated by a
/// continuous assignment a delta later. `(inst, slot)` itself when `sig` is no
/// such port.
fn through_ports(
    sources: &PortSources,
    mut inst: InstanceId,
    mut sig: SymbolId,
    mut slot: u32,
) -> (InstanceId, u32) {
    while let Some((pi, ps, pslot)) = sources.get(&(inst, sig.clone())) {
        (inst, sig, slot) = (*pi, ps.clone(), *pslot);
    }
    (inst, slot)
}

/// `body`'s default clocking block: the inline `default clocking cb @(..) ..;`
/// form or the reference form `clocking cb @(..) ..; default clocking cb;`
/// (LRM 14.12), resolved by [`vj_sim::state::default_clocking_of`]. A
/// malformed declaration (duplicate default, unresolved target) was already
/// diagnosed by slang, so it resolves to none here.
pub(crate) fn default_clocking<'d>(body: &Symbol<'d>, trees: &[SyntaxTree]) -> Option<Symbol<'d>> {
    let tree = trees.iter().find(|t| {
        vj_sim::netlist::module_items(body)
            .iter()
            .any(|m| m.syntax(t).is_some())
    })?;
    vj_sim::state::default_clocking_of(body, tree)
        .ok()
        .flatten()
}

/// What a checker procedure's `@clock` waits on when `clock` kept its default
/// `$inferred_clock` (LRM 17.4): the clocking event of the default clocking
/// (14.12) in effect where the checker is instantiated, as the signal and edge.
/// `proc_sym` is a member of the checker's body: a procedure, or the checker's own
/// `default clocking @clock;` block. `Ok(None)` for a member that is not a checker's, or whose instantiation
/// context has no default clocking (a procedure that then waits on
/// `$inferred_clock` is refused by the CFG builder, naming 17.4).
pub(crate) fn checker_inferred_clock<'d>(
    proc_sym: &Symbol<'d>,
    trees: &[SyntaxTree],
) -> Result<Option<vj_sim::process::cfg::InferredClockEvent<'d>>, String> {
    let Some(body) = proc_sym
        .parent()
        .filter(|p| p.kind() == SymbolKind::CheckerInstanceBody)
    else {
        return Ok(None);
    };
    let Some(scope) = body
        .checker_instance_body_parent_instance()
        .and_then(|inst| inst.parent())
    else {
        return Ok(None);
    };
    let Some(tree) = trees.iter().find(|t| proc_sym.syntax(t).is_some()) else {
        return Err("no syntax tree for a checker procedure or clocking block".to_string());
    };
    let found = vj_sim::state::default_clocking_of(&scope, tree)
        .map_err(|e| format!("default clocking (LRM 14.12): {e:?}"))?;
    let Some(event) = found.and_then(|cb| cb.clocking_block_event()) else {
        return Ok(None);
    };
    let Some(tc) = event.as_timing_control() else {
        return Err("a default clocking whose event is not a timing control".to_string());
    };
    let clock = vj_sim::sva::sampled::clock_event_of(tc).map_err(|e| e.0)?;
    Ok(Some((clock.signal, clock.edge, clock.iff)))
}

/// Whether procedural block `proc_sym` calls `$global_clock` (the lookup
/// climbs the hierarchy, so only such a process pays for it).
pub(crate) fn mentions_global_clock(proc_sym: &Symbol<'_>) -> bool {
    let mut stack: Vec<sv_lang::SemNode<'_>> = vj_sim::process::cfg::proc_body(proc_sym)
        .map(|b| b.as_sem_node())
        .into_iter()
        .collect();
    while let Some(n) = stack.pop() {
        if n.as_expression()
            .is_some_and(|e| vj_sim::process::cfg::is_global_clock_call(&e))
        {
            return true;
        }
        stack.extend(vj_sim::process::cfg::live_children(&n));
    }
    false
}

/// The event of a global clocking declared in an ENCLOSING instance (LRM
/// 14.14: the lookup climbs the instantiation chain) that `proc_sym` waits
/// on. Its signals belong to that instance, so the caller registers them as
/// foreign references of `proc_sym`'s instance.
pub(crate) fn enclosing_global_clock_event<'d>(
    proc_sym: &Symbol<'d>,
    trees: &[SyntaxTree],
) -> Option<sv_lang::SemNode<'d>> {
    if !mentions_global_clock(proc_sym) && !calls_gclk_sampled(proc_sym) {
        return None;
    }
    let body = vj_sim::netlist::enclosing_instance_body(proc_sym)?;
    let global = vj_sim::sva::global_clock::global_clocking_of(&body, trees).ok()??;
    if global.levels_up == 0 {
        return None;
    }
    global.block.clocking_block_event()
}

/// Whether `proc_sym` calls a `*_gclk` sampled value function (LRM 16.9.4),
/// whose clock is the global clocking's event.
fn calls_gclk_sampled(proc_sym: &Symbol<'_>) -> bool {
    vj_sim::sva::sampled::sites_of_block(proc_sym)
        .is_ok_and(|sites| sites.iter().any(|s| s.call.global))
}

/// The event of a global clocking declared in an ENCLOSING instance (LRM
/// 14.14) that `body`'s concurrent assertions and clocking blocks may be
/// clocked by (`default clocking @$global_clock`, `@$global_clock` in an
/// assertion): their event signals are foreign to `body`'s instance, so the
/// caller registers them as foreign references, which is what lets an
/// assertion row read them. `None` unless `body` has a clocking block or a
/// procedural concurrent assertion and the global clocking is not its own.
pub(crate) fn enclosing_global_clock_for_assertions<'d>(
    body: &Symbol<'d>,
    trees: &[SyntaxTree],
) -> Option<sv_lang::SemNode<'d>> {
    let items = vj_sim::netlist::module_items(body);
    let has_assertion = |m: &Symbol<'d>| {
        m.kind() == SymbolKind::ClockingBlock
            || (m.kind() == SymbolKind::ProceduralBlock
                && vj_sim::process::cfg::proc_body(m).is_some_and(|b| {
                    let mut stack = vec![b.as_sem_node()];
                    while let Some(n) = stack.pop() {
                        if n.as_statement().is_some_and(|s| {
                            s.kind() == sv_lang::kinds::StatementKind::ConcurrentAssertion
                        }) {
                            return true;
                        }
                        stack.extend(vj_sim::process::cfg::live_children(&n));
                    }
                    false
                }))
    };
    if !items.iter().any(has_assertion) {
        return None;
    }
    let global = vj_sim::sva::global_clock::global_clocking_of(body, trees).ok()??;
    if global.levels_up == 0 {
        return None;
    }
    global.block.clocking_block_event()
}

/// The event `@$global_clock` waits on in procedural block `proc_sym`: that of
/// the global clocking in effect (14.14: its own instance's, else the nearest
/// enclosing instance's). `None` when it mentions none or none is declared,
/// which the lowering then refuses where it is used.
pub(crate) fn global_clock_event<'d>(
    proc_sym: &Symbol<'d>,
    trees: &[SyntaxTree],
) -> Result<Option<vj_sim::process::cfg::InferredClockEvent<'d>>, String> {
    if !mentions_global_clock(proc_sym) {
        return Ok(None);
    }
    let Some(body) = vj_sim::netlist::enclosing_instance_body(proc_sym) else {
        return Ok(None);
    };
    let Some(global) =
        vj_sim::sva::global_clock::global_clocking_of(&body, trees).map_err(|e| e.0)?
    else {
        return Ok(None);
    };
    let Some(tc) = global
        .block
        .clocking_block_event()
        .and_then(|n| n.as_timing_control())
    else {
        return Err("the global clocking declaration has no event".to_string());
    };
    let clock = vj_sim::sva::sampled::clock_event_of(tc).map_err(|e| e.0)?;
    if clock.iff.is_some() {
        return Err(
            "a global clocking event with an `iff` condition as a procedural `@$global_clock` \
             is not supported"
                .to_string(),
        );
    }
    Ok(Some((clock.signal, clock.edge, None)))
}

/// The samplers of `body`'s clocking blocks (instance `instance`, signal map
/// `signals`) as image data: registered by `vj_exec::clocking`.
pub(crate) fn samplers<'d>(
    body: &Symbol<'d>,
    instance: InstanceId,
    signals: &HashMap<SymbolId, SignalSlot>,
    trees: &[SyntaxTree],
    port_sources: &PortSources,
    mut intern: impl FnMut(&str) -> u32,
) -> Result<Vec<ClockingImage>, LoweringError> {
    let planned = plan(body, instance, signals, port_sources, trees)
        .map_err(|m| LoweringError::unsupported(&m, "clocking block"))?;
    let mut out = Vec::with_capacity(planned.len());
    for (k, p) in planned.into_iter().enumerate() {
        let mut terms = Vec::with_capacity(p.terms.len());
        let mut term_owners = Vec::with_capacity(p.terms.len());
        let prefix = gate_prefix(instance, k);
        let gates = p
            .gates
            .iter()
            .enumerate()
            .map(|(i, (term, _))| {
                (
                    *term,
                    intern(&vj_codegen::covergroup::gate_name(&prefix, i)),
                )
            })
            .collect();
        for (slot, owner, edge, sig) in p.terms {
            term_owners.push(owner);
            terms.push((
                slot,
                match edge {
                    sv_lang::EdgeKind::None => None,
                    sv_lang::EdgeKind::BothEdges => Some(StateEdgeKind::BothEdges),
                    e => Some(to_state_edge_kind(e, &sig)?),
                },
            ));
        }
        out.push(ClockingImage {
            instance,
            terms,
            gates,
            samples: p.samples,
            parts: p.parts,
            skews: p.skews,
            counter: p.counter,
            term_owners,
        });
    }
    Ok(out)
}

/// The gate-function prefix of clocking block `k` of `instance`'s body.
fn gate_prefix(instance: InstanceId, k: usize) -> String {
    format!("vj_ckgate_{}_{k}", instance.0)
}

/// The compile specs of the sampling-event `iff` gates of every clocking block
/// of `bodies` (LRM 9.4.2.3, 14.12): one gate function per condition,
/// evaluated 4-state, named as [`samplers`] interns them.
pub(crate) fn gate_specs<'d>(
    bodies: &[(InstanceId, Symbol<'d>)],
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    trees: &[SyntaxTree],
) -> Result<Vec<CovergroupLoweringSpec<'d>>, LoweringError> {
    let mut out = Vec::new();
    for (id, body) in bodies {
        let signals = &instance_signals[id];
        let planned = plan(body, *id, signals, &PortSources::new(), trees)
            .map_err(|m| LoweringError::unsupported(&m, "clocking block"))?;
        for (k, p) in planned.into_iter().enumerate() {
            if p.gates.is_empty() {
                continue;
            }
            out.push(CovergroupLoweringSpec {
                prefix: gate_prefix(*id, k),
                cg: p.block,
                type_index: 0,
                kernels: Vec::new(),
                refs: Vec::new(),
                signals: signals.clone(),
                gates: p.gates.into_iter().map(|g| g.1).collect(),
                event_values: Vec::new(),
            });
        }
    }
    Ok(out)
}

/// One block as the planner sees it, before its edges are converted.
struct Planned<'d> {
    block: Symbol<'d>,
    /// `(signal slot, the instance owning it, edge, signal)`.
    terms: Vec<(u32, InstanceId, sv_lang::EdgeKind, Symbol<'d>)>,
    /// Each `iff` condition with the index of the event term it guards.
    gates: Vec<(u32, sv_lang::Expression<'d>)>,
    samples: Vec<(u32, u32, u32)>,
    /// The input skew of each sample, as `ClockingImage::skews`.
    skews: Vec<u64>,
    /// The derived source parts of each sample, as `ClockingImage::parts`.
    parts: Vec<Vec<(u32, u32, u32, u32)>>,
    counter: u32,
}

/// An input clock variable's initializer (14.5) as `(slot, signal width, lsb,
/// len)` parts, most significant first: a constant bit- or part-select of a
/// signal, or a concatenation of such. `Ok(empty)` is an expression this does
/// not cover; the caller refuses it by name.
fn derived_parts(
    e: sv_lang::Expression<'_>,
    signals: &HashMap<SymbolId, SignalSlot>,
) -> Result<Vec<(u32, u32, u32, u32)>, String> {
    use sv_lang::kinds::ExpressionKind as K;
    let mut e = e;
    while e.kind() == K::Conversion
        && let Some(o) = e.operand()
    {
        e = o;
    }
    let none = || Ok(Vec::new());
    if e.kind() == K::Concatenation {
        let mut out = Vec::new();
        for o in e.operands() {
            let p = derived_parts(o, signals)?;
            if p.is_empty() {
                return none();
            }
            out.extend(p);
        }
        return Ok(out);
    }
    if vj_sim::symid::is_value_name(e.kind()) {
        let Some(s) = e
            .referenced_symbol()
            .and_then(|s| signals.get(&s.uid()).copied())
        else {
            return none();
        };
        return Ok(vec![(s.slot, s.width, 0, s.width)]);
    }
    if !matches!(e.kind(), K::ElementSelect | K::RangeSelect) {
        return none();
    }
    let Some(base) = e
        .select_value()
        .filter(|b| vj_sim::symid::is_value_name(b.kind()))
    else {
        return none();
    };
    let Some(s) = base
        .referenced_symbol()
        .and_then(|s| signals.get(&s.uid()).copied())
    else {
        return none();
    };
    if matches!(
        s.class,
        vj_codegen::process_lower::SignalSlotClass::Memory { .. }
    ) {
        return none();
    }
    // Bit offset of declared index `idx` inside the base vector.
    let (left, right) = match base.expr_type() {
        Some(t) if t.is_integral() && !t.is_struct() && !t.is_union() => {
            let r = t.bit_vector_range();
            (i64::from(r.left), i64::from(r.right))
        }
        _ => (i64::from(s.width) - 1, 0),
    };
    let off = |x: sv_lang::Expression<'_>| -> Option<u32> {
        let idx = x.constant_value()?.as_i64()?;
        let o = if left >= right {
            idx - right
        } else {
            right - idx
        };
        (0..i64::from(s.width)).contains(&o).then_some(o as u32)
    };
    if e.kind() == K::ElementSelect {
        return match e.selector().and_then(off) {
            Some(o) => Ok(vec![(s.slot, s.width, o, 1)]),
            None => none(),
        };
    }
    let simple = e.range_selection_kind().is_some_and(|k| {
        vj_codegen::expr::classify_range_selection_kind(k)
            == Ok(vj_codegen::expr::RangeSelectionKindClass::Simple)
    });
    match (e.range_left().and_then(off), e.range_right().and_then(off)) {
        (Some(a), Some(b)) if simple => Ok(vec![(s.slot, s.width, a.min(b), a.abs_diff(b) + 1)]),
        _ => none(),
    }
}

/// The input skew of clock variable `v` of `cb` (LRM 14.4) as a
/// `ClockingImage::skews` code: its own skew, else the block's `default input`,
/// else `#1step`; `event_edge` is the clocking event's edge when it is one
/// term. A numeric skew is in the block's time unit, rounded to its
/// precision, as scheduler ticks of exponent `tick`.
fn input_skew(
    cb: &Symbol<'_>,
    v: &Symbol<'_>,
    tick: i32,
    event_edge: Option<sv_lang::EdgeKind>,
) -> Result<u64, String> {
    let mut skew = v.clock_var_input_skew();
    if !skew.has_value() {
        skew = cb.clocking_block_default_input_skew();
    }
    // 14.3: an edge skew (`input posedge d`) names an edge of the clocking
    // event's own signal (the block must be clocked by one simple edge). The
    // sample is the value at the end of the step of the latest such edge: the
    // clocking event's own edge is the event itself (`#0`), the opposite edge
    // the half period earlier ([`SKEW_EDGE_OPP`]).
    if skew.edge != sv_lang::EdgeKind::None {
        if skew.delay.is_some() {
            return Err(format!(
                "clock variable {}'s input skew combines an edge and a delay (LRM 14.4)",
                v.name()
            ));
        }
        return match (event_edge, skew.edge) {
            (Some(e), k @ (sv_lang::EdgeKind::PosEdge | sv_lang::EdgeKind::NegEdge)) => {
                Ok(if e == k { 0 } else { SKEW_EDGE_OPP })
            }
            _ => Err(format!(
                "clock variable {}'s edge input skew needs a clocking event of one `posedge` or \
                 `negedge` of a signal and a `posedge`/`negedge` skew (LRM 14.4)",
                v.name()
            )),
        };
    }
    let Some(tc) = skew.delay.and_then(|n| n.as_timing_control()) else {
        return Ok(SKEW_STEP);
    };
    if tc.kind() != sv_lang::kinds::TimingControlKind::Delay {
        // `#1step` (`OneStepDelayControl`).
        return Ok(SKEW_STEP);
    }
    let expr = tc
        .children()
        .into_iter()
        .find_map(|n| n.as_expression())
        .ok_or_else(|| format!("clock variable {}'s input skew has no value", v.name()))?;
    let cv = expr.constant_value().ok_or_else(|| {
        format!(
            "clock variable {}'s input skew is not a constant (LRM 14.4)",
            v.name()
        )
    })?;
    let value =
        match &cv {
            sv_lang::ConstantValue::Real(f) => *f,
            other => other.as_integer().and_then(|i| i.as_i64()).ok_or_else(|| {
                format!("clock variable {}'s input skew is not a number", v.name())
            })? as f64,
        };
    vj_codegen::timescale::delay_ticks(value, cb, tick).map_err(|e| format!("{e}"))
}

fn plan<'d>(
    body: &Symbol<'d>,
    instance: InstanceId,
    signals: &HashMap<SymbolId, SignalSlot>,
    port_sources: &PortSources,
    trees: &[SyntaxTree],
) -> Result<Vec<Planned<'d>>, String> {
    let mut out = Vec::new();
    for (cb, vars) in vj_sim::state::clocking_blocks(body) {
        let event = cb
            .clocking_block_event()
            .and_then(|n| n.as_timing_control())
            .ok_or_else(|| format!("clocking block {} has no event", cb.name()))?;
        // `@$global_clock` (14.14; a checker's `default clocking
        // @$global_clock`): the event of the global clocking in effect.
        let event = if vj_sim::sva::sampled::is_global_clock_event(event) {
            let scope = vj_sim::netlist::enclosing_instance_body(&cb)
                .ok_or_else(|| format!("clocking block {} is in no instance", cb.name()))?;
            match vj_sim::sva::global_clock::global_clocking_of(&scope, trees).map_err(|e| e.0)? {
                // An enclosing instance's global clocking (`levels_up > 0`): its event
                // signals are this instance's foreign references (`run.rs`).
                Some(g) => g
                    .block
                    .clocking_block_event()
                    .and_then(|n| n.as_timing_control())
                    .ok_or_else(|| "the global clocking declaration has no event".to_string())?,
                None => {
                    return Err(format!(
                        "clocking block {}'s `$global_clock` has no global clocking declaration \
                         in scope (LRM 14.14)",
                        cb.name()
                    ));
                }
            }
        } else {
            event
        };
        // `@(e)` or `@(a or b)`: each member's signal and edge.
        let mut terms = Vec::new();
        // The `iff` guards of the event (9.4.2.3), each with the term it guards: a
        // term that fires counts only while all of its guards hold (14.3).
        let mut guards: Vec<(u32, sv_lang::Expression<'d>)> = Vec::new();
        let members: Vec<sv_lang::TimingControl<'d>> =
            if event.kind() == sv_lang::kinds::TimingControlKind::EventList {
                event
                    .children()
                    .into_iter()
                    .filter_map(|n| n.as_timing_control())
                    .collect()
            } else {
                vec![event]
            };
        for tc in members {
            let event_expr = tc.children().into_iter().find_map(|n| n.as_expression());
            // 17.4: a checker's `default clocking @clock;` whose `clock` kept its
            // `$inferred_clock` default is clocked by the default clocking event
            // of the scope instantiating the checker. Without one the checker's
            // assertions and procedures that need the clock are refused where they
            // are lowered; the block itself then has no event to sample on.
            let (sig_expr, edge) = if event_expr
                .as_ref()
                .is_some_and(vj_sim::process::cfg::is_inferred_clock_call)
            {
                match checker_inferred_clock(&cb, trees)? {
                    // 14.12/16.14.7: a default clocking whose clock is the
                    // instantiation context's, `iff` and all.
                    Some((e, edge, iff)) => {
                        guards.extend(iff.into_iter().map(|g| (terms.len() as u32, g)));
                        (Some(e), edge)
                    }
                    None => {
                        terms.clear();
                        break;
                    }
                }
            } else {
                if tc.kind() == sv_lang::kinds::TimingControlKind::SignalEvent {
                    let n = terms.len() as u32;
                    guards.extend(
                        vj_sim::sva::sampled::clock_event_of(tc)
                            .map_err(|e| e.0)?
                            .iff
                            .into_iter()
                            .map(|g| (n, g)),
                    );
                }
                (event_expr, tc.edge())
            };
            let sig = sig_expr
                .and_then(|e| e.referenced_symbol())
                .ok_or_else(|| format!("clocking block {}'s event is not a signal", cb.name()))?;
            let slot = signals
                .get(&sig.uid())
                .ok_or_else(|| format!("clocking event signal {} has no slot", sig.name()))?;
            // An `iff` guard reads the block's own instance, so a guarded event
            // keeps the port's copy.
            let (owner, slot) = if guards.is_empty() {
                through_ports(port_sources, instance, sig.uid(), slot.slot)
            } else {
                (instance, slot.slot)
            };
            terms.push((slot, owner, edge, sig));
        }
        if terms.is_empty() {
            continue;
        }
        let gates = guards;
        let mut samples = Vec::new();
        let mut skews = Vec::new();
        let mut parts = Vec::new();
        let tick = vj_codegen::timescale::design_tick_exp(&cb);
        let event_edge = (terms.len() == 1).then(|| terms[0].2);
        for v in vars {
            let init = v.initializer();
            let dst = signals[&v.uid()];
            let (src, derived) = match init.filter(|e| vj_sim::symid::is_value_name(e.kind())) {
                Some(e) => (
                    e.referenced_symbol()
                        .and_then(|s| signals.get(&s.uid()).copied())
                        .map(|s| (s.slot, s.width)),
                    Vec::new(),
                ),
                None => {
                    // 14.5: `input x = a[3:0]` / `input y = {a, b[2:1]}`.
                    let ps = init.map(|e| derived_parts(e, signals)).transpose()?;
                    match ps.filter(|p| !p.is_empty()) {
                        Some(ps) => (Some((ps[0].0, dst.width)), ps),
                        None => (None, Vec::new()),
                    }
                }
            };
            let src = src.ok_or_else(|| {
                format!(
                    "clock variable {} is not bound to a signal, a constant select of one or a \
                     concatenation of those (only `input name`, `input name = signal`, \
                     `= sig[i]`, `= sig[a:b]` and `= {{..}}` are supported)",
                    v.name()
                )
            })?;
            samples.push((src.0, dst.slot, src.1));
            parts.push(derived);
            skews.push(input_skew(&cb, &v, tick, event_edge)?);
        }
        out.push(Planned {
            block: cb,
            terms,
            gates,
            samples,
            parts,
            skews,
            counter: signals[&cb.uid()].slot,
        });
    }
    Ok(out)
}