xlsynth-codegen 0.81.0

Rust-native SystemVerilog generation for XLS block IR
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
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
// SPDX-License-Identifier: Apache-2.0

use std::collections::{BTreeMap, BTreeSet};

use xlsynth::vast_helpers::{RegisterDefinition, RegisterScope, Reset};
use xlsynth_pir::block_invoke_inline::BlockInvokeInliner;
use xlsynth_pir::ir::{
    Binop, Block, BlockPort, InstantiationKind, MemberType, NodePayload, NodeRef, Package,
    PackageMember, Register, Type, Unop,
};
use xlsynth_pir::ir_utils::{get_topological, operands};
use xlsynth_pir::{IrFormatPreference, IrValue};
use xlsynth_vast::{
    Expr, IndexableExpr, LiteralFormat, LogicRef, VastDataType, VastFile, VastFileType, VastModule,
};

use crate::stages::{ChildTimings, Stage, reconstruct_stages};
use crate::{BlockCodegenError, BlockCodegenOptions, BlockCodegenOutput, Layout};

/// Holds a packed SystemVerilog value and its expression-inlining information.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Value {
    pub(crate) expr: Expr,
    pub(crate) indexable: Option<IndexableExpr>,
    pub(crate) depth: usize,
    pub(crate) bit_width: Option<usize>,
    pub(crate) static_origin: Option<(IndexableExpr, usize)>,
    pub(crate) array_rank: usize,
}

/// Collects registers whose writes use the same emitted reset expression.
struct ResettableRegisterGroup {
    signal: Expr,
    registers: Vec<RegisterDefinition>,
}

impl Value {
    /// Represents a declared, directly indexable SystemVerilog signal.
    pub(crate) fn signal(signal: LogicRef) -> Self {
        let indexable = signal.to_indexable_expr();
        Self {
            expr: signal.to_expr(),
            indexable: Some(indexable),
            depth: 0,
            bit_width: None,
            static_origin: Some((indexable, 0)),
            array_rank: 0,
        }
    }

    /// Represents an inline expression of the requested nesting depth.
    pub(crate) fn expression(expr: Expr, depth: usize) -> Self {
        Self {
            expr,
            indexable: None,
            depth,
            bit_width: None,
            static_origin: None,
            array_rank: 0,
        }
    }

    /// Preserves the original packed signal for nested, portable part-selects.
    pub(crate) fn static_slice(expr: Expr, source: Self, start: usize, width: usize) -> Self {
        Self {
            expr,
            indexable: None,
            depth: source.depth + 1,
            bit_width: Some(width),
            static_origin: source
                .static_origin
                .map(|(origin, offset)| (origin, offset + start)),
            array_rank: 0,
        }
    }

    /// Records a known packed width for scalar-index and slice legalization.
    pub(crate) fn with_width(mut self, bit_width: usize) -> Self {
        self.bit_width = Some(bit_width);
        self
    }

    /// Records the dimensions of a declared packed value, keeping bit slices
    /// distinct from array-element selections.
    pub(crate) fn with_type(mut self, mut ty: &Type) -> Self {
        self.bit_width = Some(ty.bit_count());
        self.array_rank = 0;
        while let Type::Array(array) = ty {
            self.array_rank += 1;
            ty = &array.element_type;
        }
        if self.array_rank != 0 {
            self.static_origin = None;
        }
        self
    }
}

/// Builds one module while preserving the source block's interfaces and state.
pub(crate) struct BlockEmitter<'a, 'file> {
    pub(crate) package: &'a Package,
    blocks: &'a BTreeMap<&'a str, &'a Block>,
    pub(crate) options: &'a BlockCodegenOptions,
    pub(crate) block: &'a Block,
    pub(crate) file: &'file mut VastFile,
    pub(crate) module: VastModule,
    pub(crate) values: Vec<Option<Value>>,
    pub(crate) ports: BTreeMap<String, LogicRef>,
    pub(crate) register_refs: BTreeMap<String, LogicRef>,
    pub(crate) users: Vec<Vec<NodeRef>>,
    pub(crate) names: BTreeSet<String>,
    pub(crate) genvar_names: BTreeMap<usize, String>,
    pub(crate) priority_helpers: BTreeMap<crate::priority::PriorityHelper, String>,
    pub(crate) arithmetic_helpers: BTreeMap<crate::arithmetic::ArithmeticHelper, String>,
    pub(crate) slice_helpers: BTreeMap<crate::slicing::SliceHelper, String>,
    pub(crate) current_stage: Option<usize>,
    pub(crate) instance_inputs: BTreeMap<(String, String), Expr>,
    pub(crate) instance_outputs: BTreeMap<(String, String), Expr>,
}

/// Emits a package after validating its selected block top.
pub(crate) fn emit_package(
    package: &Package,
    options: &BlockCodegenOptions,
) -> Result<BlockCodegenOutput, BlockCodegenError> {
    let top = select_top(package, options.top.as_deref())?;
    let mut inliner = BlockInvokeInliner::new(package).map_err(BlockCodegenError::InvalidBlock)?;

    let mut ordered = Vec::new();
    let mut visited = BTreeSet::new();
    let mut visiting = BTreeSet::new();
    collect_dependencies(package, top, &mut ordered, &mut visited, &mut visiting)?;
    // Hierarchy and pipeline layout must see the same data dependencies as
    // emission, including when a function ignores one of its arguments.
    let expanded = ordered
        .into_iter()
        .map(|block| {
            inliner
                .inline_block(&block.name)
                .map_err(BlockCodegenError::Unsupported)
        })
        .collect::<Result<Vec<_>, _>>()?;
    let ordered: Vec<&Block> = expanded.iter().map(|block| block.as_ref()).collect();
    let blocks = ordered.iter().map(|&b| (b.name.as_str(), b)).collect();
    for &block in &ordered {
        validate_single_register_writes(block)?;
    }
    crate::hierarchy::verify_hierarchy(&ordered)?;
    if let Some(module_name) = options.module_name.as_deref()
        && ordered
            .iter()
            .any(|block| block.name != top && block.name == module_name)
    {
        return Err(BlockCodegenError::InvalidBlock(format!(
            "top module name `{module_name}` conflicts with an instantiated child block; \
             choose a distinct module name"
        )));
    }

    let mut file = VastFile::new(VastFileType::SystemVerilog);
    let mut child_timings = ChildTimings::new();
    for block in ordered {
        let module_name = if block.name == top {
            options.module_name.as_deref().unwrap_or(&block.name)
        } else {
            &block.name
        };
        validate_external_identifier(module_name, "module")?;
        let module = file.add_module(module_name);
        let mut emitter = BlockEmitter::new(package, &blocks, options, block, &mut file, module);
        emitter.emit(&mut child_timings, block.name != top)?;
    }

    Ok(BlockCodegenOutput {
        system_verilog: file.emit(),
    })
}

/// Rejects multiple enabled writes, which PIR permits but codegen cannot emit.
fn validate_single_register_writes(block: &Block) -> Result<(), BlockCodegenError> {
    let mut write_counts = BTreeMap::<&str, usize>::new();
    for node in &block.nodes {
        if let NodePayload::RegisterWrite { register, .. } = &node.payload {
            *write_counts.entry(register.as_str()).or_default() += 1;
        }
    }

    for register in &block.registers {
        // Package verification already established at least one write.
        let writes = write_counts[register.name.as_str()];
        if writes != 1 {
            return Err(BlockCodegenError::InvalidBlock(format!(
                "register `{}` in block `{}` requires exactly one write, found {writes}",
                register.name, block.name
            )));
        }
    }

    Ok(())
}

/// Rejects operations that must be lowered before SystemVerilog emission.
fn validate_supported_nodes(block: &Block) -> Result<(), BlockCodegenError> {
    if block
        .nodes
        .iter()
        .any(|node| matches!(node.payload, NodePayload::CountedFor { .. }))
    {
        return Err(BlockCodegenError::Unsupported(format!(
            "counted_for is not supported in `{}`; unroll loops before block2sv code generation",
            block.name
        )));
    }
    if block
        .nodes
        .iter()
        .any(|node| matches!(node.payload, NodePayload::Map { .. }))
    {
        return Err(BlockCodegenError::Unsupported(format!(
            "map is not supported in `{}`; expand maps before block2sv code generation",
            block.name
        )));
    }
    Ok(())
}

/// Selects the explicitly requested, marked, or uniquely available block.
fn select_top<'a>(
    package: &'a Package,
    explicit_top: Option<&str>,
) -> Result<&'a str, BlockCodegenError> {
    let blocks = package
        .members
        .iter()
        .filter_map(|member| match member {
            PackageMember::Block(block) => Some(block.name.as_str()),
            PackageMember::Function(_) => None,
        })
        .collect::<Vec<_>>();

    if let Some(requested) = explicit_top {
        return blocks
            .into_iter()
            .find(|name| *name == requested)
            .ok_or_else(|| {
                BlockCodegenError::TopSelection(format!(
                    "requested top block `{requested}` does not exist"
                ))
            });
    }

    if let Some((name, MemberType::Block)) = &package.top {
        return blocks
            .into_iter()
            .find(|candidate| candidate == &name.as_str())
            .ok_or_else(|| {
                BlockCodegenError::TopSelection(format!(
                    "package top block `{name}` does not exist"
                ))
            });
    }

    match blocks.as_slice() {
        [only] => Ok(only),
        [] => Err(BlockCodegenError::TopSelection(
            "package contains no block suitable for SystemVerilog generation".to_owned(),
        )),
        _ => Err(BlockCodegenError::TopSelection(format!(
            "package contains multiple blocks ({}) without a block top; specify --top",
            blocks.join(", ")
        ))),
    }
}

/// Appends each transitive child once, before the block which instantiates it.
fn collect_dependencies<'a>(
    package: &'a Package,
    name: &'a str,
    ordered: &mut Vec<&'a Block>,
    visited: &mut BTreeSet<&'a str>,
    visiting: &mut BTreeSet<&'a str>,
) -> Result<(), BlockCodegenError> {
    if visited.contains(name) {
        return Ok(());
    }
    if !visiting.insert(name) {
        return Err(BlockCodegenError::InvalidBlock(format!(
            "block instantiation cycle includes `{name}`"
        )));
    }
    let block = package
        .members
        .iter()
        .find_map(|member| match member {
            PackageMember::Block(block) if block.name == name => Some(block),
            _ => None,
        })
        .ok_or_else(|| {
            BlockCodegenError::InvalidBlock(format!(
                "instantiated block `{name}` does not exist in the package"
            ))
        })?;

    for instance in &block.instantiations {
        if instance.kind == InstantiationKind::Block {
            collect_dependencies(package, &instance.block, ordered, visited, visiting)?;
        }
    }
    visiting.remove(name);
    visited.insert(name);
    ordered.push(block);
    Ok(())
}

impl<'a, 'file> BlockEmitter<'a, 'file> {
    /// Creates an emitter before constructing the module's public ports.
    fn new(
        package: &'a Package,
        blocks: &'a BTreeMap<&'a str, &'a Block>,
        options: &'a BlockCodegenOptions,
        block: &'a Block,
        file: &'file mut VastFile,
        module: VastModule,
    ) -> Self {
        let mut users = vec![Vec::new(); block.nodes.len()];
        for (index, node) in block.nodes.iter().enumerate() {
            for operand in operands(&node.payload) {
                users[operand.index].push(NodeRef { index });
            }
        }
        Self {
            package,
            blocks,
            options,
            block,
            file,
            module,
            values: vec![None; block.nodes.len()],
            ports: BTreeMap::new(),
            register_refs: BTreeMap::new(),
            users,
            names: BTreeSet::new(),
            genvar_names: BTreeMap::new(),
            priority_helpers: BTreeMap::new(),
            arithmetic_helpers: BTreeMap::new(),
            slice_helpers: BTreeMap::new(),
            current_stage: None,
            instance_inputs: BTreeMap::new(),
            instance_outputs: BTreeMap::new(),
        }
    }

    /// Emits ports, logic, state, output assignments, and child instances.
    fn emit(
        &mut self,
        child_timings: &mut ChildTimings<'a>,
        summarize_for_parent: bool,
    ) -> Result<(), BlockCodegenError> {
        validate_supported_nodes(self.block)?;
        self.reserve_fixed_names()?;
        self.emit_ports()?;
        self.emit_arithmetic_helpers()?;
        self.emit_slice_helpers()?;
        self.emit_priority_helpers(self.block)?;
        match self.options.layout {
            Layout::None => self.emit_flat()?,
            Layout::Pipeline => {
                let stages = reconstruct_stages(self.block, child_timings, summarize_for_parent)?;
                self.emit_pipeline(&stages)?;
            }
        }
        self.emit_outputs()?;
        self.emit_instantiations()?;
        Ok(())
    }

    /// Rejects conflicting fixed identifiers and protects them from generated
    /// declarations throughout this module, regardless of emission order.
    fn reserve_fixed_names(&mut self) -> Result<(), BlockCodegenError> {
        let mut fixed_names = BTreeMap::new();
        let mut reserve = |name: &str, kind: &'static str| {
            validate_external_identifier(name, kind)?;
            if let Some(previous) = fixed_names.insert(name.to_owned(), kind) {
                return Err(BlockCodegenError::InvalidBlock(format!(
                    "SystemVerilog name collision in block `{}`: `{name}` is used by both {previous} and {kind}",
                    self.block.name
                )));
            }
            Ok(())
        };
        if let Some(clock) = self.block.clock_port_name() {
            reserve(clock, "port")?;
        }
        for port in self.block.input_ports().chain(self.block.output_ports()) {
            if self.block.port_type(port).bit_count() != 0 {
                reserve(self.block.port_name(port), "port")?;
            }
        }
        for instance in &self.block.instantiations {
            reserve(&instance.name, "instance")?;
        }
        for node in &self.block.nodes {
            match &node.payload {
                NodePayload::Assert { label, .. }
                    if self.options.emit_asserts && !label.is_empty() =>
                {
                    reserve(label, "assertion label")?;
                }
                NodePayload::Cover { label, .. } => reserve(label, "coverage label")?,
                _ => {
                    // Other nodes have generated names or introduce no fixed
                    // declaration in the module scope.
                }
            }
        }
        self.names.extend(fixed_names.into_keys());
        Ok(())
    }

    /// Emits representable ports in the source block's original header order.
    fn emit_ports(&mut self) -> Result<(), BlockCodegenError> {
        for port in &self.block.ports {
            let (name, ir_type, sv_type, is_output) = match port {
                BlockPort::Clock(name) => (name.clone(), Type::Bits(1), None, false),
                BlockPort::Input(node) | BlockPort::Output(node) => {
                    let sv_type = match &self.block.get_node(*node).payload {
                        NodePayload::InputPort { sv_type, .. }
                        | NodePayload::OutputPort { sv_type, .. } => sv_type.as_deref(),
                        _ => unreachable!("verified block data port"),
                    };
                    (
                        self.block.port_name(*node).to_string(),
                        self.block.port_type(*node).clone(),
                        sv_type,
                        matches!(port, BlockPort::Output(_)),
                    )
                }
            };
            if self.ports.contains_key(&name) {
                continue;
            }
            let width = ir_type.bit_count();
            if width == 0 {
                continue;
            }
            validate_external_identifier(&name, "port")?;
            let data_type = if self.options.emit_sv_types {
                if let Some(sv_type) = sv_type {
                    if let Some((package, ty)) = sv_type.rsplit_once("::") {
                        self.file.make_extern_package_type(package, ty)
                    } else {
                        self.file.make_extern_type(sv_type)
                    }
                } else {
                    self.value_type(&ir_type)
                }
            } else {
                self.value_type(&ir_type)
            };
            let signal = if is_output {
                self.file.add_logic_output(self.module, &name, &data_type)
            } else {
                self.file.add_logic_input(self.module, &name, &data_type)
            };
            self.ports.insert(name, signal);
        }

        for (index, node) in self.block.nodes.iter().enumerate() {
            if let NodePayload::InputPort { name, sv_type } = &node.payload {
                if let Some(signal) = self.ports.get(name).copied() {
                    let value = Value::signal(signal).with_width(node.ty.bit_count());
                    self.values[index] = Some(if self.options.emit_sv_types && sv_type.is_some() {
                        value
                    } else {
                        value.with_type(&node.ty)
                    });
                }
            }
        }
        Ok(())
    }

    /// Emits existing register state and ordinary dependency-ordered logic.
    fn emit_flat(&mut self) -> Result<(), BlockCodegenError> {
        let start = self.file.module_member_count(self.module);
        self.emit_input_array_views()?;
        for register in &self.block.registers {
            self.declare_register(register)?;
        }
        let mut writes = Vec::new();
        for node_ref in get_topological(self.block) {
            match &self.block.get_node(node_ref).payload {
                NodePayload::Nil
                | NodePayload::InputPort { .. }
                | NodePayload::OutputPort { .. } => {
                    // Reserved nodes and parameters are represented by module
                    // ports.
                }
                NodePayload::RegisterRead { register } => {
                    if let Some(signal) = self.register_refs.get(register).copied() {
                        self.values[node_ref.index] =
                            Some(Value::signal(signal).with_type(self.block.get_node_ty(node_ref)));
                    }
                }
                NodePayload::RegisterWrite { .. } => writes.push(node_ref),
                _ => self.emit_node(node_ref)?,
            }
        }
        self.emit_register_groups(&writes)?;
        self.file.hoist_module_declarations(self.module, start);
        Ok(())
    }

    /// Emits register-delimited comments without altering sequential behavior.
    fn emit_pipeline(&mut self, stages: &[Stage]) -> Result<(), BlockCodegenError> {
        let mut emitted_visible_stage = false;
        for (stage_index, stage) in stages.iter().enumerate() {
            self.current_stage = Some(stage_index);
            let visible =
                !stage.combinational_nodes.is_empty() || !stage.register_writes.is_empty();
            if visible {
                if emitted_visible_stage {
                    let blank = self.file.make_blank_line();
                    self.file.add_member_blank_line(self.module, blank);
                }
                let comment = self
                    .file
                    .make_comment(&format!("===== Pipe stage {stage_index}:"));
                self.file.add_member_comment(self.module, comment);
                emitted_visible_stage = true;
            }
            self.emit_stage(stage, stage_index)?;
        }
        self.current_stage = None;
        Ok(())
    }

    /// Emits one reconstructed stage and the registers written at its end.
    fn emit_stage(&mut self, stage: &Stage, stage_index: usize) -> Result<(), BlockCodegenError> {
        for &node_ref in &stage.register_reads {
            if let NodePayload::RegisterRead { register } = &self.block.get_node(node_ref).payload {
                if let Some(signal) = self.register_refs.get(register).copied() {
                    self.values[node_ref.index] =
                        Some(Value::signal(signal).with_type(self.block.get_node_ty(node_ref)));
                }
            }
        }
        let start = self.file.module_member_count(self.module);
        if stage_index == 0 {
            self.emit_input_array_views()?;
        }
        for &node_ref in &stage.combinational_nodes {
            self.emit_node(node_ref)?;
        }
        self.file.hoist_module_declarations(self.module, start);
        if !stage.register_writes.is_empty() {
            let blank = self.file.make_blank_line();
            self.file.add_member_blank_line(self.module, blank);
            let comment = self
                .file
                .make_comment(&format!("Registers for pipe stage {stage_index}:"));
            self.file.add_member_comment(self.module, comment);
            for &node_ref in &stage.register_writes {
                if let NodePayload::RegisterWrite { register, .. } =
                    &self.block.get_node(node_ref).payload
                {
                    let definition = self
                        .block
                        .registers
                        .iter()
                        .find(|definition| definition.name == *register)
                        .ok_or_else(|| {
                            BlockCodegenError::InvalidBlock(format!(
                                "register `{register}` has no declaration in block `{}`",
                                self.block.name
                            ))
                        })?;
                    self.declare_register(definition)?;
                }
            }
            self.emit_register_groups(&stage.register_writes)?;
        }
        Ok(())
    }

    /// Declares one representable packed register and remembers its signal.
    fn declare_register(&mut self, register: &Register) -> Result<(), BlockCodegenError> {
        if register.ty.bit_count() == 0 || self.register_refs.contains_key(&register.name) {
            return Ok(());
        }
        let data_type = self.value_type(&register.ty);
        let name = self.unique_name(&register.name);
        let signal = self.file.add_logic(self.module, &name, &data_type)?;
        self.register_refs.insert(register.name.clone(), signal);
        Ok(())
    }

    /// Groups resettable and non-resettable registers by their existing clock.
    fn emit_register_groups(&mut self, writes: &[NodeRef]) -> Result<(), BlockCodegenError> {
        let mut resettable = Vec::new();
        let mut ordinary = Vec::new();
        for &node_ref in writes {
            let NodePayload::RegisterWrite {
                arg,
                register,
                load_enable,
                reset,
            } = &self.block.get_node(node_ref).payload
            else {
                continue;
            };
            let Some(&signal) = self.register_refs.get(register) else {
                continue;
            };
            let definition = self
                .block
                .registers
                .iter()
                .find(|definition| definition.name == *register)
                .expect("verified register write has a declaration");
            let next = self.required_value(*arg)?.expr;
            let enable = load_enable
                .map(|node| self.required_value(node).map(|value| value.expr))
                .transpose()?;
            let reset_signal = reset
                .map(|node| self.required_value(node).map(|value| value.expr))
                .transpose()?;
            let reset_value = if reset_signal.is_some() {
                definition
                    .reset_value
                    .as_ref()
                    .map(|value| self.literal(value, &definition.ty))
                    .transpose()?
                    .flatten()
            } else {
                None
            };
            let register = RegisterDefinition {
                reg: signal.to_expr(),
                next,
                reset_value,
                enable,
            };
            if let Some(signal) = reset_signal {
                resettable.push((signal, register));
            } else {
                ordinary.push(register);
            }
        }
        if ordinary.is_empty() && resettable.is_empty() {
            return Ok(());
        }
        let clock_name = self.block.clock_port_name().ok_or_else(|| {
            BlockCodegenError::InvalidBlock(format!(
                "block `{}` has registers but no clock port",
                self.block.name
            ))
        })?;
        let clock = self
            .ports
            .get(clock_name)
            .ok_or_else(|| {
                BlockCodegenError::InvalidBlock(format!(
                    "block `{}` has no declared clock port `{clock_name}`",
                    self.block.name
                ))
            })?
            .to_expr();

        if !ordinary.is_empty() {
            xlsynth::vast_helpers::add_registers(
                &clock,
                None,
                &ordinary,
                RegisterScope::Module(self.module),
                self.file,
                self.options.register_codegen_options.as_ref(),
            )?;
        }
        if !resettable.is_empty() {
            let reset_metadata = self.block.reset.as_ref().ok_or_else(|| {
                BlockCodegenError::InvalidBlock(format!(
                    "block `{}` has resettable registers but no reset metadata",
                    self.block.name
                ))
            })?;
            let mut groups = Vec::<ResettableRegisterGroup>::new();
            for (signal, register) in resettable {
                if let Some(group) = groups.iter_mut().find(|group| group.signal == signal) {
                    group.registers.push(register);
                } else {
                    groups.push(ResettableRegisterGroup {
                        signal,
                        registers: vec![register],
                    });
                }
            }
            for group in groups {
                let reset = Reset {
                    signal: group.signal,
                    active_low: reset_metadata.active_low,
                };
                if reset_metadata.asynchronous {
                    if let Some(options) = &self.options.register_codegen_options {
                        let requires_enable = group
                            .registers
                            .iter()
                            .any(|register| register.enable.is_some());
                        if options.reg_with_reset_template.is_some()
                            || (requires_enable
                                && options.reg_with_reset_with_en_template.is_some())
                        {
                            return Err(BlockCodegenError::Unsupported(format!(
                                concat!(
                                    "block `{}` has asynchronous reset; custom reset-register ",
                                    "templates cannot guarantee the required reset edge semantics"
                                ),
                                self.block.name
                            )));
                        }
                    }
                    self.emit_asynchronous_registers(&clock, reset, &group.registers)?;
                } else {
                    xlsynth::vast_helpers::add_registers(
                        &clock,
                        Some(reset),
                        &group.registers,
                        RegisterScope::Module(self.module),
                        self.file,
                        self.options.register_codegen_options.as_ref(),
                    )?;
                }
            }
        }
        Ok(())
    }

    /// Emits an asynchronous reset edge with reset priority over load enables.
    fn emit_asynchronous_registers(
        &mut self,
        clock: &Expr,
        reset: Reset,
        registers: &[RegisterDefinition],
    ) -> Result<(), BlockCodegenError> {
        let clock_edge = self.file.make_pos_edge(clock);
        let reset_edge = if reset.active_low {
            self.file.make_neg_edge(&reset.signal)
        } else {
            self.file.make_pos_edge(&reset.signal)
        };
        let always = self
            .file
            .add_always_ff(self.module, &[&clock_edge, &reset_edge])?;
        let body = self.file.statement_block(always);
        let condition = if reset.active_low {
            self.file.make_logical_not(&reset.signal)
        } else {
            reset.signal
        };
        let conditional = self.file.block_add_cond(body, &condition);
        let reset_body = self.file.conditional_then_block(conditional);
        let update_body = self.file.conditional_add_else(conditional);
        for register in registers {
            let reset_value = register
                .reset_value
                .expect("resettable register group requires reset values");
            self.file
                .block_add_nonblocking_assignment(reset_body, &register.reg, &reset_value);
            let next = if let Some(enable) = register.enable {
                self.file
                    .make_ternary(&enable, &register.next, &register.reg)
            } else {
                register.next
            };
            self.file
                .block_add_nonblocking_assignment(update_body, &register.reg, &next);
        }
        Ok(())
    }

    /// Connects representable output ports after their driving logic exists.
    fn emit_outputs(&mut self) -> Result<(), BlockCodegenError> {
        for port in self.block.output_ports() {
            let name = self.block.port_name(port);
            let node_ref = self.block.output_value(port);
            let Some(signal) = self.ports.get(name).copied() else {
                continue;
            };
            let value = self.required_value(node_ref)?;
            let assignment = self
                .file
                .make_continuous_assignment(&signal.to_expr(), &value.expr);
            self.file
                .add_member_continuous_assignment(self.module, assignment);
        }
        Ok(())
    }

    /// Emits deterministic child connections after all connection nodes exist.
    fn emit_instantiations(&mut self) -> Result<(), BlockCodegenError> {
        if self.block.instantiations.is_empty() {
            return Ok(());
        }
        if self.options.layout == Layout::Pipeline {
            let blank = self.file.make_blank_line();
            self.file.add_member_blank_line(self.module, blank);
            let comment = self.file.make_comment("===== Instantiations");
            self.file.add_member_comment(self.module, comment);
        }

        for instance in &self.block.instantiations {
            validate_external_identifier(&instance.name, "instance")?;
            let mut connections = self
                .instance_inputs
                .iter()
                .chain(self.instance_outputs.iter())
                .filter(|((name, _), _)| name == &instance.name)
                .map(|((_, port), expr)| (port.clone(), *expr))
                .collect::<Vec<_>>();

            if instance.kind == InstantiationKind::Block {
                let child = self.blocks[instance.block.as_str()];
                if let Some(clock_name) = child.clock_port_name() {
                    if !connections.iter().any(|(name, _)| name == clock_name) {
                        if let Some(parent_clock) = self
                            .block
                            .clock_port_name()
                            .and_then(|name| self.ports.get(name))
                        {
                            connections.push((clock_name.to_string(), parent_clock.to_expr()));
                        } else {
                            return Err(BlockCodegenError::InvalidBlock(format!(
                                "instance `{}` of block `{}` requires clock port \
                                 `{clock_name}`, but parent block `{}` has no clock",
                                instance.name, instance.block, self.block.name
                            )));
                        }
                    }
                }
                let order = child
                    .ports
                    .iter()
                    .map(|port| match port {
                        BlockPort::Clock(name) => name.as_str(),
                        BlockPort::Input(node) | BlockPort::Output(node) => child.port_name(*node),
                    })
                    .collect::<Vec<_>>();
                connections.sort_by_key(|(name, _)| {
                    (
                        order
                            .iter()
                            .position(|port| *port == name)
                            .unwrap_or(usize::MAX),
                        name.clone(),
                    )
                });
                let names = connections
                    .iter()
                    .map(|(name, _)| name.as_str())
                    .collect::<Vec<_>>();
                let expressions = connections
                    .iter()
                    .map(|(_, expr)| Some(expr))
                    .collect::<Vec<_>>();
                let handle = self.file.make_instantiation(
                    &instance.block,
                    &instance.name,
                    &[],
                    &[],
                    &names,
                    &expressions,
                );
                self.file.add_member_instantiation(self.module, handle);
            } else {
                self.emit_external_instantiation(instance, &connections)?;
            }
        }
        Ok(())
    }

    /// Substitutes external-function placeholders into its public FFI template.
    fn emit_external_instantiation(
        &mut self,
        instance: &xlsynth_pir::ir::Instantiation,
        connections: &[(String, Expr)],
    ) -> Result<(), BlockCodegenError> {
        let foreign = self.package.get_fn(&instance.block).ok_or_else(|| {
            BlockCodegenError::InvalidBlock(format!(
                "external instance `{}` references missing function `{}`",
                instance.name, instance.block
            ))
        })?;
        let template = foreign
            .ffi_proto()
            .and_then(|ffi| ffi.code_template.as_deref())
            .ok_or_else(|| {
                BlockCodegenError::Unsupported(format!(
                    "external function `{}` has no ffi_proto code_template",
                    foreign.name
                ))
            })?;
        let template = std::str::from_utf8(template).map_err(|error| {
            BlockCodegenError::InvalidBlock(format!(
                "external function `{}` has a non-UTF-8 ffi_proto code_template at byte {}",
                foreign.name,
                error.valid_up_to()
            ))
        })?;
        let bindings = connections
            .iter()
            .map(|(name, value)| (name.as_str(), self.file.emit_expression(value)))
            .collect::<BTreeMap<_, _>>();
        let template = substitute_external_template(template, &instance.name, &bindings)?;
        let statement = self.file.make_inline_verilog_statement(template.trim());
        self.file
            .add_member_inline_statement(self.module, statement);
        Ok(())
    }

    /// Builds the packed scalar or vector type used for one IR value.
    pub(crate) fn bits_type(&mut self, width: usize) -> VastDataType {
        self.file.make_bit_vector_type(width as i64, false)
    }

    /// Preserves outer array dimensions while packing tuple leaves into bits.
    pub(crate) fn value_type(&mut self, mut ty: &Type) -> VastDataType {
        let mut dimensions = Vec::new();
        while let Type::Array(array) = ty {
            dimensions.push(array.element_count as i64);
            ty = &array.element_type;
        }
        let element = self.bits_type(ty.bit_count());
        if dimensions.is_empty() {
            element
        } else {
            self.file.make_packed_array_type(element, &dimensions)
        }
    }

    /// Gives custom-typed array input ports shaped views without changing
    /// their explicitly requested SystemVerilog types.
    fn emit_input_array_views(&mut self) -> Result<(), BlockCodegenError> {
        for (index, node) in self.block.nodes.iter().enumerate() {
            if matches!(node.payload, NodePayload::InputPort { .. })
                && matches!(node.ty, Type::Array(_))
                && let Some(value) = self.values[index]
                && value.array_rank == 0
            {
                let view = self.assign_node(NodeRef { index }, value.expr)?;
                self.values[index] = Some(view);
            }
        }
        Ok(())
    }

    /// Returns the represented expression for a node with nonzero bit width.
    pub(crate) fn required_value(&self, node: NodeRef) -> Result<Value, BlockCodegenError> {
        self.values[node.index].ok_or_else(|| {
            BlockCodegenError::InvalidBlock(format!(
                "node `{}` in block `{}` has no representable SystemVerilog value",
                self.block.get_node(node).name.clone().unwrap_or_else(|| {
                    format!(
                        "{}.{}",
                        self.block.get_node(node).payload.get_operator(),
                        self.block.get_node(node).text_id
                    )
                }),
                self.block.name
            ))
        })
    }

    /// Converts an arbitrary-width IR literal into its packed representation.
    pub(crate) fn literal(
        &mut self,
        value: &IrValue,
        ty: &Type,
    ) -> Result<Option<Expr>, BlockCodegenError> {
        if ty.bit_count() == 0 {
            return Ok(None);
        }
        match ty {
            Type::Bits(_) => {
                let formatted = value.to_string_fmt(IrFormatPreference::Hex);
                Ok(Some(
                    self.file.make_literal(&formatted, &LiteralFormat::Hex)?,
                ))
            }
            Type::Tuple(types) => {
                let values = value.as_elements()?;
                let mut expressions = Vec::new();
                for (value, ty) in values.iter().zip(types) {
                    if let Some(expression) = self.literal(value, ty)? {
                        expressions.push(expression);
                    }
                }
                Ok(self.concat_or_only(&expressions))
            }
            Type::Array(array) => {
                let values = value.as_elements()?;
                let mut expressions = Vec::new();
                for value in values.iter().rev() {
                    if let Some(expression) = self.literal(value, &array.element_type)? {
                        expressions.push(expression);
                    }
                }
                Ok(self.concat_or_only(&expressions))
            }
            Type::Token => Ok(None),
        }
    }

    /// Concatenates expressions while avoiding an unnecessary one-element
    /// brace.
    pub(crate) fn concat_or_only(&mut self, expressions: &[Expr]) -> Option<Expr> {
        match expressions {
            [] => None,
            [only] => Some(*only),
            many => {
                let refs = many.iter().collect::<Vec<_>>();
                Some(self.file.make_concat(&refs))
            }
        }
    }

    /// Allocates a deterministic module-local identifier without collisions.
    pub(crate) fn unique_name(&mut self, requested: &str) -> String {
        let mut base = sanitize_identifier(requested);
        if self.names.insert(base.clone()) {
            return base;
        }
        let mut index = 1usize;
        loop {
            let candidate = format!("{base}__{index}");
            if self.names.insert(candidate.clone()) {
                return candidate;
            }
            index += 1;
            if index == usize::MAX {
                base.push('_');
                index = 1;
            }
        }
    }

    /// Declares a stable, indexable signal for one materialized IR node.
    pub(crate) fn declare_node(
        &mut self,
        node_ref: NodeRef,
    ) -> Result<LogicRef, BlockCodegenError> {
        let name = self.node_name(node_ref);
        let unique = self.unique_name(&name);
        let ty = self.value_type(self.block.get_node_ty(node_ref));
        Ok(self.file.add_logic(self.module, &unique, &ty)?)
    }

    /// Builds the requested node name in the current source-layout scope.
    pub(crate) fn node_name(&self, node_ref: NodeRef) -> String {
        let node = self.block.get_node(node_ref);
        let original_name = node
            .name
            .clone()
            .unwrap_or_else(|| format!("{}_{}", node.payload.get_operator(), node.text_id));
        if let Some(stage) = self.current_stage {
            let base = strip_pipeline_prefix(&original_name);
            format!("p{stage}_{base}_comb")
        } else {
            original_name
        }
    }

    /// Emits a stable signal assignment and returns its indexable value.
    pub(crate) fn assign_node(
        &mut self,
        node_ref: NodeRef,
        expression: Expr,
    ) -> Result<Value, BlockCodegenError> {
        let signal = self.declare_node(node_ref)?;
        let assignment = self
            .file
            .make_continuous_assignment(&signal.to_expr(), &expression);
        self.file
            .add_member_continuous_assignment(self.module, assignment);
        Ok(Value::signal(signal).with_type(self.block.get_node_ty(node_ref)))
    }

    /// Returns whether this node should be assigned a dedicated named signal.
    pub(crate) fn should_assign(&self, node_ref: NodeRef, depth: usize) -> bool {
        self.must_assign(node_ref)
            || self.block.get_node(node_ref).name.is_some()
            || self.users[node_ref.index].len() > 1
            || depth > self.options.max_inline_depth
    }

    /// Preserves fixed-width and indexability boundaries required by lowering.
    fn must_assign(&self, node_ref: NodeRef) -> bool {
        let node = self.block.get_node(node_ref);
        matches!(node.ty, Type::Array(_))
            || matches!(
                node.payload,
                NodePayload::ArrayIndex { .. }
                    | NodePayload::ExtCarryOut { .. }
                    | NodePayload::ExtNaryAdd { .. }
            )
            || matches!(
                node.payload,
                NodePayload::Binop(
                    Binop::Add
                        | Binop::Sub
                        | Binop::Smul
                        | Binop::Umul
                        | Binop::Smulp
                        | Binop::Umulp
                        | Binop::Sdiv
                        | Binop::Udiv,
                    _,
                    _
                )
            )
            || self.options.separate_lines
            || self.users[node_ref.index]
                .iter()
                .any(|user| self.operand_must_be_named_reference(*user, node_ref))
    }

    /// Identifies operand roles whose lowering requires a declared signal.
    fn operand_must_be_named_reference(&self, user: NodeRef, operand: NodeRef) -> bool {
        match &self.block.get_node(user).payload {
            NodePayload::RegisterWrite { .. } => true,
            NodePayload::BitSlice { arg, .. } => *arg == operand,
            NodePayload::TupleIndex { tuple, .. } => *tuple == operand,
            NodePayload::SignExt { arg, .. } => {
                *arg == operand && self.block.get_node_ty(operand).bit_count() > 1
            }
            NodePayload::ExtNaryAdd { terms, .. } => {
                terms.iter().any(|term| term.operand == operand)
            }
            NodePayload::OneHot { arg, .. }
            | NodePayload::Encode { arg }
            | NodePayload::ExtPrioEncode { arg, .. }
            | NodePayload::ExtClz { arg, .. }
            | NodePayload::ExtNormalizeLeft { arg, .. }
            | NodePayload::Unop(Unop::Reverse, arg) => {
                *arg == operand && self.block.get_node_ty(operand).bit_count() > 1
            }
            NodePayload::Sel {
                selector, cases, ..
            }
            | NodePayload::PrioritySel {
                selector, cases, ..
            }
            | NodePayload::OneHotSel { selector, cases } => *selector == operand && cases.len() > 1,
            NodePayload::ArraySlice {
                array,
                start,
                width,
            } => *width > 1 && (*array == operand || *start == operand),
            NodePayload::ArrayUpdate { indices, .. } => {
                // Genvar comparisons must not widen an inline index expression.
                indices.contains(&operand)
            }
            _ => false,
        }
    }
}

/// Substitutes named FFI expressions while unescaping doubled literal braces.
fn substitute_external_template(
    template: &str,
    instance_name: &str,
    bindings: &BTreeMap<&str, String>,
) -> Result<String, BlockCodegenError> {
    let bytes = template.as_bytes();
    let mut output = String::with_capacity(template.len());
    let mut index = 0usize;
    while index < bytes.len() {
        match bytes[index] {
            b'{' if bytes.get(index + 1) == Some(&b'{') => {
                output.push('{');
                index += 2;
            }
            b'}' if bytes.get(index + 1) == Some(&b'}') => {
                output.push('}');
                index += 2;
            }
            b'{' => {
                let start = index + 1;
                let mut nesting = 1usize;
                index = start;
                while index < bytes.len() && nesting != 0 {
                    match bytes[index] {
                        b'{' => nesting += 1,
                        b'}' => nesting -= 1,
                        _ => {
                            // Ordinary expression characters do not change
                            // brace nesting.
                        }
                    }
                    if nesting != 0 {
                        index += 1;
                    }
                }
                if index >= bytes.len() {
                    return Err(BlockCodegenError::InvalidBlock(format!(
                        "external instance `{instance_name}` has an unterminated \
                         ffi_proto placeholder"
                    )));
                }
                let name = &template[start..index];
                if name == "fn" {
                    output.push_str(instance_name);
                } else if let Some(value) = bindings.get(name) {
                    output.push_str(value);
                } else {
                    return Err(BlockCodegenError::InvalidBlock(format!(
                        "external instance `{instance_name}` leaves ffi_proto \
                         placeholder `{{{name}}}` unresolved"
                    )));
                }
                index += 1;
            }
            b'}' => {
                return Err(BlockCodegenError::InvalidBlock(format!(
                    "external instance `{instance_name}` has an unmatched \
                     closing brace in its ffi_proto template"
                )));
            }
            _ => {
                let character = template[index..]
                    .chars()
                    .next()
                    .expect("byte index is positioned at a UTF-8 character");
                output.push(character);
                index += character.len_utf8();
            }
        }
    }
    Ok(output)
}

/// Rejects public interface names that SystemVerilog cannot represent safely.
pub(crate) fn validate_external_identifier(
    name: &str,
    kind: &str,
) -> Result<(), BlockCodegenError> {
    if sanitize_identifier(name) != name {
        return Err(BlockCodegenError::InvalidBlock(format!(
            "invalid SystemVerilog {kind} identifier `{name}`: identifier is reserved, \
             malformed, or requires escaping"
        )));
    }
    Ok(())
}

/// Produces a valid, deterministic SystemVerilog identifier from an IR name.
fn sanitize_identifier(name: &str) -> String {
    let mut output = String::with_capacity(name.len() + 1);
    for (index, character) in name.chars().enumerate() {
        if character.is_ascii_alphabetic()
            || character == '_'
            || (index != 0 && (character.is_ascii_digit() || character == '$'))
        {
            output.push(character);
        } else {
            if index == 0 && character.is_ascii_digit() {
                output.push('_');
                output.push(character);
            } else {
                output.push('_');
            }
        }
    }
    if output.is_empty() {
        output.push('_');
    }
    if xlsynth_vast::is_system_verilog_keyword(&output) {
        output.push('_');
    }
    output
}

/// Removes an existing `p<digits>_` prefix before assigning a new stage.
fn strip_pipeline_prefix(name: &str) -> &str {
    let Some(rest) = name.strip_prefix('p') else {
        return name;
    };
    let digit_count = rest.chars().take_while(char::is_ascii_digit).count();
    if digit_count > 0 && rest[digit_count..].starts_with('_') {
        &rest[digit_count + 1..]
    } else {
        name
    }
}