vj-sim 0.3.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
Documentation
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
//! `force`/`release` (LRM 1800-2023 §10.6.2): each engine's table of forced
//! cells ([`ForceTable`], owned by its `VcState`), applied inside the one
//! write primitive (`write::commit_write_at`) so that every writer -- a
//! blocking or nonblocking assignment, a continuous assignment, a port
//! connection -- is overridden the same way.
//!
//! A forced cell keeps its forced bits whatever is written to it; the rest
//! of a write still lands (a `force` of a net's bit-select forces only those
//! bits). Every write is also remembered as the cell's *driven* value, so a
//! released net (or a variable with a continuous driver) goes back to what
//! its drivers now say, while any other released variable keeps the value
//! it has until its next assignment.
//!
//! A procedural `assign` (§10.6.1) is a second, lower layer of the same
//! mechanism: it overrides every procedural write to the variable, and a
//! `force` overrides it in turn (§10.6.2). Releasing a `force` while an
//! `assign` is still active brings the assigned value back; a `deassign`
//! under an active `force` changes nothing visible until the `release`, and
//! the variable then keeps the value it had.

use std::collections::HashMap;

use super::{FourStateValue, StateCellId};

/// A `force`/`assign` statement in one instance: `(instance handle, source
/// offset)` -- two instances of a module share their statements' offsets.
pub type Site = (u64, u64);

/// The bits one `force` (or one procedural `assign`) layer holds.
struct Layer {
    /// Bits it holds, LSB first, one bit per value bit.
    mask: Vec<u64>,
    /// Its value (only its `mask` bits matter).
    value: FourStateValue,
    /// The statements whose drivers keep re-applying it while it holds.
    sites: Vec<Site>,
}

impl Layer {
    fn new(width_words: usize, value: FourStateValue) -> Self {
        Layer {
            mask: vec![0; width_words],
            value,
            sites: Vec::new(),
        }
    }

    fn is_empty(&self) -> bool {
        self.mask.iter().all(|&m| m == 0)
    }
}

struct Forced {
    /// The last value the design itself wrote.
    driven: FourStateValue,
    /// Released, the cell goes back to `driven` (a net, or a variable with
    /// a continuous driver).
    restores: bool,
    /// A procedural `assign` (§10.6.1).
    assign: Option<Layer>,
    /// A `force` (§10.6.2), over the `assign`.
    force: Option<Layer>,
}

impl Forced {
    /// What the cell reads as: the driven value under the `assign`, under
    /// the `force`.
    fn visible(&self) -> FourStateValue {
        let mut v = self.driven.clone();
        for layer in [&self.assign, &self.force].into_iter().flatten() {
            v = merge(&v, &layer.value, &layer.mask);
        }
        v
    }
}

/// One engine's forced and procedurally assigned cells.
#[derive(Default)]
pub struct ForceTable {
    forced: HashMap<StateCellId, Forced>,
    /// Forced rows of unpacked-array cells (VPI `vpi_put_value` with
    /// `vpiForceFlag` on an element), keyed by the memory's cell and the
    /// row's word offset in the wide planes. Kept apart from `forced`: a
    /// whole-memory write is a row-by-row write, each filtered by its row.
    rows: HashMap<(StateCellId, u32), Forced>,
    /// Statement sites currently in effect.
    active_sites: HashMap<Site, usize>,
    /// Set while a `force`/`assign` itself writes its cell.
    bypass: bool,
}

impl ForceTable {
    /// The value a write of `new` to `cell` actually stores: `new` with the
    /// cell's assigned and forced bits, if it has any (see the module doc).
    pub(crate) fn filter(&mut self, cell: StateCellId, new: FourStateValue) -> FourStateValue {
        if self.bypass {
            return new;
        }
        match self.forced.get_mut(&cell) {
            Some(e) => {
                e.driven = new;
                e.visible()
            }
            None => new,
        }
    }

    /// [`Self::filter`] for a write of the memory row at word offset `at`.
    pub(crate) fn filter_row(
        &mut self,
        cell: StateCellId,
        at: u32,
        new: FourStateValue,
    ) -> FourStateValue {
        if self.bypass {
            return new;
        }
        match self.rows.get_mut(&(cell, at)) {
            Some(e) => {
                e.driven = new;
                e.visible()
            }
            None => new,
        }
    }

    /// Whether `cell` is forced or procedurally assigned (the write path
    /// filters exactly these cells).
    pub(crate) fn contains(&self, cell: StateCellId) -> bool {
        self.forced.contains_key(&cell)
    }

    /// The last value the design itself wrote to the forced `cell`
    /// (`$countdrivers` counts what the drivers say, not the forced value).
    pub(crate) fn driven_value(&self, cell: StateCellId) -> Option<FourStateValue> {
        self.forced.get(&cell).map(|e| e.driven.clone())
    }

    /// Whether no cell is forced (the write path's fast check).
    pub(crate) fn is_empty(&self) -> bool {
        self.forced.is_empty() && self.rows.is_empty()
    }

    /// Forces (`procedural`: procedurally assigns) the `mask` bits of `cell`
    /// to those of `value` (both full-width), on behalf of the statement at
    /// `site`; `current` is the cell's value now. Returns the value to write,
    /// with [`Self::set_bypass`] on.
    #[allow(clippy::too_many_arguments)]
    pub fn force(
        &mut self,
        cell: StateCellId,
        value: FourStateValue,
        mask: Vec<u64>,
        restores: bool,
        site: Site,
        current: FourStateValue,
        procedural: bool,
    ) -> FourStateValue {
        let e = self.forced.entry(cell).or_insert_with(|| Forced {
            driven: current,
            restores,
            assign: None,
            force: None,
        });
        apply_force(e, &mut self.active_sites, value, mask, site, procedural)
    }

    /// [`Self::force`] for the memory row of `cell` at word offset `at`.
    #[allow(clippy::too_many_arguments)]
    pub fn force_row(
        &mut self,
        cell: StateCellId,
        at: u32,
        value: FourStateValue,
        mask: Vec<u64>,
        restores: bool,
        site: Site,
        current: FourStateValue,
        procedural: bool,
    ) -> FourStateValue {
        let e = self.rows.entry((cell, at)).or_insert_with(|| Forced {
            driven: current,
            restores,
            assign: None,
            force: None,
        });
        apply_force(e, &mut self.active_sites, value, mask, site, procedural)
    }

    /// Releases (`procedural`: deassigns) the `mask` bits of `cell`. Returns
    /// the value the cell now reads as when that changes it: a released net
    /// (or continuously driven variable) goes back to its driven value, and
    /// a variable whose `force` ends while an `assign` still holds takes the
    /// assigned value. `None` otherwise: a released or deassigned variable
    /// keeps its value, and a cell with nothing to release is untouched.
    pub fn release(
        &mut self,
        cell: StateCellId,
        mask: &[u64],
        procedural: bool,
    ) -> Option<FourStateValue> {
        let e = self.forced.get_mut(&cell)?;
        let out = apply_release(e, &mut self.active_sites, mask, procedural);
        if e.assign.is_none() && e.force.is_none() {
            self.forced.remove(&cell);
        }
        out
    }

    /// [`Self::release`] for the memory row of `cell` at word offset `at`.
    pub fn release_row(
        &mut self,
        cell: StateCellId,
        at: u32,
        mask: &[u64],
        procedural: bool,
    ) -> Option<FourStateValue> {
        let e = self.rows.get_mut(&(cell, at))?;
        let out = apply_release(e, &mut self.active_sites, mask, procedural);
        if e.assign.is_none() && e.force.is_none() {
            self.rows.remove(&(cell, at));
        }
        out
    }

    /// Whether the `force` statement at `site` is still in effect (its
    /// driver re-forces the target when an operand changes).
    pub fn site_active(&self, site: Site) -> bool {
        self.active_sites.contains_key(&site)
    }

    /// Turns forcing off (a `force` writing its own cell) or back on.
    pub fn set_bypass(&mut self, on: bool) {
        self.bypass = on;
    }
}

/// Adds a `force` (`procedural`: `assign`) layer of `mask` bits of `value` to
/// `e`; returns what the entry now reads as.
fn apply_force(
    e: &mut Forced,
    active_sites: &mut HashMap<Site, usize>,
    value: FourStateValue,
    mask: Vec<u64>,
    site: Site,
    procedural: bool,
) -> FourStateValue {
    let slot = if procedural {
        &mut e.assign
    } else {
        &mut e.force
    };
    let layer = slot.get_or_insert_with(|| Layer::new(mask.len(), value.clone()));
    layer.value = merge(&layer.value, &value, &mask);
    for (m, n) in layer.mask.iter_mut().zip(&mask) {
        *m |= n;
    }
    if !layer.sites.contains(&site) {
        layer.sites.push(site);
        *active_sites.entry(site).or_insert(0) += 1;
    }
    e.visible()
}

/// Releases the `mask` bits of `e`'s `force` (`procedural`: `assign`) layer;
/// the value it now reads as when that changed it (see
/// [`ForceTable::release`]).
fn apply_release(
    e: &mut Forced,
    active_sites: &mut HashMap<Site, usize>,
    mask: &[u64],
    procedural: bool,
) -> Option<FourStateValue> {
    let before = e.visible();
    let slot = if procedural {
        &mut e.assign
    } else {
        &mut e.force
    };
    let layer = slot.as_mut()?;
    for (m, r) in layer.mask.iter_mut().zip(mask) {
        *m &= !r;
    }
    let mut freed = Vec::new();
    if layer.is_empty() {
        freed = std::mem::take(&mut layer.sites);
        *slot = None;
    }
    for site in freed {
        if let Some(n) = active_sites.get_mut(&site) {
            *n -= 1;
            if *n == 0 {
                active_sites.remove(&site);
            }
        }
    }
    // A variable that nothing drives continuously keeps what it reads as
    // now for the bits no layer holds any more (until its next write).
    if !e.restores {
        e.driven = before.clone();
    }
    let after = e.visible();
    (!same(&after, &before)).then_some(after)
}

/// Whether two values hold the same bits.
fn same(a: &FourStateValue, b: &FourStateValue) -> bool {
    match (a, b) {
        (FourStateValue::Narrow(x), FourStateValue::Narrow(y)) => x == y,
        (
            FourStateValue::Wide { aval: xa, bval: xb },
            FourStateValue::Wide { aval: ya, bval: yb },
        ) => xa == ya && xb == yb,
        _ => false,
    }
}

/// `base` with the bits set in `mask` taken from `forced`.
fn merge(base: &FourStateValue, forced: &FourStateValue, mask: &[u64]) -> FourStateValue {
    match (base, forced) {
        (FourStateValue::Narrow(b), FourStateValue::Narrow(v)) => {
            let m = u128::from(mask.first().copied().unwrap_or(0));
            let m = m | (m << 64);
            FourStateValue::Narrow((b & !m) | (v & m))
        }
        (
            FourStateValue::Wide { aval: ba, bval: bb },
            FourStateValue::Wide { aval: fa, bval: fb },
        ) => {
            let pick = |b: &[u64], f: &[u64]| -> Vec<u64> {
                b.iter()
                    .enumerate()
                    .map(|(i, &w)| {
                        let m = mask.get(i).copied().unwrap_or(0);
                        (w & !m) | (f.get(i).copied().unwrap_or(0) & m)
                    })
                    .collect()
            };
            FourStateValue::Wide {
                aval: pick(ba, fa),
                bval: pick(bb, fb),
            }
        }
        _ => base.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn forced_bits_win_and_a_released_net_returns_to_its_driven_value() {
        let mut t = ForceTable::default();
        let cell = StateCellId(3);
        let now = FourStateValue::Narrow(0x5);
        let written = t.force(
            cell,
            FourStateValue::Narrow(0xA0),
            vec![0xF0],
            true,
            (9, 7),
            now,
            false,
        );
        assert!(matches!(written, FourStateValue::Narrow(0xA5)));
        assert!(t.site_active((9, 7)));
        assert!(
            !t.site_active((8, 7)),
            "another instance's statement is not in effect"
        );
        // A driver writes 0x33: the low nibble lands, the high stays forced.
        assert!(matches!(
            t.filter(cell, FourStateValue::Narrow(0x33)),
            FourStateValue::Narrow(0xA3)
        ));
        assert!(matches!(
            t.release(cell, &[0xF0], false),
            Some(FourStateValue::Narrow(0x33))
        ));
        assert!(!t.site_active((9, 7)));
        assert!(matches!(
            t.filter(cell, FourStateValue::Narrow(0x44)),
            FourStateValue::Narrow(0x44)
        ));
    }

    #[test]
    fn a_released_variable_keeps_its_value() {
        let mut t = ForceTable::default();
        let cell = StateCellId(4);
        t.force(
            cell,
            FourStateValue::Narrow(9),
            vec![0xF],
            false,
            (1, 1),
            FourStateValue::Narrow(2),
            false,
        );
        assert!(matches!(
            t.filter(cell, FourStateValue::Narrow(7)),
            FourStateValue::Narrow(9)
        ));
        assert!(t.release(cell, &[0xF], false).is_none());
        // It keeps 9 until its next write.
        assert!(matches!(
            t.filter(cell, FourStateValue::Narrow(7)),
            FourStateValue::Narrow(7)
        ));
    }

    /// §10.6.2: `force` overrides a procedural `assign`; releasing it brings
    /// the assigned value back, and a `deassign` under the `force` changes
    /// nothing visible until the `release`, after which the variable keeps
    /// the value it had.
    #[test]
    fn force_overrides_assign_and_release_restores_it() {
        let mut t = ForceTable::default();
        let cell = StateCellId(5);
        let n = |v: u128| FourStateValue::Narrow(v);
        let assign = (1, 10);
        let force = (1, 20);
        assert!(matches!(
            t.force(cell, n(3), vec![0xF], false, assign, n(1), true),
            FourStateValue::Narrow(3)
        ));
        assert!(
            matches!(t.filter(cell, n(8)), FourStateValue::Narrow(3)),
            "assign beats writes"
        );
        assert!(matches!(
            t.force(cell, n(5), vec![0xF], false, force, n(3), false),
            FourStateValue::Narrow(5)
        ));
        // The assign's driver re-applies a new value: still under the force.
        assert!(matches!(
            t.force(cell, n(6), vec![0xF], false, assign, n(5), true),
            FourStateValue::Narrow(5)
        ));
        assert!(
            matches!(
                t.release(cell, &[0xF], false),
                Some(FourStateValue::Narrow(6))
            ),
            "the assign shows through"
        );
        assert!(t.site_active(assign) && !t.site_active(force));
        // Force again, then deassign under it: nothing visible changes.
        t.force(cell, n(9), vec![0xF], false, force, n(6), false);
        assert!(t.release(cell, &[0xF], true).is_none());
        assert!(t.release(cell, &[0xF], false).is_none(), "keeps 9");
        assert!(
            matches!(t.filter(cell, n(2)), FourStateValue::Narrow(2)),
            "nothing holds it now"
        );
    }
}