prjunnamed_netlist/
design.rs

1use std::fmt::Display;
2use std::ops::{Deref, Range};
3use std::cell::{Ref, RefCell};
4use std::borrow::Cow;
5use std::hash::Hash;
6use std::collections::{btree_map, BTreeMap, BTreeSet, HashMap};
7use std::rc::Rc;
8use std::sync::Arc;
9
10use crate::{MetaItem, MetaStringRef, MetaItemRef};
11use crate::{
12    cell::CellRepr, AssignCell, Cell, ControlNet, FlipFlop, Instance, IoBuffer, IoNet, IoValue, MatchCell, Memory, Net,
13    Target, TargetCell, TargetCellPurity, TargetPrototype, Trit, Value,
14};
15use crate::metadata::{MetadataStore, MetaStringIndex, MetaItemIndex};
16use crate::smt::{SmtEngine, SmtBuilder};
17
18/// Sea of [`Cell`]s.
19#[derive(Debug, Clone)]
20pub struct Design {
21    ios: BTreeMap<String, Range<u32>>,
22    cells: Vec<AnnotatedCell>,
23    changes: RefCell<ChangeQueue>,
24    metadata: RefCell<MetadataStore>,
25    target: Option<Arc<dyn Target>>,
26}
27
28#[derive(Debug, Clone, Default)]
29struct ChangeQueue {
30    next_io: u32,
31    added_ios: BTreeMap<String, Range<u32>>,
32    added_cells: Vec<AnnotatedCell>,
33    cell_cache: HashMap<AnnotatedCell, Value>,
34    cell_metadata: MetaItemIndex,
35    appended_metadata: BTreeMap<usize, Vec<MetaItemIndex>>,
36    replaced_cells: BTreeMap<usize, AnnotatedCell>,
37    unalived_cells: BTreeSet<usize>,
38    replaced_nets: BTreeMap<Net, Net>,
39}
40
41impl Design {
42    pub fn new() -> Design {
43        Self::with_target(None)
44    }
45
46    pub fn with_target(target: Option<Arc<dyn Target>>) -> Design {
47        Design {
48            ios: BTreeMap::new(),
49            cells: vec![],
50            changes: RefCell::new(ChangeQueue::default()),
51            metadata: RefCell::new(MetadataStore::new()),
52            target,
53        }
54    }
55
56    pub fn add_io(&self, name: impl Into<String>, width: usize) -> IoValue {
57        let mut changes = self.changes.borrow_mut();
58        let name = name.into();
59        let width = width as u32;
60        let range = changes.next_io..(changes.next_io + width);
61        changes.next_io += width;
62        if self.ios.contains_key(&name) {
63            panic!("duplicate IO port {name}");
64        }
65        match changes.added_ios.entry(name) {
66            btree_map::Entry::Occupied(entry) => {
67                panic!("duplicate IO port {}", entry.key());
68            }
69            btree_map::Entry::Vacant(entry) => {
70                entry.insert(range.clone());
71            }
72        }
73        IoValue::from_range(range)
74    }
75
76    pub fn get_io(&self, name: impl AsRef<str>) -> Option<IoValue> {
77        self.ios.get(name.as_ref()).map(|range| IoValue::from_range(range.clone()))
78    }
79
80    pub fn find_io(&self, io_net: IoNet) -> Option<(&str, usize)> {
81        for (name, range) in self.ios.iter() {
82            if range.contains(&io_net.index) {
83                return Some((name.as_str(), (io_net.index - range.start) as usize));
84            }
85        }
86        None
87    }
88
89    pub fn iter_ios(&self) -> impl Iterator<Item = (&str, IoValue)> {
90        self.ios.iter().map(|(name, range)| (name.as_str(), IoValue::from_range(range.clone())))
91    }
92
93    pub(crate) fn add_cell_with_metadata_index(&self, cell: Cell, metadata: MetaItemIndex) -> Value {
94        cell.validate(self);
95        let cell_with_meta = AnnotatedCell { repr: cell.clone().into(), meta: metadata };
96        let mut changes = self.changes.borrow_mut();
97        if let Some(value) = changes.cell_cache.get(&cell_with_meta) {
98            value.clone()
99        } else {
100            let index = self.cells.len() + changes.added_cells.len();
101            let output_len = cell.output_len();
102            let output = Value::from_cell_range(index, output_len);
103            if !cell.has_effects(self) {
104                changes.cell_cache.insert(cell_with_meta.clone(), output.clone());
105            }
106            changes.added_cells.push(cell_with_meta);
107            for _ in 0..output_len.saturating_sub(1) {
108                changes.added_cells.push(CellRepr::Skip(index.try_into().expect("cell index too large")).into())
109            }
110            output
111        }
112    }
113
114    pub fn add_cell_with_metadata_ref(&self, cell: Cell, metadata: MetaItemRef) -> Value {
115        self.add_cell_with_metadata_index(cell, metadata.index())
116    }
117
118    pub fn add_cell_with_metadata(&self, cell: Cell, metadata: &MetaItem) -> Value {
119        metadata.validate();
120        let metadata = self.metadata.borrow_mut().add_item(metadata);
121        self.add_cell_with_metadata_index(cell, metadata)
122    }
123
124    pub fn use_metadata(&self, item: MetaItemRef) -> WithMetadataGuard<'_> {
125        let mut changes = self.changes.borrow_mut();
126        let guard = WithMetadataGuard { design: self, restore: changes.cell_metadata };
127        changes.cell_metadata = item.index();
128        guard
129    }
130
131    pub fn use_metadata_from(&self, cell_refs: &[CellRef]) -> WithMetadataGuard<'_> {
132        let item = MetaItemRef::from_merge(self, cell_refs.iter().map(CellRef::metadata));
133        self.use_metadata(item)
134    }
135
136    pub fn get_use_metadata(&self) -> MetaItemRef<'_> {
137        let changes = self.changes.borrow();
138        self.ref_metadata_item(changes.cell_metadata)
139    }
140
141    pub fn add_cell(&self, cell: Cell) -> Value {
142        let metadata = self.changes.borrow().cell_metadata;
143        self.add_cell_with_metadata_index(cell, metadata)
144    }
145
146    pub fn add_void(&self, width: usize) -> Value {
147        let mut changes = self.changes.borrow_mut();
148        let index = self.cells.len() + changes.added_cells.len();
149        for _ in 0..width {
150            changes.added_cells.push(CellRepr::Void.into());
151        }
152        Value::from_cell_range(index, width)
153    }
154
155    #[inline]
156    pub fn find_cell(&self, net: Net) -> Result<(CellRef<'_>, usize), Trit> {
157        let index = net.as_cell_index()?;
158        match self.cells[index].repr {
159            CellRepr::Void => panic!("located a void cell %{index} in design"),
160            CellRepr::Skip(start) => Ok((CellRef { design: self, index: start as usize }, index - start as usize)),
161            _ => Ok((CellRef { design: self, index }, 0)),
162        }
163    }
164
165    pub fn map_net_new(&self, net: impl Into<Net>) -> Net {
166        let changes = self.changes.borrow();
167        let mut net = net.into();
168        while let Some(new_net) = changes.replaced_nets.get(&net) {
169            net = *new_net;
170        }
171        net
172    }
173
174    pub fn find_new_cell(&self, net: Net) -> Result<(Cow<'_, Cell>, MetaItemRef<'_>, usize), Trit> {
175        let net = self.map_net_new(net);
176        let index = net.as_cell_index()?;
177        let changes = self.changes.borrow();
178        let (mut cell, mut meta, index, bit) = if index < self.cells.len() {
179            let (index, bit) = match self.cells[index].repr {
180                CellRepr::Void => panic!("located a void cell %{index} in design"),
181                CellRepr::Skip(start) => (start as usize, index - start as usize),
182                _ => (index, 0),
183            };
184            (self.cells[index].get(), self.cells[index].meta, index, bit)
185        } else {
186            let (index, bit) = match changes.added_cells[index - self.cells.len()].repr {
187                CellRepr::Void => panic!("located a void cell %{index} in change queue"),
188                CellRepr::Skip(start) => (start as usize, index - start as usize),
189                _ => (index, 0),
190            };
191            let acell = &changes.added_cells[index - self.cells.len()];
192            (Cow::Owned(acell.get().into_owned()), acell.meta, index, bit)
193        };
194        if changes.unalived_cells.contains(&index) {
195            panic!("cell %{index} has been unalived");
196        }
197        if let Some(new_cell) = changes.replaced_cells.get(&index) {
198            cell = Cow::Owned(new_cell.get().into_owned());
199            meta = new_cell.meta;
200        }
201        let mut meta = self.ref_metadata_item(meta);
202        if let Some(extra_meta) = changes.appended_metadata.get(&index) {
203            meta = MetaItemRef::from_iter(
204                self,
205                meta.iter().chain(extra_meta.iter().flat_map(|&index| self.ref_metadata_item(index).iter())),
206            );
207        }
208        Ok((cell, meta, bit))
209    }
210
211    pub fn append_metadata_by_net(&self, net: Net, metadata: MetaItemRef<'_>) {
212        let net = self.map_net_new(net);
213        let Ok(index) = net.as_cell_index() else { return };
214        let mut changes = self.changes.borrow_mut();
215        let index = if index < self.cells.len() {
216            match self.cells[index].repr {
217                CellRepr::Void => panic!("located a void cell %{index} in design"),
218                CellRepr::Skip(start) => start as usize,
219                _ => index,
220            }
221        } else {
222            match changes.added_cells[index - self.cells.len()].repr {
223                CellRepr::Void => panic!("located a void cell %{index} in change queue"),
224                CellRepr::Skip(start) => start as usize,
225                _ => index,
226            }
227        };
228        changes.appended_metadata.entry(index).or_default().push(metadata.index())
229    }
230
231    pub fn iter_cells(&self) -> CellIter<'_> {
232        CellIter { design: self, index: 0 }
233    }
234
235    pub(crate) fn is_valid_cell_index(&self, index: usize) -> bool {
236        index < self.cells.len()
237    }
238
239    pub(crate) fn metadata(&self) -> Ref<'_, MetadataStore> {
240        self.metadata.borrow()
241    }
242
243    pub fn add_metadata_string(&self, string: &str) -> MetaStringRef<'_> {
244        let index = self.metadata.borrow_mut().add_string(string);
245        self.metadata.borrow().ref_string(self, index)
246    }
247
248    pub(crate) fn ref_metadata_string(&self, index: MetaStringIndex) -> MetaStringRef<'_> {
249        self.metadata.borrow().ref_string(self, index)
250    }
251
252    pub fn add_metadata_item(&self, item: &MetaItem) -> MetaItemRef<'_> {
253        item.validate();
254        let index = self.metadata.borrow_mut().add_item(item);
255        self.metadata.borrow().ref_item(self, index)
256    }
257
258    pub(crate) fn ref_metadata_item(&self, index: MetaItemIndex) -> MetaItemRef<'_> {
259        self.metadata.borrow().ref_item(self, index)
260    }
261
262    pub fn replace_net(&self, from_net: impl Into<Net>, to_net: impl Into<Net>) {
263        let (from_net, to_net) = (from_net.into(), to_net.into());
264        if from_net != to_net {
265            let mut changes = self.changes.borrow_mut();
266            assert_eq!(changes.replaced_nets.insert(from_net, to_net), None);
267        }
268    }
269
270    pub fn replace_value<'a, 'b>(&self, from_value: impl Into<Cow<'a, Value>>, to_value: impl Into<Cow<'b, Value>>) {
271        let (from_value, to_value) = (from_value.into(), to_value.into());
272        assert_eq!(from_value.len(), to_value.len());
273        for (from_net, to_net) in from_value.iter().zip(to_value.iter()) {
274            self.replace_net(from_net, to_net);
275        }
276    }
277
278    pub fn map_net(&self, net: impl Into<Net>) -> Net {
279        let changes = self.changes.borrow();
280        let net = net.into();
281        let mut mapped_net = net;
282        while let Some(new_net) = changes.replaced_nets.get(&mapped_net) {
283            mapped_net = *new_net;
284        }
285        // Assume the caller might want to locate the cell behind the net.
286        match mapped_net.as_cell_index() {
287            Ok(index) if index >= self.cells.len() => net,
288            _ => mapped_net,
289        }
290    }
291
292    pub fn map_value(&self, value: impl Into<Value>) -> Value {
293        let mut value = value.into();
294        value.visit_mut(|net| *net = self.map_net(*net));
295        value
296    }
297
298    pub fn is_empty(&self) -> bool {
299        self.ios.is_empty() && self.cells.is_empty() && !self.is_changed() && self.target.is_none()
300    }
301
302    pub fn is_changed(&self) -> bool {
303        let changes = self.changes.borrow();
304        !changes.added_ios.is_empty()
305            || !changes.added_cells.is_empty()
306            || !changes.replaced_cells.is_empty()
307            || !changes.unalived_cells.is_empty()
308            || !changes.replaced_nets.is_empty()
309    }
310
311    pub fn verify<SMT: SmtEngine>(&self, engine: SMT) -> Result<(), SMT::Error> {
312        let changes = self.changes.borrow();
313        let locate_cell = |net: Net| {
314            net.as_cell_index().map(|index| {
315                if index < self.cells.len() {
316                    &self.cells[index].repr
317                } else {
318                    &changes.added_cells[index - self.cells.len()].repr
319                }
320            })
321        };
322        let get_cell = |net: Net| match locate_cell(net) {
323            Ok(CellRepr::Skip(index)) => locate_cell(Net::from_cell_index(*index as usize)),
324            result => result,
325        };
326
327        let mut smt = SmtBuilder::new(self, engine);
328        for (index, cell) in self.cells.iter().chain(changes.added_cells.iter()).enumerate() {
329            if matches!(cell.repr, CellRepr::Skip(_) | CellRepr::Void) || cell.output_len() == 0 {
330            } else if let Some(new_cell) = changes.replaced_cells.get(&index) {
331                smt.replace_cell(&Value::from_cell_range(index, cell.output_len()), &cell.get(), &new_cell.get())?;
332            } else {
333                smt.add_cell(&Value::from_cell_range(index, cell.output_len()), &cell.get())?;
334            }
335        }
336        for (&net, &new_net) in changes.replaced_nets.iter() {
337            if let Ok(cell) = get_cell(net) {
338                if matches!(cell, CellRepr::Void) {
339                    smt.replace_void_net(net, new_net)?;
340                    continue;
341                } else if matches!(&*cell.get(), Cell::Dff(_))
342                    && let Ok(new_cell) = get_cell(new_net)
343                    && matches!(&*new_cell.get(), Cell::Dff(_))
344                {
345                    smt.replace_dff_net(net, new_net)?;
346                }
347            }
348            smt.replace_net(net, new_net)?;
349        }
350        if let Some(example) = smt.check()? {
351            let mut message = "verification failed!\n".to_string();
352            message.push_str(&format!("\ndesign:\n{self:#}"));
353            message.push_str("\ncounterexample:\n");
354            for (index, cell) in self.cells.iter().chain(changes.added_cells.iter()).enumerate() {
355                if matches!(cell.repr, CellRepr::Skip(_) | CellRepr::Void) || cell.output_len() == 0 {
356                } else {
357                    let output = Value::from_cell_range(index, cell.output_len());
358                    let (was, now) = (example.get_past_value(&output), example.get_value(&output));
359                    message.push_str(&match (was, now) {
360                        (Some(was), Some(now)) => format!("{} = {} -> {}\n", self.display_value(&output), was, now),
361                        (None, Some(now)) => format!("{} = {}\n", self.display_value(&output), now),
362                        (Some(was), None) => format!("{} = {} -> ?\n", self.display_value(&output), was),
363                        (None, None) => unreachable!(),
364                    });
365                }
366            }
367            for (&net, &new_net) in changes.replaced_nets.iter() {
368                if example.get_value(net) != example.get_value(new_net) {
369                    message.push_str(&format!(
370                        "\npossible cause: replacing net {} with net {} is not valid",
371                        self.display_net(net),
372                        self.display_net(new_net)
373                    ));
374                }
375            }
376            panic!("{message}");
377        }
378        Ok(())
379    }
380
381    pub fn apply(&mut self) -> bool {
382        #[cfg(feature = "verify")]
383        self.verify(crate::EasySmtEngine::z3().unwrap()).unwrap();
384
385        let mut changes = std::mem::take(self.changes.get_mut());
386        self.changes.get_mut().next_io = changes.next_io;
387
388        let mut did_change = !changes.added_ios.is_empty() || !changes.added_cells.is_empty();
389        self.ios.extend(changes.added_ios);
390        self.cells.extend(changes.added_cells);
391        for cell_index in changes.unalived_cells {
392            let output_len = self.cells[cell_index].output_len().max(1);
393            for index in cell_index..cell_index + output_len {
394                self.cells[index] = CellRepr::Void.into();
395            }
396            did_change = true;
397        }
398        for (index, new_cell) in changes.replaced_cells {
399            assert_eq!(self.cells[index].output_len(), new_cell.output_len());
400            self.cells[index] = new_cell;
401            // CellRef::replace() ensures the new cell is different.
402            did_change = true;
403        }
404        for (cell_index, new_items) in changes.appended_metadata {
405            let cell_meta_iter = self.ref_metadata_item(self.cells[cell_index].meta).iter();
406            let new_items_iter = new_items.into_iter().flat_map(|new_item| self.ref_metadata_item(new_item).iter());
407            self.cells[cell_index].meta = MetaItemRef::from_iter(self, cell_meta_iter.chain(new_items_iter)).index();
408        }
409        changes.cell_cache.clear();
410        if !changes.replaced_nets.is_empty() {
411            for cell in self.cells.iter_mut().filter(|cell| !matches!(cell.repr, CellRepr::Skip(_) | CellRepr::Void)) {
412                cell.repr.visit_mut(|net| {
413                    while let Some(new_net) = changes.replaced_nets.get(net) {
414                        if *net != *new_net {
415                            *net = *new_net;
416                            did_change = true;
417                        }
418                    }
419                });
420            }
421            changes.replaced_nets.clear();
422        }
423        did_change
424    }
425
426    pub fn target(&self) -> Option<Arc<dyn Target>> {
427        self.target.as_ref().map(|target| target.clone())
428    }
429
430    pub fn target_prototype(&self, target_cell: &TargetCell) -> &TargetPrototype {
431        self.target
432            .as_ref()
433            .expect("design has no target")
434            .prototype(&target_cell.kind)
435            .expect("target prototype not defined")
436    }
437}
438
439impl Default for Design {
440    fn default() -> Self {
441        Self::new()
442    }
443}
444
445#[derive(Debug, Clone, PartialEq, Eq, Hash)]
446struct AnnotatedCell {
447    repr: CellRepr,
448    meta: MetaItemIndex,
449}
450
451impl Deref for AnnotatedCell {
452    type Target = CellRepr;
453
454    fn deref(&self) -> &Self::Target {
455        &self.repr
456    }
457}
458
459impl From<CellRepr> for AnnotatedCell {
460    fn from(val: CellRepr) -> Self {
461        AnnotatedCell { repr: val, meta: MetaItemIndex::NONE }
462    }
463}
464
465pub struct WithMetadataGuard<'a> {
466    design: &'a Design,
467    restore: MetaItemIndex,
468}
469
470impl Drop for WithMetadataGuard<'_> {
471    fn drop(&mut self) {
472        self.design.changes.borrow_mut().cell_metadata = self.restore;
473    }
474}
475
476#[derive(Clone, Copy)]
477pub struct CellRef<'a> {
478    design: &'a Design,
479    index: usize,
480}
481
482impl PartialEq<CellRef<'_>> for CellRef<'_> {
483    fn eq(&self, other: &CellRef<'_>) -> bool {
484        std::ptr::eq(self.design, other.design) && self.index == other.index
485    }
486}
487
488impl Eq for CellRef<'_> {}
489
490impl PartialOrd<CellRef<'_>> for CellRef<'_> {
491    fn partial_cmp(&self, other: &CellRef<'_>) -> Option<std::cmp::Ordering> {
492        Some(self.cmp(other))
493    }
494}
495
496impl Ord for CellRef<'_> {
497    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
498        match (self.design as *const Design).cmp(&(other.design as *const Design)) {
499            core::cmp::Ordering::Equal => self.index.cmp(&other.index),
500            ord => ord,
501        }
502    }
503}
504
505impl Hash for CellRef<'_> {
506    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
507        self.index.hash(state);
508    }
509}
510
511impl<'a> CellRef<'a> {
512    pub fn get(self) -> Cow<'a, Cell> {
513        self.design.cells[self.index].get()
514    }
515
516    pub fn metadata(&self) -> MetaItemRef<'a> {
517        self.design.metadata.borrow().ref_item(self.design, self.design.cells[self.index].meta)
518    }
519
520    pub fn output_len(&self) -> usize {
521        self.design.cells[self.index].output_len()
522    }
523
524    pub fn output(&self) -> Value {
525        Value::from_cell_range(self.index, self.output_len())
526    }
527
528    pub fn visit(&self, f: impl FnMut(Net)) {
529        self.design.cells[self.index].visit(f)
530    }
531
532    pub fn replace(&self, to_cell: Cell) {
533        if *self.design.cells[self.index].get() != to_cell {
534            to_cell.validate(self.design);
535            let to_cell = AnnotatedCell { repr: to_cell.into(), meta: self.design.cells[self.index].meta };
536            let mut changes = self.design.changes.borrow_mut();
537            assert!(changes.replaced_cells.insert(self.index, to_cell).is_none());
538        }
539    }
540
541    pub fn append_metadata(&self, metadata: MetaItemRef<'a>) {
542        let mut changes = self.design.changes.borrow_mut();
543        changes.appended_metadata.entry(self.index).or_default().push(metadata.index())
544    }
545
546    pub fn unalive(&self) {
547        let mut changes = self.design.changes.borrow_mut();
548        changes.unalived_cells.insert(self.index);
549    }
550
551    /// Returns the same index as the one used by `Display` implementation. There is intentionally no way to retrieve
552    /// a cell by its index.
553    pub fn debug_index(&self) -> usize {
554        self.index
555    }
556
557    pub(crate) fn metadata_index(&self) -> MetaItemIndex {
558        self.design.cells[self.index].meta
559    }
560
561    /// Returns a reference to the underlying [`Design`].
562    pub fn design(self) -> &'a Design {
563        self.design
564    }
565}
566
567pub struct CellIter<'a> {
568    design: &'a Design,
569    index: usize,
570}
571
572impl<'a> Iterator for CellIter<'a> {
573    type Item = CellRef<'a>;
574
575    fn next(&mut self) -> Option<Self::Item> {
576        while matches!(self.design.cells.get(self.index), Some(AnnotatedCell { repr: CellRepr::Void, .. })) {
577            self.index += 1;
578        }
579        if self.index < self.design.cells.len() {
580            let cell_ref = CellRef { design: self.design, index: self.index };
581            self.index += self.design.cells[self.index].output_len().max(1);
582            Some(cell_ref)
583        } else {
584            None
585        }
586    }
587}
588
589macro_rules! builder_fn {
590    () => {};
591
592    ($func:ident( $($arg:ident : $argty:ty),+ ) -> $retty:ty : $cstr:ident $body:tt; $($rest:tt)*) => {
593        pub fn $func(&self, $( $arg: $argty ),+) -> $retty {
594            self.add_cell(Cell::$cstr $body).try_into().unwrap()
595        }
596
597        builder_fn!{ $($rest)* }
598    };
599
600    // For cells with no output value.
601    ($func:ident( $($arg:ident : $argty:ty),+ ) : $cstr:ident $body:tt; $($rest:tt)*) => {
602        pub fn $func(&self, $( $arg: $argty ),+) {
603            self.add_cell(Cell::$cstr $body);
604        }
605
606        builder_fn!{ $($rest)* }
607    };
608}
609
610impl Design {
611    builder_fn! {
612        add_buf(arg: impl Into<Value>) -> Value :
613            Buf(arg.into());
614        add_buf1(arg: impl Into<Net>) -> Net :
615            Buf(arg.into().into());
616        add_not(arg: impl Into<Value>) -> Value :
617            Not(arg.into());
618        add_not1(arg: impl Into<Net>) -> Net :
619            Not(arg.into().into());
620        add_and(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
621            And(arg1.into(), arg2.into());
622        add_and1(arg1: impl Into<Net>, arg2: impl Into<Net>) -> Net :
623            And(arg1.into().into(), arg2.into().into());
624        add_or(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
625            Or(arg1.into(), arg2.into());
626        add_or1(arg1: impl Into<Net>, arg2: impl Into<Net>) -> Net :
627            Or(arg1.into().into(), arg2.into().into());
628        add_xor(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
629            Xor(arg1.into(), arg2.into());
630        add_xor1(arg1: impl Into<Net>, arg2: impl Into<Net>) -> Net :
631            Xor(arg1.into().into(), arg2.into().into());
632        add_adc(arg1: impl Into<Value>, arg2: impl Into<Value>, arg3: impl Into<Net>) -> Value :
633            Adc(arg1.into(), arg2.into(), arg3.into());
634        add_aig(arg1: impl Into<ControlNet>, arg2: impl Into<ControlNet>) -> Net :
635            Aig(arg1.into(), arg2.into());
636
637        add_eq(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Net :
638            Eq(arg1.into(), arg2.into());
639        add_ult(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Net :
640            ULt(arg1.into(), arg2.into());
641        add_slt(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Net :
642            SLt(arg1.into(), arg2.into());
643
644        add_shl(arg1: impl Into<Value>, arg2: impl Into<Value>, stride: u32) -> Value :
645            Shl(arg1.into(), arg2.into(), stride);
646        add_ushr(arg1: impl Into<Value>, arg2: impl Into<Value>, stride: u32) -> Value :
647            UShr(arg1.into(), arg2.into(), stride);
648        add_sshr(arg1: impl Into<Value>, arg2: impl Into<Value>, stride: u32) -> Value :
649            SShr(arg1.into(), arg2.into(), stride);
650        add_xshr(arg1: impl Into<Value>, arg2: impl Into<Value>, stride: u32) -> Value :
651            XShr(arg1.into(), arg2.into(), stride);
652
653        add_mul(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
654            Mul(arg1.into(), arg2.into());
655        add_udiv(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
656            UDiv(arg1.into(), arg2.into());
657        add_umod(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
658            UMod(arg1.into(), arg2.into());
659        add_sdiv_trunc(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
660            SDivTrunc(arg1.into(), arg2.into());
661        add_sdiv_floor(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
662            SDivFloor(arg1.into(), arg2.into());
663        add_smod_trunc(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
664            SModTrunc(arg1.into(), arg2.into());
665        add_smod_floor(arg1: impl Into<Value>, arg2: impl Into<Value>) -> Value :
666            SModFloor(arg1.into(), arg2.into());
667
668        add_match(arg: impl Into<MatchCell>) -> Value :
669            Match(arg.into());
670        add_assign(arg: impl Into<AssignCell>) -> Value :
671            Assign(arg.into());
672        add_dff(arg: impl Into<FlipFlop>) -> Value :
673            Dff(arg.into());
674        add_memory(arg: impl Into<Memory>) -> Value :
675            Memory(arg.into());
676        add_iobuf(arg: impl Into<IoBuffer>) -> Value :
677            IoBuf(arg.into());
678        add_other(arg: impl Into<Instance>) -> Value :
679            Other(arg.into());
680        add_target(arg: impl Into<TargetCell>) -> Value :
681            Target(arg.into());
682
683        add_input(name: impl Into<String>, width: usize) -> Value :
684            Input(name.into(), width);
685        add_input1(name: impl Into<String>) -> Net :
686            Input(name.into(), 1);
687        add_output(name: impl Into<String>, value: impl Into<Value>) :
688            Output(name.into(), value.into());
689        add_name(name: impl Into<String>, value: impl Into<Value>) :
690            Name(name.into(), value.into());
691        add_debug(name: impl Into<String>, value: impl Into<Value>) :
692            Debug(name.into(), value.into());
693    }
694
695    pub fn add_mux(&self, arg1: impl Into<ControlNet>, arg2: impl Into<Value>, arg3: impl Into<Value>) -> Value {
696        match arg1.into() {
697            ControlNet::Pos(net) => self.add_cell(Cell::Mux(net, arg2.into(), arg3.into())),
698            ControlNet::Neg(net) => self.add_cell(Cell::Mux(net, arg3.into(), arg2.into())),
699        }
700    }
701
702    pub fn add_mux1(&self, arg1: impl Into<ControlNet>, arg2: impl Into<Net>, arg3: impl Into<Net>) -> Net {
703        match arg1.into() {
704            ControlNet::Pos(net) => self.add_cell(Cell::Mux(net, arg2.into().into(), arg3.into().into())).unwrap_net(),
705            ControlNet::Neg(net) => self.add_cell(Cell::Mux(net, arg3.into().into(), arg2.into().into())).unwrap_net(),
706        }
707    }
708
709    pub fn add_ne(&self, arg1: impl Into<Value>, arg2: impl Into<Value>) -> Net {
710        let eq = self.add_eq(arg1, arg2);
711        self.add_not1(eq)
712    }
713}
714
715#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
716pub enum TopoSortItem<'a> {
717    Cell(CellRef<'a>),
718    CellBit(CellRef<'a>, usize),
719}
720
721impl Design {
722    pub fn topo_sort(&self) -> Vec<TopoSortItem<'_>> {
723        fn is_splittable(cell: CellRef) -> bool {
724            matches!(
725                &*cell.get(),
726                Cell::Buf(..) | Cell::Not(..) | Cell::And(..) | Cell::Or(..) | Cell::Xor(..) | Cell::Mux(..)
727            )
728        }
729
730        fn is_comb_edge(design: &Design, net: Net) -> bool {
731            if let Ok((cell, _)) = design.find_cell(net) {
732                match &*cell.get() {
733                    Cell::Input(..) | Cell::IoBuf(..) | Cell::Dff(..) | Cell::Other(..) => false,
734                    Cell::Target(target_cell) => design.target_prototype(target_cell).purity == TargetCellPurity::Pure,
735                    _ => true,
736                }
737            } else {
738                false
739            }
740        }
741
742        fn get_deps(item: TopoSortItem) -> Vec<Net> {
743            let mut result = vec![];
744            match item {
745                TopoSortItem::Cell(cell) => {
746                    cell.visit(|net| {
747                        result.push(net);
748                    });
749                }
750                TopoSortItem::CellBit(cell, bit) => match &*cell.get() {
751                    Cell::Buf(val) | Cell::Not(val) => {
752                        result.push(val[bit]);
753                    }
754                    Cell::And(val1, val2) | Cell::Or(val1, val2) | Cell::Xor(val1, val2) => {
755                        result.push(val1[bit]);
756                        result.push(val2[bit]);
757                    }
758                    Cell::Mux(net, val1, val2) => {
759                        result.push(*net);
760                        result.push(val1[bit]);
761                        result.push(val2[bit]);
762                    }
763                    _ => unreachable!(),
764                },
765            }
766            let cell = match item {
767                TopoSortItem::Cell(cell) => cell,
768                TopoSortItem::CellBit(cell, _) => cell,
769            };
770            result.retain(|net| is_comb_edge(cell.design(), *net));
771            result
772        }
773
774        fn get_item_from_net(design: &Design, net: Net) -> Option<TopoSortItem<'_>> {
775            let Ok((cell, bit)) = design.find_cell(net) else {
776                return None;
777            };
778            if is_splittable(cell) { Some(TopoSortItem::CellBit(cell, bit)) } else { Some(TopoSortItem::Cell(cell)) }
779        }
780
781        struct StackEntry<'a> {
782            item: TopoSortItem<'a>,
783            deps: Vec<Net>,
784        }
785
786        let mut result = vec![];
787        let mut visited = BTreeSet::new();
788        for cell in self.iter_cells() {
789            let roots = if is_splittable(cell) {
790                Vec::from_iter((0..cell.output_len()).map(|bit| TopoSortItem::CellBit(cell, bit)))
791            } else {
792                vec![TopoSortItem::Cell(cell)]
793            };
794            for root in roots {
795                let mut stack = vec![StackEntry { item: root, deps: get_deps(root) }];
796                if visited.contains(&root) {
797                    continue;
798                }
799                visited.insert(root);
800                while let Some(top) = stack.last_mut() {
801                    if let Some(net) = top.deps.pop() {
802                        let Some(item) = get_item_from_net(self, net) else { continue };
803                        if visited.contains(&item) {
804                            continue;
805                        }
806                        visited.insert(item);
807                        stack.push(StackEntry { item, deps: get_deps(item) });
808                    } else {
809                        result.push(top.item);
810                        stack.pop();
811                    };
812                }
813            }
814        }
815        result
816    }
817
818    pub fn iter_cells_topo(&self) -> impl DoubleEndedIterator<Item = CellRef<'_>> {
819        fn get_deps(design: &Design, cell: CellRef) -> BTreeSet<usize> {
820            let mut result = BTreeSet::new();
821            cell.visit(|net| {
822                if let Ok((cell, _offset)) = design.find_cell(net) {
823                    result.insert(cell.index);
824                }
825            });
826            result
827        }
828
829        let mut result = vec![];
830        let mut visited = BTreeSet::new();
831        // emit inputs, iobs and stateful cells first, in netlist order
832        for cell in self.iter_cells() {
833            match &*cell.get() {
834                Cell::Input(..) | Cell::IoBuf(..) | Cell::Dff(..) | Cell::Other(..) => {
835                    visited.insert(cell.index);
836                    result.push(cell);
837                }
838                Cell::Target(target_cell) => {
839                    if self.target_prototype(target_cell).purity != TargetCellPurity::Pure {
840                        visited.insert(cell.index);
841                        result.push(cell);
842                    }
843                }
844                _ => (),
845            }
846        }
847        // now emit combinational cells, in topologically-sorted order whenever possible.
848        // we try to emit them in netlist order; however, if we try to emit a cell
849        // that has an input that has not yet been emitted, we push it on a stack,
850        // and go emit the inputs instead.  the cell is put on the "visitted" list
851        // as soon as we start processing it, so cycles will be automatically broken
852        // by considering inputs already on the processing stack as "already emitted".
853        for cell in self.iter_cells() {
854            if matches!(&*cell.get(), Cell::Output(..) | Cell::Name(..) | Cell::Debug(..)) {
855                continue;
856            }
857            if visited.contains(&cell.index) {
858                continue;
859            }
860            visited.insert(cell.index);
861            let mut stack = vec![(cell, get_deps(self, cell))];
862            'outer: while let Some((cell, deps)) = stack.last_mut() {
863                while let Some(dep_index) = deps.pop_first() {
864                    if !visited.contains(&dep_index) {
865                        let cell = CellRef { design: self, index: dep_index };
866                        visited.insert(dep_index);
867                        stack.push((cell, get_deps(self, cell)));
868                        continue 'outer;
869                    }
870                }
871                result.push(*cell);
872                stack.pop();
873            }
874        }
875        // finally, emit outputs, names, and debugs
876        for cell in self.iter_cells() {
877            if visited.contains(&cell.index) {
878                continue;
879            }
880            result.push(cell);
881        }
882        result.into_iter()
883    }
884
885    pub fn compact(&mut self) -> bool {
886        let did_change = self.apply();
887
888        let mut queue = BTreeSet::new();
889        let mut debug = BTreeMap::new();
890        for (index, cell) in self.cells.iter().enumerate() {
891            if matches!(cell.repr, CellRepr::Skip(_) | CellRepr::Void) {
892                continue;
893            }
894            match &*cell.get() {
895                cell if cell.has_effects(self) => {
896                    queue.insert(index);
897                }
898                Cell::Debug(name, value) => {
899                    debug.insert(name.clone(), (value.clone(), cell.meta));
900                }
901                _ => (),
902            }
903        }
904
905        let mut keep = BTreeSet::new();
906        while let Some(index) = queue.pop_first() {
907            keep.insert(index);
908            self.cells[index].visit(|net| {
909                if let Ok((cell_ref, _offset)) = self.find_cell(net)
910                    && !keep.contains(&cell_ref.index)
911                {
912                    queue.insert(cell_ref.index);
913                }
914            });
915        }
916
917        let mut net_map = BTreeMap::new();
918        for (old_index, cell) in std::mem::take(&mut self.cells).into_iter().enumerate() {
919            if keep.contains(&old_index) {
920                let new_index = self.cells.len();
921                for offset in 0..cell.output_len() {
922                    net_map.insert(Net::from_cell_index(old_index + offset), Net::from_cell_index(new_index + offset));
923                }
924                let skip_count = cell.output_len().saturating_sub(1);
925                self.cells.push(cell);
926                for _ in 0..skip_count {
927                    self.cells.push(CellRepr::Skip(new_index as u32).into());
928                }
929            }
930        }
931
932        for cell in self.cells.iter_mut().filter(|cell| !matches!(cell.repr, CellRepr::Skip(_))) {
933            cell.repr.visit_mut(|net| {
934                if net.is_cell() {
935                    *net = net_map[net];
936                }
937            });
938        }
939
940        for (name, (mut value, meta)) in debug {
941            value.visit_mut(|net| {
942                if net.is_cell() {
943                    if let Some(&new_net) = net_map.get(net) {
944                        *net = new_net;
945                    } else {
946                        *net = Net::UNDEF;
947                    }
948                }
949            });
950            self.cells.push(AnnotatedCell { repr: CellRepr::Boxed(Box::new(Cell::Debug(name, value))), meta });
951        }
952
953        did_change
954    }
955
956    pub fn statistics(&self) -> BTreeMap<String, usize> {
957        let result = RefCell::new(BTreeMap::<String, usize>::new());
958        for cell_ref in self.iter_cells() {
959            let simple = |name: &str| {
960                *result.borrow_mut().entry(name.to_string()).or_default() += 1;
961            };
962            let bitwise = |name: &str, amount: usize| {
963                *result.borrow_mut().entry(name.to_string()).or_default() += amount;
964            };
965            let wide = |name: &str, size: usize| {
966                *result.borrow_mut().entry(format!("{name}:{size}")).or_default() += 1;
967            };
968            let custom = |args: std::fmt::Arguments| {
969                *result.borrow_mut().entry(format!("{args}")).or_default() += 1;
970            };
971            match &*cell_ref.get() {
972                Cell::Buf(arg) => bitwise("buf", arg.len()),
973                Cell::Not(arg) => bitwise("not", arg.len()),
974                Cell::And(arg, _) => bitwise("and", arg.len()),
975                Cell::Or(arg, _) => bitwise("or", arg.len()),
976                Cell::Xor(arg, _) => bitwise("xor", arg.len()),
977                Cell::Mux(_, arg, _) => bitwise("mux", arg.len()),
978                Cell::Adc(arg, _, _) => wide("adc", arg.len()),
979                Cell::Aig(_, _) => simple("aig"),
980                Cell::Eq(arg, _) => wide("eq", arg.len()),
981                Cell::ULt(arg, _) => wide("ult", arg.len()),
982                Cell::SLt(arg, _) => wide("slt", arg.len()),
983                Cell::Shl(arg, _, _) => wide("shl", arg.len()),
984                Cell::UShr(arg, _, _) => wide("ushr", arg.len()),
985                Cell::SShr(arg, _, _) => wide("sshr", arg.len()),
986                Cell::XShr(arg, _, _) => wide("xshr", arg.len()),
987                Cell::Mul(arg, _) => wide("mul", arg.len()),
988                Cell::UDiv(arg, _) => wide("udiv", arg.len()),
989                Cell::UMod(arg, _) => wide("umod", arg.len()),
990                Cell::SDivTrunc(arg, _) => wide("sdiv_trunc", arg.len()),
991                Cell::SDivFloor(arg, _) => wide("sdiv_floor", arg.len()),
992                Cell::SModTrunc(arg, _) => wide("smod_trunc", arg.len()),
993                Cell::SModFloor(arg, _) => wide("smod_floor", arg.len()),
994                Cell::Match(_) => custom(format_args!("match")),
995                Cell::Assign(AssignCell { value, .. }) => bitwise("assign", value.len()),
996                Cell::Dff(FlipFlop { data, .. }) => bitwise("dff", data.len()),
997                Cell::Memory(Memory { depth, width, .. }) => custom(format_args!("memory:{depth}:{width}")),
998                Cell::IoBuf(IoBuffer { io, .. }) => bitwise("iobuf", io.len()),
999                Cell::Target(TargetCell { kind, .. }) => custom(format_args!("{kind}")),
1000                Cell::Other(Instance { kind, .. }) => custom(format_args!("{kind}")),
1001                Cell::Input(_, width) => bitwise("input", *width),
1002                Cell::Output(_, value) => bitwise("output", value.len()),
1003                Cell::Name(..) | Cell::Debug(..) => (),
1004            }
1005        }
1006        result.into_inner()
1007    }
1008}
1009
1010// This can't be in `crate::print` because of the privacy violations.
1011impl Display for Design {
1012    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1013        let changes = self.changes.borrow();
1014
1015        let diff = self.is_changed();
1016        let added = "+";
1017        let removed = "-";
1018        let unchanged = " ";
1019        let comment = if !diff { "; " } else { " ; " };
1020
1021        let mut net_names = BTreeMap::new();
1022        for cell_ref in self.iter_cells() {
1023            match &*cell_ref.get() {
1024                Cell::Output(name, value) | Cell::Name(name, value) | Cell::Debug(name, value) => {
1025                    let name = Rc::new(name.clone());
1026                    for (offset, net) in value.iter().enumerate() {
1027                        if net.is_cell() {
1028                            net_names.insert(net, (name.clone(), offset));
1029                        }
1030                    }
1031                }
1032                _ => (),
1033            }
1034        }
1035
1036        if let Some(target) = self.target() {
1037            write!(f, "{}target ", if !diff { "" } else { unchanged })?;
1038            Design::write_string(f, target.name())?;
1039            for (name, value) in target.options() {
1040                write!(f, " ")?;
1041                Design::write_string(f, &name)?;
1042                write!(f, "=")?;
1043                Design::write_string(f, &value)?;
1044            }
1045            writeln!(f)?;
1046        }
1047
1048        for metadata_ref in self.metadata.borrow().iter_items(self) {
1049            if metadata_ref.index() == MetaItemIndex::NONE {
1050                continue;
1051            }
1052            write!(f, "{}", if !diff { "" } else { unchanged })?;
1053            write!(f, "{} = ", metadata_ref.index())?;
1054            let item = metadata_ref.get();
1055            match item {
1056                MetaItem::None => unreachable!(),
1057                MetaItem::Set(items) => {
1058                    write!(f, "{{")?;
1059                    for item in items {
1060                        write!(f, " {}", item.index())?;
1061                    }
1062                    write!(f, " }}")?;
1063                }
1064                MetaItem::Source { file, start, end } => {
1065                    write!(f, "source ")?;
1066                    Design::write_string(f, &file.get())?;
1067                    write!(f, " (#{} #{}) (#{} #{})", start.line, start.column, end.line, end.column)?;
1068                }
1069                MetaItem::NamedScope { name: _, source, parent }
1070                | MetaItem::IndexedScope { index: _, source, parent } => {
1071                    write!(f, "scope ")?;
1072                    match item {
1073                        MetaItem::NamedScope { name, .. } => Design::write_string(f, &name.get())?,
1074                        MetaItem::IndexedScope { index, .. } => write!(f, "#{index}")?,
1075                        _ => unreachable!(),
1076                    }
1077                    if !parent.is_none() {
1078                        write!(f, " in={}", parent.index())?;
1079                    }
1080                    if !source.is_none() {
1081                        write!(f, " src={}", source.index())?;
1082                    }
1083                }
1084                MetaItem::Ident { name, scope } => {
1085                    write!(f, "ident ")?;
1086                    Design::write_string(f, &name.get())?;
1087                    write!(f, " in={}", scope.index())?;
1088                }
1089                MetaItem::Attr { name, value } => {
1090                    write!(f, "attr ")?;
1091                    Design::write_string(f, &name.get())?;
1092                    write!(f, " {value}")?;
1093                }
1094            }
1095            writeln!(f)?;
1096        }
1097
1098        for (name, io_value) in self.iter_ios() {
1099            write!(f, "{}&", if !diff { "" } else { unchanged })?;
1100            Design::write_string(f, name)?;
1101            writeln!(f, ":{} = io", io_value.len())?;
1102        }
1103        for (name, io_value) in &changes.added_ios {
1104            write!(f, "{added}&")?;
1105            Design::write_string(f, name)?;
1106            writeln!(f, ":{} = io", io_value.len())?;
1107        }
1108
1109        let write_cell = |f: &mut std::fmt::Formatter, index: usize, cell: &Cell, metadata: MetaItemIndex| {
1110            for item in self.ref_metadata_item(metadata).iter() {
1111                match item.get() {
1112                    MetaItem::Source { file, start, end: _ } => {
1113                        writeln!(f, "{comment}source file://{}#{}", file.get(), start.line + 1)?;
1114                    }
1115                    MetaItem::NamedScope { .. } => {
1116                        let mut names = Vec::new();
1117                        let mut scope = item;
1118                        while !scope.is_none() {
1119                            let MetaItem::NamedScope { name, parent, .. } = scope.get() else { break };
1120                            names.push(name);
1121                            scope = parent;
1122                        }
1123                        if !names.is_empty() {
1124                            write!(f, "{comment}scope ")?;
1125                            for (index, name) in names.iter().rev().enumerate() {
1126                                if index > 0 {
1127                                    write!(f, ".")?;
1128                                }
1129                                write!(f, "{}", name.get())?;
1130                            }
1131                            writeln!(f)?;
1132                        }
1133                    }
1134                    _ => (),
1135                }
1136            }
1137            if matches!(cell, Cell::Target(..)) {
1138                for index in (index..index + cell.output_len()).rev() {
1139                    if let Some((name, offset)) = net_names.get(&Net::from_cell_index(index)) {
1140                        write!(f, "{comment}drives ")?;
1141                        Design::write_string(f, name)?;
1142                        writeln!(f, "+{offset}")?;
1143                    }
1144                }
1145            }
1146            if !diff {
1147                self.write_cell(f, "", index, cell, metadata)?;
1148            } else if changes.unalived_cells.contains(&index) {
1149                self.write_cell(f, removed, index, cell, metadata)?;
1150            } else {
1151                let mut mapped_cell;
1152                if let Some(replaced_cell) = changes.replaced_cells.get(&index) {
1153                    mapped_cell = (*replaced_cell.get()).clone();
1154                } else {
1155                    mapped_cell = cell.clone();
1156                }
1157                mapped_cell.visit_mut(|net| {
1158                    while let Some(&new_net) = changes.replaced_nets.get(net) {
1159                        *net = new_net;
1160                    }
1161                });
1162                if index >= self.cells.len() {
1163                    self.write_cell(f, added, index, &mapped_cell, metadata)?;
1164                } else if mapped_cell != *cell {
1165                    self.write_cell(f, removed, index, cell, metadata)?;
1166                    writeln!(f)?;
1167                    self.write_cell(f, added, index, &mapped_cell, metadata)?;
1168                } else {
1169                    self.write_cell(f, unchanged, index, cell, metadata)?;
1170                }
1171            }
1172            writeln!(f)
1173        };
1174
1175        if f.alternate() {
1176            for cell_ref in self.iter_cells() {
1177                write_cell(f, cell_ref.index, &cell_ref.get(), cell_ref.metadata_index())?;
1178            }
1179        } else {
1180            for cell_ref in self.iter_cells_topo() {
1181                write_cell(f, cell_ref.index, &cell_ref.get(), cell_ref.metadata_index())?;
1182            }
1183        }
1184        for (offset, cell) in changes.added_cells.iter().enumerate() {
1185            if !matches!(cell.repr, CellRepr::Skip(_) | CellRepr::Void) {
1186                write_cell(f, self.cells.len() + offset, &cell.get(), cell.meta)?;
1187            }
1188        }
1189
1190        Ok(())
1191    }
1192}