diff --git a/CLAUDE.md b/CLAUDE.md
index 4b006d7bd54..40fa5b29d36 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -101,6 +101,7 @@ GCC-style optimization level presets with per-pass overrides.
| `IdentityStoreBypass` | Detects identity copies and registers address aliases |
| `TailCallSplit` | Splits large functions into tail-call chains (enabled even at O0) |
| `DerivedEdgeUnits` | Runs edges of gated/divided clocks in generated units instead of the Rust plan walk (not a SIR transform; costs build time, `-sir:derived_edge_units` to opt out) |
+| `PartitionedSettle` | Splits the combinational settle into partitions that run only when state they read changed (not a SIR transform; off unless enabled, `+sir:partitioned_settle`; `SimulatorBuilder::settle_check` cross-checks it) |
### Cranelift Backend Optimization
diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv
index a6186810a34..404b148ae0e 100644
--- a/conformance/sv-tests/expected.tsv
+++ b/conformance/sv-tests/expected.tsv
@@ -777,18 +777,18 @@ chapter-21/21.2--write-boh.sv 2state pass
chapter-21/21.2--write-boh.sv 4state pass
chapter-21/21.2--write.sv 2state pass
chapter-21/21.2--write.sv 4state pass
-chapter-21/21.3--fdisplay-boh.sv 2state fail
-chapter-21/21.3--fdisplay-boh.sv 4state fail
-chapter-21/21.3--fdisplay.sv 2state fail
-chapter-21/21.3--fdisplay.sv 4state fail
+chapter-21/21.3--fdisplay-boh.sv 2state pass
+chapter-21/21.3--fdisplay-boh.sv 4state pass
+chapter-21/21.3--fdisplay.sv 2state pass
+chapter-21/21.3--fdisplay.sv 4state pass
chapter-21/21.3--feof.sv 2state pass
chapter-21/21.3--feof.sv 4state pass
chapter-21/21.3--ferror.sv 2state fail
chapter-21/21.3--ferror.sv 4state fail
chapter-21/21.3--fflush.sv 2state pass
chapter-21/21.3--fflush.sv 4state pass
-chapter-21/21.3--fgetc.sv 2state fail
-chapter-21/21.3--fgetc.sv 4state fail
+chapter-21/21.3--fgetc.sv 2state pass
+chapter-21/21.3--fgetc.sv 4state pass
chapter-21/21.3--fgets.sv 2state fail
chapter-21/21.3--fgets.sv 4state fail
chapter-21/21.3--file.sv 2state pass
@@ -797,16 +797,16 @@ chapter-21/21.3--fmonitor.sv 2state fail
chapter-21/21.3--fmonitor.sv 4state fail
chapter-21/21.3--fpos.sv 2state pass
chapter-21/21.3--fpos.sv 4state pass
-chapter-21/21.3--fread.sv 2state fail
-chapter-21/21.3--fread.sv 4state fail
-chapter-21/21.3--fscanf.sv 2state fail
-chapter-21/21.3--fscanf.sv 4state fail
+chapter-21/21.3--fread.sv 2state pass
+chapter-21/21.3--fread.sv 4state pass
+chapter-21/21.3--fscanf.sv 2state pass
+chapter-21/21.3--fscanf.sv 4state pass
chapter-21/21.3--fstrobe.sv 2state fail
chapter-21/21.3--fstrobe.sv 4state fail
-chapter-21/21.3--fwrite-boh.sv 2state fail
-chapter-21/21.3--fwrite-boh.sv 4state fail
-chapter-21/21.3--fwrite.sv 2state fail
-chapter-21/21.3--fwrite.sv 4state fail
+chapter-21/21.3--fwrite-boh.sv 2state pass
+chapter-21/21.3--fwrite-boh.sv 4state pass
+chapter-21/21.3--fwrite.sv 2state pass
+chapter-21/21.3--fwrite.sv 4state pass
chapter-21/21.3--sscanf.sv 2state pass
chapter-21/21.3--sscanf.sv 4state pass
chapter-21/21.3--ungetc.sv 2state fail
@@ -1579,8 +1579,8 @@ chapter-9/9.2.2.3--always_latch.sv 2state fail
chapter-9/9.2.2.3--always_latch.sv 4state fail
chapter-9/9.2.2.4--always_ff.sv 2state pass
chapter-9/9.2.2.4--always_ff.sv 4state pass
-chapter-9/9.2.3--final.sv 2state fail
-chapter-9/9.2.3--final.sv 4state fail
+chapter-9/9.2.3--final.sv 2state pass
+chapter-9/9.2.3--final.sv 4state pass
chapter-9/9.3.1--sequential_block.sv 2state pass
chapter-9/9.3.1--sequential_block.sv 4state pass
chapter-9/9.3.2--parallel_block_join.sv 2state fail
@@ -1735,46 +1735,46 @@ generated/assignment_op/11.4.1--plus_assignment.sv 2state pass
generated/assignment_op/11.4.1--plus_assignment.sv 4state pass
generated/assignment_op/11.4.1--xor_assignment.sv 2state pass
generated/assignment_op/11.4.1--xor_assignment.sv 4state pass
-generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state fail
-generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state fail
-generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state fail
-generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state fail
-generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state fail
+generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state pass
+generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state pass
+generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state pass
+generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state pass
+generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state pass
generated/binary_op/11.4.10--binary_op_arith_shl.sv 2state pass
generated/binary_op/11.4.10--binary_op_arith_shl.sv 4state pass
generated/binary_op/11.4.10--binary_op_arith_shr.sv 2state pass
@@ -2467,22 +2467,22 @@ generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 2s
generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 4state fail
generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 2state fail
generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state fail
-generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state fail
-generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state fail
+generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state pass
+generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state pass
+generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state pass
+generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state pass
+generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state pass
+generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state pass
+generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state pass
+generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state pass
+generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state pass
generated/nets/6.6.1--net_tri.sv 2state pass
generated/nets/6.6.1--net_tri.sv 4state pass
generated/nets/6.6.1--net_wire.sv 2state pass
@@ -2507,42 +2507,42 @@ generated/nets/6.6.6--net_supply0.sv 2state fail
generated/nets/6.6.6--net_supply0.sv 4state fail
generated/nets/6.6.6--net_supply1.sv 2state fail
generated/nets/6.6.6--net_supply1.sv 4state fail
-generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state fail
+generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state pass
generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 2state pass
generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 4state pass
generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 2state pass
generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 4state pass
-generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state fail
+generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state pass
generated/operators_sim/11.4.3--simple_div_operator_sim.sv 2state pass
generated/operators_sim/11.4.3--simple_div_operator_sim.sv 4state pass
generated/operators_sim/11.4.3--simple_exp_operator_sim.sv 2state pass
@@ -2555,22 +2555,22 @@ generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 2state pass
generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 4state pass
generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 2state pass
generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 4state pass
-generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state fail
+generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state pass
generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 2state pass
generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 4state pass
generated/operators_sim/11.4.4--simple_gt_operator_sim.sv 2state pass
@@ -2579,14 +2579,14 @@ generated/operators_sim/11.4.4--simple_le_operator_sim.sv 2state pass
generated/operators_sim/11.4.4--simple_le_operator_sim.sv 4state pass
generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 2state pass
generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 4state pass
-generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state fail
+generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state pass
generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 2state pass
generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 4state pass
generated/operators_sim/11.4.5--simple_eq_xz_operator_sim.sv 2state pass
@@ -2595,18 +2595,18 @@ generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 2state pass
generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 4state pass
generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 2state pass
generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 4state pass
-generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state fail
-generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state fail
-generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state fail
-generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state fail
-generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state fail
+generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state pass
+generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state pass
+generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state pass
+generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state pass
+generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state pass
generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 2state pass
generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 4state pass
generated/operators_sim/11.4.8--simple_bit_or_operator_sim.sv 2state pass
diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs
index 3456a2c8be1..92e7fc934be 100644
--- a/crates/celox-backend-arm64/src/isel/tests.rs
+++ b/crates/celox-backend-arm64/src/isel/tests.rs
@@ -16,6 +16,7 @@ fn layout_for(address: AbsoluteAddr, width: usize, four_state: bool) -> MemoryLa
let total_size = plane_size * if four_state { 2 } else { 1 };
MemoryLayout {
trace: None,
+ settle: None,
four_state,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-wasm/src/lib.rs b/crates/celox-backend-wasm/src/lib.rs
index 5b146b76b5a..cc010904637 100644
--- a/crates/celox-backend-wasm/src/lib.rs
+++ b/crates/celox-backend-wasm/src/lib.rs
@@ -6488,6 +6488,7 @@ mod bit_count_tests {
MemoryLayout {
trace: None,
+ settle: None,
four_state,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests.rs b/crates/celox-backend-x86/src/backend/native/isel/tests.rs
index 19b3c5d844b..8d513fecf0b 100644
--- a/crates/celox-backend-x86/src/backend/native/isel/tests.rs
+++ b/crates/celox-backend-x86/src/backend/native/isel/tests.rs
@@ -16,6 +16,7 @@ use num_bigint::BigUint;
fn empty_layout() -> MemoryLayout {
MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs
index 7ed5e929daa..db8fe2abd3f 100644
--- a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs
+++ b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs
@@ -196,6 +196,7 @@ fn compile_bit_count(op: UnaryOp, source_width: usize, four_state: bool) -> Comp
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs
index aed958745c1..97a0c5cf9e5 100644
--- a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs
+++ b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs
@@ -800,6 +800,7 @@ fn narrowed_wide_binary_store_does_not_write_source_width() {
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
@@ -1130,6 +1131,7 @@ fn execute_unaligned_64_bit_load(dynamic: bool) -> u64 {
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
@@ -1295,6 +1297,7 @@ fn verify_scalar_alignment_matrix(dynamic: bool, four_state: bool) {
eu.verify();
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
@@ -1511,6 +1514,7 @@ fn verify_wide_alignment_matrix(dynamic: bool) {
eu.verify();
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs
index ddce616c2bb..37503198e34 100644
--- a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs
+++ b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs
@@ -511,6 +511,7 @@ fn lowers_shared_selector_roots_to_cached_indexed_table_loads() {
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs
index 51d1ae82584..3f94d1bda99 100644
--- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs
+++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs
@@ -660,6 +660,7 @@ fn narrow_wide_shift_uses_only_chunks_covered_by_the_result() {
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
@@ -836,6 +837,7 @@ fn wide_shift_result_is_canonical_before_mux_condition() {
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs
index fd1e45ec7e1..e0b20af1d78 100644
--- a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs
+++ b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs
@@ -1426,6 +1426,7 @@ mod tests {
.collect();
MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: MemoryLayoutMode::Packed,
unpacked_arrays: HashMap::default(),
diff --git a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs
index 437eff6db62..0c82cb95455 100644
--- a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs
+++ b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs
@@ -145,6 +145,7 @@ pub fn compile(recover: bool) -> CompiledUpdate {
)];
let layout = MemoryLayout {
trace: None,
+ settle: None,
four_state: false,
mode: celox_state_layout::MemoryLayoutMode::Packed,
offsets: [
diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs
index 7294c286a4e..7cb6fdda1da 100644
--- a/crates/celox-design/src/lib.rs
+++ b/crates/celox-design/src/lib.rs
@@ -616,6 +616,17 @@ impl std::fmt::Display for ProcessOrigin {
}
}
+/// When a procedural kernel is invoked by the runtime.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum ProcessKind {
+ /// Static declarations run before ordinary HDL procedures.
+ Initializer,
+ #[default]
+ Regular,
+ /// A final procedure runs only when simulation ends (IEEE 1800-2023 9.2.3).
+ Final,
+}
+
/// State through which one process kernel exchanges control with the runtime.
///
/// A process kernel is a resumable function. On entry it reads `resume` to
@@ -625,9 +636,9 @@ impl std::fmt::Display for ProcessOrigin {
/// checkpoints capture a suspended process.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProcessSlots {
- /// A static declaration initializer, executed before all HDL procedures.
- pub is_initializer: bool,
- /// This kernel originated from an edge procedure and must execute in Simulation.
+ /// The phase in which the runtime invokes this kernel.
+ pub kind: ProcessKind,
+ /// This kernel requires Simulation's process scheduler rather than Simulator.
pub requires_timed_simulation: bool,
/// Every delay the kernel suspends for is a constant of at least one
/// time unit.
@@ -646,7 +657,7 @@ pub struct ProcessSlots {
impl ProcessSlots {
pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots {
ProcessSlots {
- is_initializer: self.is_initializer,
+ kind: self.kind,
requires_timed_simulation: self.requires_timed_simulation,
const_delays: self.const_delays,
program: self.program.map(&mut map),
@@ -1053,6 +1064,27 @@ pub struct RuntimeSchema {
/// Generated units that run an edge of an event with every derived
/// clock domain it reaches, for the events that have them.
pub derived_edges: Vec>,
+ /// The partitions of a partitioned combinational settle, when it is
+ /// partitioned.
+ pub settle_partitions: Option>,
+}
+
+/// A combinational settle split into partitions that run only when state
+/// they read changed since they last ran.
+///
+/// Byte `p` of `flags` is partition `p`'s dirty flag; the byte after the
+/// last partition's is the untracked byte, set once state may change
+/// without anyone setting flags (a retained raw view), after which every
+/// partition always runs.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SettlePartitions {
+ pub flags: A,
+ pub partitions: u32,
+ /// State the settle reads or writes, with the partitions to mark when
+ /// something other than the settle writes it. A written object lists
+ /// its writers as well, so that, as in a single pass, the settle
+ /// recomputes it.
+ pub marks: Vec<(A, Vec)>,
}
/// The process units that run the edges of one event together with its
@@ -1279,6 +1311,7 @@ impl Default for RuntimeSchema {
time_slots: Vec::new(),
scheduler: None,
derived_edges: Vec::new(),
+ settle_partitions: None,
}
}
}
diff --git a/crates/celox-frontend-core/src/lib.rs b/crates/celox-frontend-core/src/lib.rs
index 05e833c6575..5a208e3e8c1 100644
--- a/crates/celox-frontend-core/src/lib.rs
+++ b/crates/celox-frontend-core/src/lib.rs
@@ -18,7 +18,7 @@ pub use shared::{
pub use trace::{FrontendTrace, FrontendTraceOptions, TraceSimModule};
pub use symbolic::flattening;
-pub use symbolic::parallel::ParallelScheduleOptions;
+pub use symbolic::parallel::{ParallelScheduleOptions, SettlePartitionMode};
pub(crate) type HashMap = fxhash::FxHashMap;
pub(crate) type HashSet = fxhash::FxHashSet;
diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs
index f955fda9e87..c5c89c1135f 100644
--- a/crates/celox-frontend-core/src/sdk.rs
+++ b/crates/celox-frontend-core/src/sdk.rs
@@ -1729,7 +1729,7 @@ fn lower_processes(
for (index, process) in artifact.processes().iter().enumerate() {
let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()];
let slots = ProcessSlots {
- is_initializer: false,
+ kind: celox_design::ProcessKind::Regular,
requires_timed_simulation: false,
const_delays: false,
program: None,
diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs
index 2e8b3db9b56..aa5104fcb87 100644
--- a/crates/celox-frontend-core/src/symbolic/assembly.rs
+++ b/crates/celox-frontend-core/src/symbolic/assembly.rs
@@ -8,7 +8,7 @@ use crate::symbolic::artifact::{
use crate::{
FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap,
HashSet, InstancePath, ParallelScheduleOptions, ParserError, ScheduledRtl, ScheduledRtlOutput,
- SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening,
+ SettlePartitionMode, SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening,
};
use celox_design::{
BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign,
@@ -1507,6 +1507,29 @@ pub fn schedule_symbolic_rtl_reporting_loops(
}
}
let parallel_comb_blocks = parallel.enabled().then(|| comb_blocks.clone());
+ // The flag object of a partitioned settle is declared once the
+ // partitions are known; reserve its address now.
+ let root_instance = expanded[&InstancePath(Vec::new())];
+ let settle_flags =
+ settle_partitioning(parallel, &comb_blocks, &global_arena, eval_apply_ffs.len()).map(
+ |target_cost| {
+ let var_id = SourceVarId(
+ modules[&root_id]
+ .variables
+ .keys()
+ .map(|id| id.0 + 1)
+ .max()
+ .unwrap_or(0),
+ );
+ scheduler::SettlePartitioning {
+ flags: AbsoluteAddr {
+ instance_id: root_instance,
+ var_id,
+ },
+ target_cost,
+ }
+ },
+ );
let sched_start = flatten_timing.then(std::time::Instant::now);
let schedule = match scheduler::sort_with_unpacked_element_widths(
comb_blocks,
@@ -1517,6 +1540,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
&var_widths,
&unpacked_element_widths,
next_runtime_error_code,
+ settle_flags,
) {
Ok(schedule) => schedule,
Err(error) => {
@@ -1557,6 +1581,19 @@ pub fn schedule_symbolic_rtl_reporting_loops(
});
}
};
+ let settle_partitions = schedule.partitions.clone();
+
+ let settle_flags = settle_flags.filter(|_| !settle_partitions.is_empty());
+ if let Some(settle) = &settle_flags {
+ // The flags carry what changed from one settle to the next.
+ persistent_comb_state.insert(settle.flags);
+ declare_settle_flags(
+ &mut modules,
+ root_id,
+ settle.flags.var_id,
+ settle_partitions.len(),
+ );
+ }
let object_sizes = super::parallel::ObjectSizes {
widths: &var_widths,
element_widths: &unpacked_element_widths,
@@ -1677,7 +1714,10 @@ pub fn schedule_symbolic_rtl_reporting_loops(
// events; that copy lets the FF part use comb values in registers.
// Beyond that the copies would multiply the design by its event count,
// so the ticks share the one `eval_comb` program instead.
- let merge_comb_apply = eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS;
+ // A merged program drops comb stores the next full settle would redo;
+ // a partitioned settle keeps what its skipped partitions stored.
+ let merge_comb_apply =
+ eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS && settle_flags.is_none();
let mut eval_comb_apply_ffs = HashMap::default();
let mut fused_direct_ff_writes = HashMap::default();
if let (
@@ -1920,6 +1960,21 @@ pub fn schedule_symbolic_rtl_reporting_loops(
.chain(bound_initials)
.map(|(_, init)| init)
.collect();
+ if let Some(settle) = &settle_flags {
+ // Every partition runs at the first settle.
+ let partitions = settle_partitions.len();
+ let value = (0..partitions).fold(BigUint::default(), |value, partition| {
+ value | (BigUint::from(1u8) << (partition * 8))
+ });
+ initial_memory_values.push(InitialStateValue {
+ address: settle.flags,
+ data: InitialStateData::Packed {
+ value,
+ mask: BigUint::default(),
+ written_mask: (BigUint::from(1u8) << ((partitions + 1) * 8)) - 1u8,
+ },
+ });
+ }
let state_objects: HashMap = instance_modules
.iter()
.flat_map(|(&instance_id, module_id)| {
@@ -1940,7 +1995,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
.collect();
let declaration_startup = processes
.iter()
- .any(|process| process.slots.is_initializer)
+ .any(|process| process.slots.kind == celox_design::ProcessKind::Initializer)
.then(|| {
let targets: BTreeSet<_> = folded_initials.iter().map(|init| init.address).collect();
let mut reset = targets
@@ -2326,6 +2381,32 @@ pub fn schedule_symbolic_rtl_reporting_loops(
let active_commits: Vec = active_commits.into_iter().map(project).collect();
let time_slots: Vec = time_slots.into_iter().map(project).collect();
let root_instance = expanded[&InstancePath(Vec::new())];
+ let settle_partitions = settle_flags.map(|settle| {
+ let mut marks: HashMap> = HashMap::default();
+ for (index, partition) in settle_partitions.iter().enumerate() {
+ let index = index as u32;
+ for addr in &partition.reads {
+ if let Some(&state) = source_to_state.get(addr) {
+ marks.entry(state).or_default().insert(index);
+ }
+ }
+ for addr in &partition.writes {
+ if let Some(&state) = source_to_state.get(addr) {
+ marks.entry(state).or_default().insert(index);
+ }
+ }
+ }
+ let mut marks = marks
+ .into_iter()
+ .map(|(state, partitions)| (state, partitions.into_iter().collect()))
+ .collect::>();
+ marks.sort_unstable();
+ celox_design::SettlePartitions {
+ flags: project(settle.flags),
+ partitions: settle_partitions.len() as u32,
+ marks,
+ }
+ });
let scheduler = scheduler_slots.map(|slots| celox_design::SchedulerSchema {
slots: slots.map(|var_id| {
project(AbsoluteAddr {
@@ -2468,6 +2549,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
time_slots,
scheduler,
derived_edges: Vec::new(),
+ settle_partitions,
},
};
@@ -2485,6 +2567,77 @@ pub fn schedule_symbolic_rtl_reporting_loops(
})
}
+/// Smallest combinational program, in expression nodes, whose settle
+/// [`SettlePartitionMode::Estimated`] partitions.
+const MIN_PARTITIONED_SETTLE_COST: usize = 20_000;
+/// Expression nodes per partition of an estimated partitioned settle.
+const SETTLE_PARTITION_COST: usize = 2_000;
+
+/// The cost per partition of a partitioned settle of `comb_blocks`, or
+/// `None` to keep one pass.
+///
+/// A partition costs a flag test per settle and flag stores in every writer
+/// of what it reads, and pays off when most of the program is idle in most
+/// settles. A design with few event domains drives most of its logic from
+/// one clock, so it keeps the single pass, as does a small program.
+fn settle_partitioning(
+ parallel: &ParallelScheduleOptions,
+ comb_blocks: &[LogicPath],
+ arena: &SLTNodeArena,
+ events: usize,
+) -> Option {
+ // Lane-partitioned kernels run the comb program as lane tasks.
+ if parallel.enabled() {
+ return None;
+ }
+ match parallel.settle {
+ SettlePartitionMode::Off => None,
+ SettlePartitionMode::Always => Some(1),
+ SettlePartitionMode::Estimated => {
+ if events <= MERGED_COMB_APPLY_EVENTS {
+ return None;
+ }
+ let cost: usize = comb_blocks
+ .iter()
+ .map(|path| scheduler::path_cost(arena, path))
+ .sum();
+ (cost >= MIN_PARTITIONED_SETTLE_COST).then_some(SETTLE_PARTITION_COST)
+ }
+ }
+}
+
+/// Declare the flags of a settle of `partitions` partitions, one byte each
+/// plus the untracked byte, as a hidden variable of the top module.
+fn declare_settle_flags(
+ modules: &mut HashMap,
+ root: ModuleId,
+ var_id: SourceVarId,
+ partitions: usize,
+) {
+ let width = (partitions + 1) * 8;
+ let variables = &mut modules.get_mut(&root).expect("top module").variables;
+ variables.insert(
+ var_id,
+ crate::symbolic::artifact::SymbolicVariable {
+ path: vec!["$settle".to_string(), "flags".to_string()],
+ kind: crate::VariableKind::Variable,
+ signed: false,
+ metadata: VariableMetadata {
+ width,
+ is_4state: false,
+ kind: DomainKind::Other,
+ type_kind: celox_design::PortTypeKind::Bit,
+ array_dims: Vec::new(),
+ value_kind: Default::default(),
+ },
+ packed_dims: vec![width],
+ unpacked_ranges: Vec::new(),
+ source: None,
+ module_affiliated: false,
+ },
+ );
+}
+
/// Declare the hidden objects a compiled scheduler exchanges with the
/// runtime (`RuntimeSchema::scheduler`) as variables of the top module, for
/// a design with `process_count` process kernels. A design without kernels
diff --git a/crates/celox-frontend-core/src/symbolic/parallel.rs b/crates/celox-frontend-core/src/symbolic/parallel.rs
index dccfada3730..f0824ef3d88 100644
--- a/crates/celox-frontend-core/src/symbolic/parallel.rs
+++ b/crates/celox-frontend-core/src/symbolic/parallel.rs
@@ -27,6 +27,22 @@ pub struct ParallelScheduleOptions {
/// Smallest accepted estimated speedup of a partitioned phase, in
/// percent of its single-lane cost.
pub minimum_speedup_percent: u64,
+ /// Whether the combinational settle may be split into partitions that
+ /// run only when what they read changed. Only a host that reports its
+ /// writes and instruments the units it generates may request it.
+ pub settle: SettlePartitionMode,
+}
+
+/// Whether a settle is partitioned ([`ParallelScheduleOptions::settle`]).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum SettlePartitionMode {
+ /// One pass over the whole combinational program.
+ #[default]
+ Off,
+ /// Partition designs with many event domains and a large program.
+ Estimated,
+ /// Partition every program into the smallest partitions. For tests.
+ Always,
}
impl ParallelScheduleOptions {
@@ -35,6 +51,7 @@ impl ParallelScheduleOptions {
lanes: 1,
synchronization_cost: 400,
minimum_speedup_percent: 125,
+ settle: SettlePartitionMode::Off,
};
/// Request `lanes` simulation lanes with the default cost model.
diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs
index b5b0d177f4c..11a49c86e24 100644
--- a/crates/celox-frontend-sv/src/lowering.rs
+++ b/crates/celox-frontend-sv/src/lowering.rs
@@ -1348,7 +1348,7 @@ fn kernel_window_writes(
for process in module
.initial_processes()
.iter()
- .filter(|process| !process.is_initializer())
+ .filter(|process| !process.is_initializer() && !process.is_final())
{
let body = process.body();
let first = if process.repeats() {
@@ -4978,6 +4978,7 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig
let construct = match process.site() {
Some(site) => site.construct,
None if process.is_initializer() => "declaration initializer",
+ None if process.is_final() => "final",
None if process.repeats() => "always",
None => "initial",
};
@@ -4988,9 +4989,9 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig
}
}
-/// The `initial` blocks and declaration initializers (IEEE 1800-2023 9.2.1,
-/// 10.5): the initial state they define, and the processes that run the
-/// others from time zero.
+/// Lower declaration initializers and procedural kernels. Final procedures
+/// retain kernels but execute only at simulation termination (9.2.3); they
+/// must never contribute folded initial state.
///
/// A block whose writes have constant values defines initial state, with
/// the hidden variables used while executing it discarded. Declaration
@@ -5062,7 +5063,10 @@ fn lower_initial_processes(
// initial state. A program's `initial` procedure runs in the reactive
// region set (IEEE 1800-2023 24.3.1), after the design's processes of
// time zero, so it is not folded either.
- if process.repeats() || (module.is_program() && !process.is_initializer()) {
+ if process.is_final()
+ || process.repeats()
+ || (module.is_program() && !process.is_initializer())
+ {
runtime.push((process, random_seed));
continue;
}
@@ -5138,8 +5142,8 @@ fn lower_initial_processes(
id
};
ProcessSlots {
- is_initializer: process.is_initializer(),
- requires_timed_simulation: process.is_scheduled_edge(),
+ kind: process.kind(),
+ requires_timed_simulation: process.is_scheduled_edge() || process.is_final(),
const_delays: false,
program: None,
resume: declare("resume", PROCESS_RESUME_WIDTH),
@@ -5155,10 +5159,10 @@ fn lower_initial_processes(
let program = slots
.iter()
.zip(&runtime)
- .find(|(_, (process, _))| !process.is_initializer())
+ .find(|(_, (process, _))| !process.is_initializer() && !process.is_final())
.map(|(slots, _)| slots.status);
for (slots, (process, _)) in slots.iter_mut().zip(&runtime) {
- if !process.is_initializer() {
+ if !process.is_initializer() && !process.is_final() {
slots.program = program;
}
}
@@ -10725,7 +10729,7 @@ endmodule
.runtime_schema
.processes
.iter()
- .filter(|process| !process.is_initializer)
+ .filter(|process| process.kind != celox_design::ProcessKind::Initializer)
.count()
}
diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs
index 94ba20cf12e..05bb918ca1e 100644
--- a/crates/celox-runtime/src/backend.rs
+++ b/crates/celox-runtime/src/backend.rs
@@ -119,6 +119,27 @@ pub trait SimBackend {
assert!(offset + bytes.len() <= len, "write past the memory image");
// Safety: the backend exposes `len` writable bytes at `ptr`.
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.add(offset), bytes.len()) };
+ self.mark_settle_range(offset, bytes.len());
+ }
+
+ /// Set the flags of the settle partitions reading `offset..offset + len`,
+ /// which the host wrote.
+ fn mark_settle_range(&mut self, offset: usize, len: usize) {
+ if let Some(settle) = self.layout().settle.as_ref() {
+ let (ptr, _) = self.memory_as_ptr();
+ // SAFETY: the settle layout describes this backend's state image.
+ unsafe { settle.mark_range(ptr.cast_mut(), offset, len) };
+ }
+ }
+
+ /// From now on run every settle partition on every settle: a raw view
+ /// of the state can change it without reporting.
+ fn mark_settle_untracked(&mut self) {
+ if let Some(settle) = self.layout().settle.as_ref() {
+ let (ptr, _) = self.memory_as_ptr();
+ // SAFETY: the settle layout describes this backend's state image.
+ unsafe { settle.mark_untracked(ptr.cast_mut()) };
+ }
}
/// Return an opaque owner that keeps the memory allocation alive.
@@ -200,17 +221,18 @@ pub trait SimBackend {
/// Called by host setters, which share the generated-store notification ABI.
fn mark_vcd_signal(&mut self, signal: SignalRef) {
+ let len = signal.array_layout.map_or_else(
+ || celox_state_layout::get_byte_size(signal.width),
+ |array| array.element_count * array.element_stride,
+ );
if let Some(trace) = self.layout().trace.as_ref() {
- let len = signal.array_layout.map_or_else(
- || celox_state_layout::get_byte_size(signal.width),
- |array| array.element_count * array.element_stride,
- );
let (ptr, _) = self.memory_as_ptr();
// SAFETY: layout homes and metadata fit in the writable state image.
unsafe {
trace.mark_range(ptr.cast_mut(), signal.offset, len);
}
}
+ self.mark_settle_range(signal.offset, len);
}
}
diff --git a/crates/celox-runtime/src/error.rs b/crates/celox-runtime/src/error.rs
index 33603a87ee6..5cb9f3f2f03 100644
--- a/crates/celox-runtime/src/error.rs
+++ b/crates/celox-runtime/src/error.rs
@@ -5,6 +5,11 @@ pub enum SimulatorErrorCode {
DetectedTrueLoopAt {
signals: Vec,
},
+ /// `$fatal` also implicitly requests simulation termination.
+ Fatal {
+ message: String,
+ signals: Vec,
+ },
Runtime {
message: String,
signals: Vec,
@@ -36,6 +41,16 @@ impl PartialEq for SimulatorErrorCode {
signals: sb,
},
) => a == b && sa == sb,
+ (
+ Self::Fatal {
+ message: a,
+ signals: sa,
+ },
+ Self::Fatal {
+ message: b,
+ signals: sb,
+ },
+ ) => a == b && sa == sb,
(Self::NotAnEvent(a), Self::NotAnEvent(b)) => a == b,
_ => false,
}
@@ -54,8 +69,12 @@ impl std::fmt::Display for SimulatorErrorCode {
Self::DetectedTrueLoopAt { signals } => {
write!(f, "Detected True Loop: {}", signals.join(", "))
}
- Self::Runtime { message, signals } if signals.is_empty() => write!(f, "{message}"),
- Self::Runtime { message, signals } => {
+ Self::Fatal { message, signals } | Self::Runtime { message, signals }
+ if signals.is_empty() =>
+ {
+ write!(f, "{message}")
+ }
+ Self::Fatal { message, signals } | Self::Runtime { message, signals } => {
write!(f, "{}: {}", message, signals.join(", "))
}
Self::InternalError => write!(f, "Internal Error"),
diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs
index 064c9049bad..99e07af4d2a 100644
--- a/crates/celox-runtime/src/schedule.rs
+++ b/crates/celox-runtime/src/schedule.rs
@@ -198,7 +198,7 @@ impl ResolvedSchedule {
.processes
.iter()
.map(|process| ProcessRefs {
- is_initializer: process.slots.is_initializer,
+ kind: process.slots.kind,
program: process.slots.program.as_ref().map(resolve),
resume: resolve(&process.slots.resume),
starts_with_event_wait: process.slots.requires_timed_simulation,
@@ -312,7 +312,9 @@ impl ResolvedSchedule {
program_processes: processes
.iter()
.enumerate()
- .filter(|(_, process)| process.program.is_some())
+ .filter(|(_, process)| {
+ process.kind == celox_design::ProcessKind::Regular && process.program.is_some()
+ })
.map(|(index, _)| index)
.collect(),
processes,
diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs
index 7173050bca6..852dd20dd2e 100644
--- a/crates/celox-runtime/src/simulation/compiled.rs
+++ b/crates/celox-runtime/src/simulation/compiled.rs
@@ -161,6 +161,10 @@ impl SimulationState {
}
Err(Halt::Stop) => Ok(Some(self.scheduler.time)),
Err(Halt::Error(error)) => {
+ if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
+ let _ = self.finalize_terminal(executor);
+ return Err(error);
+ }
let _ = self.finish_timed_boundary(executor, self.scheduler.time);
let _ = executor.flush_output();
Err(error)
diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs
index dded48af181..a0e68d89208 100644
--- a/crates/celox-runtime/src/simulation/mod.rs
+++ b/crates/celox-runtime/src/simulation/mod.rs
@@ -10,6 +10,7 @@ mod persist;
mod process;
mod round;
mod stats;
+mod terminal;
mod time;
mod wait;
@@ -146,6 +147,8 @@ pub struct SimulationState {
host_pending: bool,
/// A process requested the end of the simulation.
finished: bool,
+ /// Next final procedure while terminal execution is suspended by `$stop`.
+ finalizing: Option,
/// A process suspended the simulation (`$stop`) in the last step.
stopped: bool,
/// The round a `$stop` suspended, which the next step continues.
@@ -193,7 +196,9 @@ impl SimulationState {
.processes
.iter()
.enumerate()
- .filter_map(|(index, process)| process.is_initializer.then_some(index))
+ .filter_map(|(index, process)| {
+ (process.kind == celox_design::ProcessKind::Initializer).then_some(index)
+ })
.collect();
let declarations_pending = !declaration_processes.is_empty();
let mut state = Self {
@@ -202,6 +207,7 @@ impl SimulationState {
last_clock_unknown: BitSet::new(),
four_state: backend.layout().four_state,
process_wakeups: (0..model.processes.len())
+ .filter(|&index| model.processes[index].kind != celox_design::ProcessKind::Final)
.map(|process| Reverse((0, process)))
.collect(),
model,
@@ -210,6 +216,7 @@ impl SimulationState {
declarations_pending,
host_pending: false,
finished: false,
+ finalizing: None,
stopped: false,
suspended: None,
scratch: None,
@@ -253,6 +260,13 @@ impl SimulationState {
E: SimulationExecutor,
{
self.stopped = false;
+ if self.finalizing.is_some() {
+ if self.scheduler.time > limit {
+ return Ok(None);
+ }
+ self.finalize_terminal(executor)?;
+ return Ok(Some(self.scheduler.time));
+ }
match self.step_time(executor, limit) {
Ok(time) => Ok(time),
Err(Halt::Finish) => {
@@ -262,6 +276,10 @@ impl SimulationState {
// The time slot goes on when the simulation continues.
Err(Halt::Stop) => Ok(Some(self.scheduler.time)),
Err(Halt::Error(error)) => {
+ if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
+ let _ = self.finalize_terminal(executor);
+ return Err(error);
+ }
// Preserve the primary runtime failure even if diagnostic
// waveform output also fails. This does not resume processes.
let _ = self.finish_timed_boundary(executor, self.scheduler.time);
@@ -312,7 +330,10 @@ impl SimulationState {
// A process the scheduler does not run waits: the slot stays in
// the reference loop. Test that first, as designs with such
// processes fail it at every step.
- let compiled = if compiles && self.process_state.waiters.len() <= waiting_kernels {
+ let compiled = if self.finalizing.is_none()
+ && compiles
+ && self.process_state.waiters.len() <= waiting_kernels
+ {
self.compiled_limit(executor, end, observer.one_slot())
} else {
None
@@ -405,9 +426,14 @@ impl SimulationState {
{
match executor.try_finish_timed_step(time) {
Ok(()) => Ok(()),
- Err(Halt::Error(error)) => Err(error),
+ Err(Halt::Error(error)) => {
+ if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
+ let _ = self.finalize_terminal(executor);
+ }
+ Err(error)
+ }
Err(Halt::Finish) => {
- self.finish_checked(executor)?;
+ self.finalize_terminal(executor)?;
Ok(())
}
Err(Halt::Stop) => {
@@ -417,34 +443,6 @@ impl SimulationState {
}
}
- fn finish_checked(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode>
- where
- E: SimulationExecutor,
- {
- self.finished = true;
- executor.try_freeze()
- }
-
- /// Once $finish is consumed, output errors must not make execution resumable.
- pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode>
- where
- E: SimulationExecutor,
- {
- self.finished = true;
- let output = self.finish_timed_boundary(executor, self.scheduler.time);
- let frozen = executor.try_freeze();
- output.and(frozen)
- }
-
- /// End the simulation where it is.
- pub fn finish(&mut self, executor: &mut E)
- where
- E: SimulationExecutor,
- {
- self.finished = true;
- executor.freeze();
- }
-
/// Whether a process requested the end of the simulation.
pub fn is_finished(&self) -> bool {
self.finished
@@ -461,7 +459,8 @@ impl SimulationState {
/// Whether the simulation is suspended in the middle of a time slot, so
/// that its scheduling state cannot be captured.
pub fn is_suspended(&self) -> bool {
- self.suspended.is_some() || (self.stopped && self.declarations_pending)
+ self.suspended.is_some()
+ || (self.stopped && (self.declarations_pending || self.finalizing.is_some()))
}
/// Settle externally driven state against the previous edge baseline even
@@ -486,6 +485,10 @@ impl SimulationState {
}
Err(Halt::Stop) => Ok(Some(self.scheduler.time)),
Err(Halt::Error(error)) => {
+ if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
+ let _ = self.finalize_terminal(executor);
+ return Err(error);
+ }
// Preserve the primary runtime failure even if diagnostic
// waveform output also fails. This does not resume processes.
let _ = self.finish_timed_boundary(executor, self.scheduler.time);
@@ -556,7 +559,7 @@ impl SimulationState {
return None;
}
// Host writes are work of the current time.
- if self.host_pending {
+ if self.host_pending || self.finalizing.is_some() {
return Some(self.scheduler.time);
}
self.next_work_time()
diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs
index aa0a94ff8e9..d652d9f9e82 100644
--- a/crates/celox-runtime/src/simulation/persist.rs
+++ b/crates/celox-runtime/src/simulation/persist.rs
@@ -26,6 +26,7 @@ impl SimulationState {
declarations_pending: self.declarations_pending,
host_pending: self.host_pending,
finished: self.finished,
+ finalizing: self.finalizing,
}
}
@@ -63,6 +64,7 @@ impl SimulationState {
self.declarations_pending = snapshot.declarations_pending;
self.host_pending = snapshot.host_pending;
self.finished = snapshot.finished;
+ self.finalizing = snapshot.finalizing;
self.stopped = false;
self.suspended = None;
Ok(())
@@ -190,17 +192,14 @@ impl SimulationState {
.map(|(process, time)| Reverse((time, process)))
.collect();
self.process_state = parts.process_state;
- self.declarations_pending = self
- .process_wakeups
- .iter()
- .any(|Reverse((_, index))| self.model.processes[*index].is_initializer)
- || self
- .process_state
- .ready
- .iter()
- .any(|&index| self.model.processes[index].is_initializer);
+ self.declarations_pending = self.process_wakeups.iter().any(|Reverse((_, index))| {
+ self.model.processes[*index].kind == celox_design::ProcessKind::Initializer
+ }) || self.process_state.ready.iter().any(|&index| {
+ self.model.processes[index].kind == celox_design::ProcessKind::Initializer
+ });
self.host_pending = parts.host_pending;
self.finished = parts.finished;
+ self.finalizing = None;
self.stopped = false;
self.suspended = None;
}
@@ -218,6 +217,7 @@ pub struct SimulationSnapshot {
declarations_pending: bool,
host_pending: bool,
finished: bool,
+ finalizing: Option,
}
impl Clone for SimulationSnapshot {
@@ -233,6 +233,7 @@ impl Clone for SimulationSnapshot {
declarations_pending: self.declarations_pending,
host_pending: self.host_pending,
finished: self.finished,
+ finalizing: self.finalizing,
}
}
}
@@ -300,6 +301,7 @@ impl SimulationState {
declarations_pending: self.declarations_pending,
host_pending: self.host_pending,
finished: self.finished,
+ finalizing: self.finalizing,
stopped: self.stopped,
suspended: self.suspended.is_some(),
}
@@ -329,6 +331,7 @@ pub struct ScheduleKey {
pub declarations_pending: bool,
pub host_pending: bool,
pub finished: bool,
+ pub finalizing: Option,
pub stopped: bool,
pub suspended: bool,
}
diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs
index bc74b2729d8..e8a7324dabd 100644
--- a/crates/celox-runtime/src/simulation/process.rs
+++ b/crates/celox-runtime/src/simulation/process.rs
@@ -29,7 +29,12 @@ impl SimulationState {
self.stopped = true;
Ok(())
}
- Err(Halt::Error(error)) => Err(error),
+ Err(Halt::Error(error)) => {
+ if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
+ let _ = self.finalize_terminal(executor);
+ }
+ Err(error)
+ }
}
}
diff --git a/crates/celox-runtime/src/simulation/terminal.rs b/crates/celox-runtime/src/simulation/terminal.rs
new file mode 100644
index 00000000000..8d2553e935d
--- /dev/null
+++ b/crates/celox-runtime/src/simulation/terminal.rs
@@ -0,0 +1,99 @@
+//! Terminal procedures run sequentially, without scheduling another HDL event.
+
+use celox_design::{HostRequestKind, ProcessKind, ProcessStatus};
+
+use super::{SimulationExecutor, SimulationState};
+use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt};
+
+impl SimulationState {
+ /// Finish once, running final procedures before flushing output and freezing.
+ /// A `$stop` in a final procedure suspends this phase; the next step resumes it.
+ pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode>
+ where
+ E: SimulationExecutor,
+ {
+ if self.finished {
+ return Ok(());
+ }
+ self.stopped = false;
+ if self.finalizing.is_none() {
+ // An explicit host finish may replace a stopped ordinary round.
+ self.suspended = None;
+ self.host_pending = false;
+ self.finalizing = Some(0);
+ }
+ let result = self.run_final_procedures(executor);
+ if matches!(result, Err(Halt::Stop)) {
+ self.stopped = true;
+ return Ok(());
+ }
+ // A failed final procedure or output flush cannot make termination resumable.
+ self.finished = true;
+ self.finalizing = None;
+ let output = self.finish_timed_boundary(executor, self.scheduler.time);
+ let frozen = executor.try_freeze();
+ match result {
+ Ok(()) | Err(Halt::Finish) => output.and(frozen),
+ Err(Halt::Error(error)) => Err(error),
+ Err(Halt::Stop) => unreachable!(),
+ }
+ }
+
+ /// Explicitly end simulation at its current time. Merely exhausting currently
+ /// scheduled work does not end an externally driven simulation.
+ pub fn finish(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode>
+ where
+ E: SimulationExecutor,
+ {
+ self.finalize_terminal(executor)
+ }
+
+ fn run_final_procedures(&mut self, executor: &mut E) -> Result<(), Halt>
+ where
+ E: SimulationExecutor,
+ {
+ let mut returns = 0;
+ while let Some(index) = self
+ .finalizing
+ .filter(|&index| index < self.model.processes.len())
+ {
+ let process = &self.model.processes[index];
+ if process.kind != ProcessKind::Final {
+ self.finalizing = Some(index + 1);
+ continue;
+ }
+ executor.run_process(index)?;
+ returns += 1;
+ self.charge(returns, Some(index))?;
+ let status: u8 = executor.backend().get_as(process.status);
+ match ProcessStatus::from_code(status) {
+ Some(ProcessStatus::Done) => self.finalizing = Some(index + 1),
+ Some(ProcessStatus::Finish) => return Err(Halt::Finish),
+ Some(ProcessStatus::Stop) => return Err(Halt::Stop),
+ Some(ProcessStatus::HostRequest) => {
+ let encoded: u64 = executor.backend().get_as(process.delay);
+ let (kind, site) = HostRequestKind::decode(encoded)
+ .ok_or(SimulatorErrorCode::InternalError)?;
+ let request = process
+ .host_requests
+ .iter()
+ .filter(|request| request.kind == kind)
+ .nth(site as usize)
+ .ok_or(SimulatorErrorCode::InternalError)?;
+ executor.host_request(request, self.scheduler.time)?;
+ }
+ // Yield is an implementation boundary, not an HDL timing control.
+ // NBA events created by a final never run after termination (9.2.3).
+ Some(ProcessStatus::Yield | ProcessStatus::Nba) => {}
+ _ => {
+ return Err(SimulatorErrorCode::Runtime {
+ message: "final procedure cannot suspend for HDL timing".into(),
+ signals: Vec::new(),
+ }
+ .into());
+ }
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs
index e25822ae243..89f621c1e8d 100644
--- a/crates/celox-runtime/src/simulation/time.rs
+++ b/crates/celox-runtime/src/simulation/time.rs
@@ -299,7 +299,10 @@ impl SimulationState {
if self.finished {
return None;
}
- if !self.process_state.ready.is_empty() || !self.process_state.reactive.is_empty() {
+ if self.finalizing.is_some()
+ || !self.process_state.ready.is_empty()
+ || !self.process_state.reactive.is_empty()
+ {
return Some(self.scheduler.time);
}
let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time);
diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs
index 9edb4ed0927..20cdc112493 100644
--- a/crates/celox-runtime/src/timing.rs
+++ b/crates/celox-runtime/src/timing.rs
@@ -153,7 +153,7 @@ pub struct NbaSiteRefs {
/// Control slots and sites of one process kernel.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProcessRefs {
- pub is_initializer: bool,
+ pub kind: celox_design::ProcessKind,
/// The status slot naming the program instance of a program kernel
/// ([`celox_design::ProcessSlots::program`]), which runs in the reactive
/// region set.
@@ -175,7 +175,7 @@ impl ProcessRefs {
/// A process without wait or nonblocking sites.
pub fn new(status: SignalRef, delay: SignalRef) -> Self {
Self {
- is_initializer: false,
+ kind: celox_design::ProcessKind::Regular,
program: None,
resume: status,
starts_with_event_wait: false,
diff --git a/crates/celox-sir-opt/src/lib.rs b/crates/celox-sir-opt/src/lib.rs
index 352f3cbc005..57d173ca032 100644
--- a/crates/celox-sir-opt/src/lib.rs
+++ b/crates/celox-sir-opt/src/lib.rs
@@ -102,5 +102,6 @@ pub fn optimize(
mod policy;
pub use policy::{
- OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SirDiagnostics, SirPass,
+ OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SettlePartition, SirDiagnostics,
+ SirPass,
};
diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs
index 7ec294253c5..8d6b6973002 100644
--- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs
+++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs
@@ -44,6 +44,14 @@ struct StoreCandidate {
struct GlobalIdentityFacts {
accesses: HashMap,
stores: Vec,
+ /// In a partitioned settle, where each address is loaded and the
+ /// immediate dominators of every unit (see [`reads_follow_store`]).
+ settle_loads: Option,
+}
+
+struct SettleLoads {
+ sites: HashMap>,
+ immediate_dominators: Vec>,
}
/// Analyze all combinational units before selecting any whole-program address
@@ -69,15 +77,27 @@ pub(in crate::optimizer) fn optimize_program_identity_stores(
);
blocked_aliases.extend(program.design.initial_state.iter().map(|init| init.address));
+ let settle_flags = settle_flags(program);
optimize_eval_comb_identity_stores(
&mut program.sir.eval_comb,
&metadata,
&blocked_aliases,
program.layout_requirements.state_aliases(),
four_state,
+ settle_flags,
)
}
+/// The flags of a partitioned settle, whose guards skip a partition only
+/// when it would store what memory already holds.
+fn settle_flags(program: &OptimizationContext) -> Option {
+ program
+ .runtime_schema
+ .settle_partitions
+ .as_ref()
+ .map(|settle| settle.flags)
+}
+
fn address_metadata(program: &OptimizationContext) -> HashMap {
program
.design
@@ -101,8 +121,9 @@ fn optimize_eval_comb_identity_stores(
blocked_aliases: &HashSet,
existing_aliases: &HashMap,
four_state: bool,
+ settle_flags: Option,
) -> HashMap {
- let facts = collect_global_facts(units, metadata, four_state);
+ let facts = collect_global_facts(units, metadata, four_state, settle_flags);
let aliases = select_aliases(
&facts,
metadata,
@@ -129,20 +150,36 @@ pub(crate) fn retain_final_identity_aliases(program: &mut OptimizationContext, f
let aliases = program.layout_requirements.state_aliases().clone();
let mut valid = aliases.keys().copied().collect::>();
+ let settle_flags = settle_flags(program);
retain_aliases_valid_for_units(
&program.sir.eval_comb,
&aliases,
&metadata,
four_state,
+ settle_flags,
&mut valid,
);
for units in program.sir.eval_comb_apply_ffs.values() {
- retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid);
+ retain_aliases_valid_for_units(
+ units,
+ &aliases,
+ &metadata,
+ four_state,
+ settle_flags,
+ &mut valid,
+ );
}
// The lane-partitioned combinational kernel is one more projection of the
// same comb logic, lowered and optimized independently.
with_parallel_comb_units(program, |units| {
- retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid);
+ retain_aliases_valid_for_units(
+ units,
+ &aliases,
+ &metadata,
+ four_state,
+ settle_flags,
+ &mut valid,
+ );
});
program
.layout_requirements
@@ -190,17 +227,31 @@ pub(crate) fn remove_final_identity_alias_stores(
return;
}
let metadata = address_metadata(program);
+ let settle_flags = settle_flags(program);
remove_proven_alias_stores(
&mut program.sir.eval_comb,
validated_aliases,
&metadata,
four_state,
+ settle_flags,
);
for units in program.sir.eval_comb_apply_ffs.values_mut() {
- remove_proven_alias_stores(units, validated_aliases, &metadata, four_state);
+ remove_proven_alias_stores(
+ units,
+ validated_aliases,
+ &metadata,
+ four_state,
+ settle_flags,
+ );
}
with_parallel_comb_units(program, |units| {
- remove_proven_alias_stores(units, validated_aliases, &metadata, four_state);
+ remove_proven_alias_stores(
+ units,
+ validated_aliases,
+ &metadata,
+ four_state,
+ settle_flags,
+ );
});
}
@@ -263,9 +314,10 @@ fn retain_aliases_valid_for_units(
aliases: &HashMap,
metadata: &HashMap,
four_state: bool,
+ settle_flags: Option,
valid: &mut HashSet,
) {
- let facts = collect_global_facts(units, metadata, four_state);
+ let facts = collect_global_facts(units, metadata, four_state, settle_flags);
valid.retain(|alias| {
aliases
.get(alias)
@@ -316,8 +368,9 @@ fn remove_proven_alias_stores(
aliases: &HashMap,
metadata: &HashMap,
four_state: bool,
+ settle_flags: Option,
) {
- let facts = collect_global_facts(units, metadata, four_state);
+ let facts = collect_global_facts(units, metadata, four_state, settle_flags);
let mut sites = aliases
.iter()
.filter_map(|(&alias, &canonical)| proven_alias_store(&facts, alias, canonical).flatten())
@@ -373,7 +426,7 @@ fn analyze_eval_comb_aliases(
) -> HashMap {
// Phase 1: collect every read/write and every syntactic store candidate.
// No alias decision is made while the scan is incomplete.
- let facts = collect_global_facts(units, metadata, four_state);
+ let facts = collect_global_facts(units, metadata, four_state, None);
// Phase 2: require the completed global facts for both identity and
// duplicate-store proofs.
@@ -390,9 +443,14 @@ fn collect_global_facts(
units: &[ExecutionUnit],
metadata: &HashMap,
four_state: bool,
+ settle_flags: Option,
) -> GlobalIdentityFacts {
let mut accesses = HashMap::::default();
let mut stores = Vec::new();
+ let mut settle_loads = settle_flags.map(|_| SettleLoads {
+ sites: HashMap::default(),
+ immediate_dominators: units.iter().map(immediate_dominators).collect(),
+ });
for (eu_index, eu) in units.iter().enumerate() {
let mut defs = HashMap::default();
@@ -408,7 +466,7 @@ fn collect_global_facts(
// each candidate applies a sparse decrement map rather than cloning
// this whole table.
let use_counts = register_use_counts(eu);
- let must_execute = must_execute_blocks(eu);
+ let must_execute = must_execute_blocks(eu, settle_flags);
for block in eu.blocks.values() {
for (instruction_index, inst) in block.instructions.iter().enumerate() {
@@ -417,6 +475,13 @@ fn collect_global_facts(
increment_saturating(
&mut accesses.entry(address.absolute_addr()).or_default().reads,
);
+ if let Some(loads) = &mut settle_loads {
+ loads
+ .sites
+ .entry(address.absolute_addr())
+ .or_default()
+ .push((eu_index, block.id, instruction_index));
+ }
}
SIRInstruction::Store(
address,
@@ -477,6 +542,14 @@ fn collect_global_facts(
increment_saturating(
&mut accesses.entry(source.absolute_addr()).or_default().reads,
);
+ if let Some(loads) = &mut settle_loads {
+ // A commit reads its source outside any proof here.
+ loads
+ .sites
+ .entry(source.absolute_addr())
+ .or_default()
+ .push((usize::MAX, block.id, instruction_index));
+ }
increment_saturating(
&mut accesses
.entry(destination.absolute_addr())
@@ -498,7 +571,108 @@ fn collect_global_facts(
store.address,
)
});
- GlobalIdentityFacts { accesses, stores }
+ GlobalIdentityFacts {
+ accesses,
+ stores,
+ settle_loads,
+ }
+}
+
+/// Whether every read of `store`'s address comes after the store: later in
+/// its block, in a block it dominates, or in a later unit, which the
+/// topological order runs after it. Then an alias reads what the store
+/// would have written.
+///
+/// Only a partitioned settle relaxes the unread rule this way: there a
+/// reader in a later partition loads a copy's target from memory, where the
+/// single pass forwards the stored register.
+fn reads_follow_store(facts: &GlobalIdentityFacts, store: &StoreCandidate) -> bool {
+ let Some(loads) = &facts.settle_loads else {
+ return false;
+ };
+ let address = store.address.absolute_addr();
+ let Some(sites) = loads.sites.get(&address) else {
+ return true;
+ };
+ sites.iter().all(|&(eu_index, block, instruction_index)| {
+ if eu_index == usize::MAX {
+ return false;
+ }
+ if eu_index != store.eu_index {
+ return eu_index > store.eu_index;
+ }
+ if block == store.block {
+ return instruction_index > store.instruction_index;
+ }
+ let dominators = &loads.immediate_dominators[eu_index];
+ let mut current = block;
+ while let Some(&parent) = dominators.get(¤t) {
+ if parent == store.block {
+ return true;
+ }
+ if parent == current {
+ return false;
+ }
+ current = parent;
+ }
+ false
+ })
+}
+
+/// The immediate dominator of every block of `eu` reachable from its entry;
+/// the entry is its own.
+fn immediate_dominators(eu: &ExecutionUnit) -> HashMap {
+ let blocks = reverse_postorder_with(eu, &terminator_successors);
+ let indices = blocks
+ .iter()
+ .copied()
+ .enumerate()
+ .map(|(index, block)| (block, index))
+ .collect::>();
+ let mut predecessors = vec![Vec::new(); blocks.len()];
+ for (index, block_id) in blocks.iter().enumerate() {
+ if let Some(block) = eu.blocks.get(block_id) {
+ for successor in terminator_successors(&block.terminator) {
+ if let Some(&successor_index) = indices.get(&successor) {
+ predecessors[successor_index].push(index);
+ }
+ }
+ }
+ }
+ let mut immediate_dominator = vec![None; blocks.len()];
+ if blocks.is_empty() {
+ return HashMap::default();
+ }
+ immediate_dominator[0] = Some(0);
+ let mut changed = true;
+ while changed {
+ changed = false;
+ for block in 1..blocks.len() {
+ let mut defined = predecessors[block]
+ .iter()
+ .copied()
+ .filter(|&predecessor| immediate_dominator[predecessor].is_some());
+ let Some(mut new_dominator) = defined.next() else {
+ continue;
+ };
+ for predecessor in defined {
+ if let Some(intersection) =
+ intersect_dominators(predecessor, new_dominator, &immediate_dominator)
+ {
+ new_dominator = intersection;
+ }
+ }
+ if immediate_dominator[block] != Some(new_dominator) {
+ immediate_dominator[block] = Some(new_dominator);
+ changed = true;
+ }
+ }
+ }
+ immediate_dominator
+ .into_iter()
+ .enumerate()
+ .filter_map(|(index, dominator)| Some((blocks[index], blocks[dominator?])))
+ .collect()
}
fn identity_commit_is_profitable(
@@ -645,7 +819,12 @@ fn select_aliases(
|| !store.effects_are_removable
|| blocked_aliases.contains(&alias)
|| existing_aliases.contains_key(&alias)
- || !is_unique_unread_alias(alias, &facts.accesses)
+ || !(is_unique_unread_alias(alias, &facts.accesses)
+ || (facts
+ .accesses
+ .get(&alias)
+ .is_some_and(|access| access.writes == 1)
+ && reads_follow_store(facts, store)))
|| facts
.accesses
.get(&canonical)
@@ -910,8 +1089,35 @@ fn ff_referenced_addresses(program: &OptimizationContext) -> HashSet) -> HashSet {
- let blocks = reverse_postorder(eu);
+///
+/// A partitioned settle skips a partition only when its stores would write
+/// what memory already holds, so for an identity copy the partition counts
+/// as executed: its guard (a branch into a block that stores to
+/// `settle_flags`) is treated as always taken.
+fn must_execute_blocks(
+ eu: &ExecutionUnit,
+ settle_flags: Option,
+) -> HashSet {
+ let successors = |terminator: &SIRTerminator| {
+ if let (
+ Some(flags),
+ SIRTerminator::Branch {
+ true_block: (body, _),
+ ..
+ },
+ ) = (settle_flags, terminator)
+ && eu.blocks.get(body).is_some_and(|block| {
+ block.instructions.iter().any(|instruction| {
+ matches!(instruction, SIRInstruction::Store(address, ..)
+ if address.region == STABLE_REGION && address.absolute_addr() == flags)
+ })
+ })
+ {
+ return vec![*body];
+ }
+ terminator_successors(terminator)
+ };
+ let blocks = reverse_postorder_with(eu, &successors);
if blocks.is_empty() {
return HashSet::default();
}
@@ -927,7 +1133,7 @@ fn must_execute_blocks(eu: &ExecutionUnit) -> HashSet) -> Vec {
+fn reverse_postorder_with(
+ eu: &ExecutionUnit,
+ successors_of: &dyn Fn(&SIRTerminator) -> Vec,
+) -> Vec {
if !eu.blocks.contains_key(&eu.entry_block_id) {
return Vec::new();
}
@@ -1029,7 +1238,7 @@ fn reverse_postorder(eu: &ExecutionUnit) -> Vec {
return Vec::new();
};
stack.push((block_id, true));
- let mut successors = terminator_successors(&block.terminator);
+ let mut successors = successors_of(&block.terminator);
successors.reverse();
stack.extend(successors.into_iter().map(|successor| (successor, false)));
}
@@ -1429,6 +1638,7 @@ mod tests {
&HashSet::default(),
existing_aliases,
four_state,
+ None,
)
}
@@ -2349,7 +2559,7 @@ mod tests {
.collect();
let metadata = metadata(&[(source, 8), (destination, 8)]);
- remove_proven_alias_stores(&mut units, &aliases, &metadata, false);
+ remove_proven_alias_stores(&mut units, &aliases, &metadata, false, None);
assert_eq!(
units[0].blocks[&BlockId(0)].instructions,
@@ -2374,7 +2584,7 @@ mod tests {
&[(0, 8)],
)];
let metadata = metadata(&[(source, 8), (destination, 8)]);
- let facts = collect_global_facts(&units, &metadata, false);
+ let facts = collect_global_facts(&units, &metadata, false, None);
assert!(
proven_alias_store(&facts, destination.absolute_addr(), source.absolute_addr())
diff --git a/crates/celox-sir-opt/src/policy.rs b/crates/celox-sir-opt/src/policy.rs
index 90c1664ed84..caa5fca0305 100644
--- a/crates/celox-sir-opt/src/policy.rs
+++ b/crates/celox-sir-opt/src/policy.rs
@@ -30,7 +30,8 @@ impl OptLevel {
pub fn default_enabled(self, pass: SirPass) -> bool {
match self {
OptLevel::O0 => matches!(pass, SirPass::TailCallSplit),
- OptLevel::O1 | OptLevel::O2 => true,
+ // Opt-in until it pays off on its own (#2013).
+ OptLevel::O1 | OptLevel::O2 => !matches!(pass, SirPass::PartitionedSettle),
}
}
@@ -122,6 +123,10 @@ define_sir_passes! {
/// clock's domain once more, so disabling it trades tick speed for build
/// time.
DerivedEdgeUnits => "derived_edge_units",
+ /// Split the combinational settle of designs with many event domains
+ /// into partitions that run only when state they read changed. Not a
+ /// SIR transform: the frontend consumes it. Off unless enabled.
+ PartitionedSettle => "partitioned_settle",
}
/// Diagnostics and additional verification for the SIR optimizer.
///
@@ -167,9 +172,21 @@ pub struct OptimizeOptions {
max_native_memory_width: usize,
parallel_lanes: u32,
parallel_partition: ParallelPartition,
+ settle_partition: SettlePartition,
pub diagnostics: SirDiagnostics,
}
+/// How the compiler decides whether to partition the combinational settle
+/// ([`SirPass::PartitionedSettle`]).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum SettlePartition {
+ /// Partition designs with many event domains and a large program.
+ #[default]
+ Estimated,
+ /// Partition every program as finely as possible. For tests.
+ Always,
+}
+
/// How the compiler decides whether a phase gets a lane-partitioned kernel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ParallelPartition {
@@ -202,6 +219,7 @@ impl OptimizeOptions {
},
parallel_lanes: 1,
parallel_partition: ParallelPartition::Estimated,
+ settle_partition: SettlePartition::Estimated,
diagnostics: SirDiagnostics::default(),
}
}
@@ -273,6 +291,15 @@ impl OptimizeOptions {
self.parallel_partition
}
+ pub fn with_settle_partition(mut self, partition: SettlePartition) -> Self {
+ self.settle_partition = partition;
+ self
+ }
+
+ pub fn settle_partition(&self) -> SettlePartition {
+ self.settle_partition
+ }
+
/// Query whether a specific pass is active.
pub fn is_enabled(&self, pass: SirPass) -> bool {
if self.enabled.contains(&pass) {
@@ -285,10 +312,13 @@ impl OptimizeOptions {
}
/// Returns true if any SIR transform is enabled: any pass other than
- /// the TailCallSplit and DerivedEdgeUnits selectors.
+ /// the TailCallSplit, DerivedEdgeUnits and PartitionedSettle selectors.
pub fn any_enabled(&self) -> bool {
SirPass::ALL.iter().any(|&p| {
- !matches!(p, SirPass::TailCallSplit | SirPass::DerivedEdgeUnits) && self.is_enabled(p)
+ !matches!(
+ p,
+ SirPass::TailCallSplit | SirPass::DerivedEdgeUnits | SirPass::PartitionedSettle
+ ) && self.is_enabled(p)
})
}
diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs
index c0aa948bae2..4f2f1390dd8 100644
--- a/crates/celox-slt/src/scheduler.rs
+++ b/crates/celox-slt/src/scheduler.rs
@@ -2420,6 +2420,37 @@ pub struct ScheduleResult {
/// comb/FF schedule. These Stores are semantic state updates rather than
/// disposable comb publications.
pub direct_ff_writes: Vec>,
+ /// The partitions of a partitioned settle, in schedule order; empty when
+ /// the schedule runs as one pass.
+ pub partitions: Vec>,
+}
+
+/// Request to split a combinational schedule into partitions that run only
+/// when state they read changed since they last ran.
+///
+/// Byte `p` of `flags`, a two-state object, is partition `p`'s dirty flag:
+/// the settle runs the partition only when it is not zero, and clears it.
+/// A partition that runs sets the flags of the partitions reading what it
+/// writes; every other writer of state a partition reads must set its flag
+/// too ([`SettlePartition::reads`]).
+#[derive(Clone, Copy, Debug)]
+pub struct SettlePartitioning {
+ pub flags: Addr,
+ /// Approximate expression nodes per partition.
+ pub target_cost: usize,
+}
+
+/// One partition of a partitioned settle.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SettlePartition {
+ /// The state objects the partition reads. A change to any of them must
+ /// set the partition's flag before the next settle.
+ pub reads: Vec,
+ /// The state objects the partition writes.
+ pub writes: Vec,
+ /// Whether the partition runs on every settle, because it has effects
+ /// beyond its stores.
+ pub pinned: bool,
}
pub trait ClockFfLowering {
@@ -3464,6 +3495,333 @@ const UNROLL_THRESHOLD: usize = 32;
/// compatibility matrix for a long run of independent roots.
const MAX_JOINT_FOLD_ROOTS: usize = 16;
+/// One partition of a settle plan.
+struct PlannedPartition {
+ reads: Vec,
+ writes: Vec,
+ /// The partitions whose flags it sets when it runs: those reading what
+ /// it writes, itself included when it reads the previous value of its
+ /// own writes.
+ marks: Vec,
+ pinned: bool,
+}
+
+/// The partitions of a settle, each a contiguous run of scheduled work.
+struct PartitionPlan {
+ /// The first scheduled work of each partition.
+ first_work: Vec,
+ partitions: Vec>,
+}
+
+/// The paths of one piece of scheduled combinational work.
+fn work_paths(work: &ScheduledWork) -> &[usize] {
+ match work {
+ ScheduledWork::CombPath(path) => std::slice::from_ref(path),
+ ScheduledWork::CombScc(paths) | ScheduledWork::GuardedComb { paths, .. } => paths,
+ ScheduledWork::Ff(_) => &[],
+ }
+}
+
+/// The approximate lowering cost of a path: its distinct expression nodes,
+/// or a process unit's instructions.
+pub fn path_cost(
+ arena: &SLTNodeArena,
+ path: &LogicPath,
+) -> usize {
+ if let LogicPathTarget::Process { unit, .. } = &path.target {
+ return unit
+ .blocks
+ .values()
+ .map(|block| block.instructions.len() + 1)
+ .sum();
+ }
+ let mut seen = HashSet::default();
+ let mut stack = vec![path.expr];
+ let mut cost = 0;
+ while let Some(node) = stack.pop() {
+ if !seen.insert(node) {
+ continue;
+ }
+ cost += 1;
+ match arena.get(node) {
+ SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]),
+ SLTNode::Unary(_, operand)
+ | SLTNode::Slice { expr: operand, .. }
+ | SLTNode::Capture { expr: operand, .. } => stack.push(*operand),
+ SLTNode::Mux {
+ cond,
+ then_expr,
+ else_expr,
+ } => stack.extend([*cond, *then_expr, *else_expr]),
+ SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)),
+ // A loop's cost scales with its trip count; count it as large.
+ SLTNode::ForFold { .. } | SLTNode::ForFoldGroup { .. } => cost += 64,
+ SLTNode::Input { .. } | SLTNode::Constant(..) => {}
+ }
+ }
+ cost
+}
+
+/// Whether a path's expression captures a value at an evaluation position.
+fn path_has_capture(
+ arena: &SLTNodeArena,
+ path: &LogicPath,
+) -> bool {
+ if matches!(path.target, LogicPathTarget::CombCaptureEvent { .. }) {
+ return true;
+ }
+ let mut seen = HashSet::default();
+ let mut stack = vec![path.expr];
+ while let Some(node) = stack.pop() {
+ if !seen.insert(node) {
+ continue;
+ }
+ match arena.get(node) {
+ SLTNode::Capture { .. } => return true,
+ SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]),
+ SLTNode::Unary(_, operand) | SLTNode::Slice { expr: operand, .. } => {
+ stack.push(*operand)
+ }
+ SLTNode::Mux {
+ cond,
+ then_expr,
+ else_expr,
+ } => stack.extend([*cond, *then_expr, *else_expr]),
+ SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)),
+ _ => {}
+ }
+ }
+ false
+}
+
+/// Whether a path does more than store its value: comb capture events,
+/// activation of capture sites, and process units with runtime events or
+/// extern calls. A partition holding one runs on every settle.
+fn path_has_effects(path: &LogicPath) -> bool {
+ if !path.comb_capture_enable_sites.is_empty() || path.comb_capture_enable_always {
+ return true;
+ }
+ match &path.target {
+ LogicPathTarget::CombCaptureEvent { .. } => true,
+ LogicPathTarget::Process { unit, .. } => unit.blocks.values().any(|block| {
+ block
+ .instructions
+ .iter()
+ .any(|instruction| match instruction {
+ SIRInstruction::RuntimeEvent { .. }
+ | SIRInstruction::CombCaptureEvent { .. }
+ | SIRInstruction::CombCaptureEnableIfChanged { .. }
+ | SIRInstruction::ExternCall { .. } => true,
+ SIRInstruction::Store(.., capture_sites) => !capture_sites.is_empty(),
+ _ => false,
+ })
+ }),
+ LogicPathTarget::Var(_) => false,
+ }
+}
+
+/// Cut a combinational schedule into partitions of about
+/// `partitioning.target_cost`, or `None` when it would be one.
+fn plan_settle_partitions(
+ prepared: &PreparedSchedule,
+ arena: &SLTNodeArena,
+ var_widths: &HashMap,
+ partitioning: SettlePartitioning,
+) -> Option<(PartitionPlan, Addr)> {
+ let input = &prepared.input;
+ // A captured value or a pre-lowered node is materialized at one place
+ // and reused at a later one through the lowering cache, which a
+ // partition boundary between them would clear.
+ if input
+ .iter()
+ .any(|path| !path.pre_lower_nodes.is_empty() || path_has_capture(arena, path))
+ {
+ return None;
+ }
+ // Whole-variable copies, by target.
+ let mut copy_source: HashMap = HashMap::default();
+ for work in &prepared.scheduled_work {
+ if let ScheduledWork::CombPath(path) = work
+ && let Some((target, source)) = whole_variable_copy(arena, &input[*path], var_widths)
+ {
+ copy_source.insert(target, source);
+ }
+ }
+ let mut first_work = Vec::new();
+ let mut cost = 0;
+ for (index, work) in prepared.scheduled_work.iter().enumerate() {
+ if first_work.is_empty() || cost >= partitioning.target_cost {
+ first_work.push(index);
+ cost = 0;
+ }
+ cost += work_paths(work)
+ .iter()
+ .map(|&path| path_cost(arena, &input[path]))
+ .sum::();
+ }
+ if first_work.len() < 2 {
+ return None;
+ }
+ let mut partition_of_work = vec![0; prepared.scheduled_work.len()];
+ for (partition, &first) in first_work.iter().enumerate() {
+ let end = first_work
+ .get(partition + 1)
+ .copied()
+ .unwrap_or(prepared.scheduled_work.len());
+ partition_of_work[first..end].fill(partition);
+ }
+ let count = first_work.len();
+ let mut reads = vec![BTreeSet::new(); count];
+ let mut writes = vec![BTreeSet::new(); count];
+ let mut previous = vec![BTreeSet::new(); count];
+ let mut pinned = vec![false; count];
+ for (index, work) in prepared.scheduled_work.iter().enumerate() {
+ let partition = partition_of_work[index];
+ for &path_index in work_paths(work) {
+ let path = &input[path_index];
+ pinned[partition] |= path_has_effects(path);
+ let atoms = path
+ .sources
+ .iter()
+ .chain(&path.address_sources)
+ .chain(&path.previous_sources);
+ reads[partition].extend(atoms.map(|atom| atom.id));
+ // A process's activation guard reads its occurrence counters and
+ // startup slots as well.
+ if let LogicPathTarget::Process {
+ sensitivity_counters,
+ startup,
+ unit,
+ ..
+ } = &path.target
+ {
+ // The unit may read more than its listed sources, such as
+ // force controls. It runs at its process's first projection
+ // and writes every output there.
+ for block in unit.blocks.values() {
+ for instruction in &block.instructions {
+ match instruction {
+ SIRInstruction::Load(_, address, ..) => {
+ reads[partition].insert(*address);
+ }
+ SIRInstruction::Store(address, ..) => {
+ writes[partition].insert(*address);
+ }
+ SIRInstruction::Commit(source, target, ..) => {
+ reads[partition].insert(*source);
+ writes[partition].insert(*target);
+ }
+ _ => {}
+ }
+ }
+ }
+ for (atom, counter) in sensitivity_counters {
+ reads[partition].extend([atom.id, *counter]);
+ }
+ if let Some(startup) = startup {
+ reads[partition].insert(startup.initialized);
+ for (atom, slot) in &startup.inputs {
+ reads[partition].extend([atom.id, *slot]);
+ }
+ for (counter, slot) in &startup.counters {
+ reads[partition].extend([*counter, *slot]);
+ }
+ }
+ }
+ previous[partition].extend(path.previous_sources.iter().map(|atom| atom.id));
+ if let Some(target) = path.target.var() {
+ writes[partition].insert(target.id);
+ }
+ }
+ }
+ // Reading a copy's target reads its source: the copy may become an
+ // alias of its source, whose changes then reach the target without the
+ // copy running.
+ for read in &mut reads {
+ let mut sources = Vec::new();
+ for &addr in read.iter() {
+ let mut current = addr;
+ let mut steps = 0;
+ while let Some(&source) = copy_source.get(¤t) {
+ sources.push(source);
+ current = source;
+ steps += 1;
+ if steps > copy_source.len() {
+ break;
+ }
+ }
+ }
+ read.extend(sources);
+ }
+ let mut readers: HashMap> = HashMap::default();
+ for (partition, read) in reads.iter().enumerate() {
+ for &addr in read {
+ readers.entry(addr).or_default().push(partition);
+ }
+ }
+ let partitions = (0..count)
+ .map(|partition| {
+ let mut marks = BTreeSet::new();
+ for addr in &writes[partition] {
+ for &reader in readers.get(addr).into_iter().flatten() {
+ if reader != partition || previous[partition].contains(addr) {
+ marks.insert(reader);
+ }
+ }
+ }
+ PlannedPartition {
+ reads: reads[partition].iter().copied().collect(),
+ writes: writes[partition].iter().copied().collect(),
+ marks: marks.into_iter().collect(),
+ pinned: pinned[partition],
+ }
+ })
+ .collect();
+ Some((
+ PartitionPlan {
+ first_work,
+ partitions,
+ },
+ partitioning.flags,
+ ))
+}
+
+/// The `(target, source)` of a path that copies one whole variable into
+/// another of the same width.
+fn whole_variable_copy(
+ arena: &SLTNodeArena,
+ path: &LogicPath,
+ var_widths: &HashMap,
+) -> Option<(Addr, Addr)> {
+ if !path.transparent_copy || !path.previous_sources.is_empty() {
+ return None;
+ }
+ let target = match &path.target {
+ LogicPathTarget::Var(target) => target,
+ _ => return None,
+ };
+ let width = *var_widths.get(&target.id)?;
+ if target.access.lsb != 0 || target.access.msb + 1 != width {
+ return None;
+ }
+ match arena.get(path.expr) {
+ SLTNode::Input {
+ variable,
+ index,
+ access,
+ ..
+ } if index.is_empty()
+ && access.lsb == 0
+ && access.msb + 1 == width
+ && var_widths.get(variable) == Some(&width)
+ && *variable != target.id =>
+ {
+ Some((target.id, *variable))
+ }
+ _ => None,
+ }
+}
+
/// Lowering state for one sequence of scheduled work emitted through one SIR
/// builder. Register numbers and the expression cache are local to it.
struct WorkLowering<'a, Addr: Clone + Eq + Hash> {
@@ -3478,6 +3836,11 @@ struct WorkLowering<'a, Addr: Clone + Eq + Hash> {
/// The processes whose unit an acyclic projection has run (see
/// [`Self::lower`]).
run_processes: HashSet,
+ /// Inside a partition of a partitioned settle, which units must not
+ /// split.
+ in_partition: bool,
+ /// Where a guarded partition continues when it is skipped.
+ partition_merge: Option,
}
impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a, Addr> {
@@ -3492,9 +3855,102 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a
pending_fold_indices: Vec::new(),
pending_fold_roots: HashSet::default(),
run_processes: HashSet::default(),
+ in_partition: false,
+ partition_merge: None,
}
}
+ /// Open partition `index`: run it only when its flag or the untracked
+ /// byte (`untracked`) is set, and clear its flag. Values computed before
+ /// it may be reused inside, but not the other way round, so the
+ /// expression cache starts over.
+ fn begin_partition(
+ &mut self,
+ flags: Addr,
+ index: usize,
+ untracked: usize,
+ partition: &PlannedPartition,
+ ) {
+ self.flush_pending_folds();
+ if self.context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT {
+ if let Some(eu) = self.builder.flush_eu() {
+ self.execution_units.push(eu);
+ }
+ }
+ self.lower_cache.clear();
+ self.in_partition = true;
+ let offset = SIROffset::Static(index * 8);
+ if !partition.pinned {
+ let own = self.builder.alloc_bit(8, false);
+ self.builder
+ .emit(SIRInstruction::Load(own, flags, offset.clone(), 8));
+ let all = self.builder.alloc_bit(8, false);
+ self.builder.emit(SIRInstruction::Load(
+ all,
+ flags,
+ SIROffset::Static(untracked * 8),
+ 8,
+ ));
+ let flag = self.builder.alloc_bit(8, false);
+ self.builder
+ .emit(SIRInstruction::Binary(flag, own, BinaryOp::Or, all));
+ let zero = self.builder.alloc_bit(8, false);
+ self.builder
+ .emit(SIRInstruction::Imm(zero, SIRValue::new(0u64)));
+ let dirty = self.builder.alloc_bit(1, false);
+ self.builder
+ .emit(SIRInstruction::Binary(dirty, flag, BinaryOp::Ne, zero));
+ let body = self.builder.new_block();
+ let merge = self.builder.new_block();
+ self.builder.seal_block(SIRTerminator::Branch {
+ cond: dirty,
+ true_block: (body, Vec::new()),
+ false_block: (merge, Vec::new()),
+ });
+ self.builder.switch_to_block(body);
+ self.partition_merge = Some(merge);
+ }
+ let clean = self.builder.alloc_bit(8, false);
+ self.builder
+ .emit(SIRInstruction::Imm(clean, SIRValue::new(0u64)));
+ self.builder.emit(SIRInstruction::Store(
+ flags,
+ offset,
+ 8,
+ clean,
+ Vec::new(),
+ Vec::new(),
+ ));
+ }
+
+ /// Close a partition: set the flags of the partitions reading what it
+ /// wrote, then join the path that skipped it.
+ fn end_partition(&mut self, flags: Addr, partition: &PlannedPartition) {
+ self.flush_pending_folds();
+ if !partition.marks.is_empty() {
+ let one = self.builder.alloc_bit(8, false);
+ self.builder
+ .emit(SIRInstruction::Imm(one, SIRValue::new(1u64)));
+ for &reader in &partition.marks {
+ self.builder.emit(SIRInstruction::Store(
+ flags,
+ SIROffset::Static(reader * 8),
+ 8,
+ one,
+ Vec::new(),
+ Vec::new(),
+ ));
+ }
+ }
+ if let Some(merge) = self.partition_merge.take() {
+ self.builder
+ .seal_block(SIRTerminator::Jump(merge, Vec::new()));
+ self.builder.switch_to_block(merge);
+ }
+ self.lower_cache.clear();
+ self.in_partition = false;
+ }
+
/// Lower the buffered run of exact grouped-fold paths.
fn flush_pending_folds(&mut self) {
let context = self.context;
@@ -3854,7 +4310,10 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a
}
} else {
// DAG Part — flush before emitting if the EU has grown too large
- if context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT {
+ if context.split_large_units
+ && !self.in_partition
+ && self.builder.block_count() >= EU_BLOCK_LIMIT
+ {
self.flush_pending_folds();
if let Some(eu) = self.builder.flush_eu() {
self.execution_units.push(eu);
@@ -3932,6 +4391,7 @@ fn sort_impl(
unpacked_element_widths: &HashMap,
first_runtime_error_code: i64,
mut ff: Option<&mut dyn ClockFfLowering>,
+ partitioning: Option>,
) -> Result, ClockSortError> {
let prepared = prepare_schedule(
input,
@@ -3972,7 +4432,25 @@ fn sort_impl(
}
let mut runtime_errors: HashMap> = HashMap::default();
let mut next_runtime_error_code = first_runtime_error_code;
- for work in &prepared.scheduled_work {
+ let plan = partitioning
+ .filter(|_| ff.is_none())
+ .and_then(|partitioning| {
+ plan_settle_partitions(&prepared, arena, var_widths, partitioning)
+ });
+ for (index, work) in prepared.scheduled_work.iter().enumerate() {
+ if let Some((plan, flags)) = &plan {
+ if let Some(partition) = plan.first_work.iter().position(|&first| first == index) {
+ if partition > 0 {
+ lowering.end_partition(*flags, &plan.partitions[partition - 1]);
+ }
+ lowering.begin_partition(
+ *flags,
+ partition,
+ plan.partitions.len(),
+ &plan.partitions[partition],
+ );
+ }
+ }
lowering.lower(
work,
ff.as_deref_mut(),
@@ -3980,6 +4458,11 @@ fn sort_impl(
&mut next_runtime_error_code,
)?;
}
+ if let Some((plan, flags)) = &plan
+ && let Some(last) = plan.partitions.last()
+ {
+ lowering.end_partition(*flags, last);
+ }
// Flush the final exact grouped-fold run after the SCC loop.
lowering.flush_pending_folds();
if let Some(ff_lowering) = ff {
@@ -3991,6 +4474,18 @@ fn sort_impl(
execution_units: lowering.finish(),
runtime_errors,
direct_ff_writes,
+ partitions: plan
+ .map(|(plan, _)| {
+ plan.partitions
+ .into_iter()
+ .map(|partition| SettlePartition {
+ reads: partition.reads,
+ writes: partition.writes,
+ pinned: partition.pinned,
+ })
+ .collect()
+ })
+ .unwrap_or_default(),
})
}
@@ -4013,6 +4508,7 @@ pub fn sort(
var_widths,
&HashMap::default(),
first_runtime_error_code,
+ None,
)
}
@@ -4025,6 +4521,7 @@ pub fn sort_with_unpacked_element_widths,
unpacked_element_widths: &HashMap,
first_runtime_error_code: i64,
+ partitioning: Option>,
) -> Result, SchedulerError> {
match sort_impl::(
input,
@@ -4036,6 +4533,7 @@ pub fn sort_with_unpacked_element_widths Ok(result),
Err(ClockSortError::Scheduler(error)) => Err(error),
@@ -4066,6 +4564,7 @@ pub fn sort_clock(
unpacked_element_widths,
first_runtime_error_code,
Some(ff),
+ None,
)
}
@@ -4085,7 +4584,7 @@ mod tests {
LogicPath, LogicPathTarget, SLTForFoldGroupState, SLTNode, SLTNodeArena, SLTToSIRLowerer,
};
use celox_design::{BinaryOp, BitAccess, VarAtomBase};
- use celox_sir::{SIRBuilder, SIRInstruction, SIRTerminator};
+ use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator};
#[test]
fn deep_input_dependencies_use_heap_and_preserve_inverse_index() {
@@ -4629,6 +5128,105 @@ mod tests {
assert_eq!(adj, vec![vec![1], vec![2], Vec::new()]);
}
+ fn partitioned_sort(
+ paths: Vec>,
+ arena: &SLTNodeArena,
+ ) -> super::ScheduleResult {
+ let widths = (10..14).map(|id| (id, 8)).collect();
+ super::sort_with_unpacked_element_widths(
+ paths,
+ arena,
+ &crate::HashSet::default(),
+ &crate::HashMap::default(),
+ false,
+ &widths,
+ &crate::HashMap::default(),
+ 1,
+ Some(super::SettlePartitioning {
+ flags: 99,
+ target_cost: 1,
+ }),
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn settle_partitions_follow_schedule_and_guard_on_their_flags() {
+ let mut arena = SLTNodeArena::new();
+ let paths = vec![
+ simple_path(&mut arena, 13, Some(12)),
+ simple_path(&mut arena, 12, Some(11)),
+ simple_path(&mut arena, 11, Some(10)),
+ ];
+ let result = partitioned_sort(paths, &arena);
+ let plan = result
+ .partitions
+ .iter()
+ .map(|partition| (partition.reads.clone(), partition.writes.clone()))
+ .collect::>();
+ assert_eq!(
+ plan,
+ vec![
+ (vec![10], vec![11]),
+ (vec![11], vec![12]),
+ (vec![12], vec![13]),
+ ]
+ );
+ assert!(result.partitions.iter().all(|partition| !partition.pinned));
+ // Each partition loads its own flag and the untracked-writes flag
+ // after them; a partition sets its reader's.
+ let mut loaded = Vec::new();
+ let mut stored = Vec::new();
+ for unit in &result.execution_units {
+ for block in unit.blocks.values() {
+ for instruction in &block.instructions {
+ match instruction {
+ SIRInstruction::Load(_, 99, SIROffset::Static(byte), 8) => {
+ loaded.push(*byte)
+ }
+ SIRInstruction::Store(99, SIROffset::Static(byte), 8, ..) => {
+ stored.push(*byte)
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+ loaded.sort_unstable();
+ stored.sort_unstable();
+ assert_eq!(loaded, vec![0, 8, 16, 24, 24, 24]);
+ // The clears of all three flags, and the marks of partitions 1 and 2.
+ assert_eq!(stored, vec![0, 8, 8, 16, 16]);
+ }
+
+ #[test]
+ fn settle_copy_readers_read_the_copied_source() {
+ let mut arena = SLTNodeArena::new();
+ let mut copy = simple_path(&mut arena, 12, Some(11));
+ copy.transparent_copy = true;
+ let paths = vec![
+ simple_path(&mut arena, 13, Some(12)),
+ copy,
+ simple_path(&mut arena, 11, Some(10)),
+ ];
+ let result = partitioned_sort(paths, &arena);
+ let plan = result
+ .partitions
+ .iter()
+ .map(|partition| (partition.reads.clone(), partition.writes.clone()))
+ .collect::>();
+ // The copy is guarded like other work, and its reader reads the
+ // copied source too.
+ assert_eq!(
+ plan,
+ vec![
+ (vec![10], vec![11]),
+ (vec![11], vec![12]),
+ (vec![11, 12], vec![13]),
+ ]
+ );
+ }
+
#[test]
fn memory_ssa_scheduler_lowers_independent_single_use_chains_contiguously() {
let mut arena = SLTNodeArena::new();
diff --git a/crates/celox-state-layout/src/lib.rs b/crates/celox-state-layout/src/lib.rs
index ff2fbef6463..f296da09d27 100644
--- a/crates/celox-state-layout/src/lib.rs
+++ b/crates/celox-state-layout/src/lib.rs
@@ -11,7 +11,9 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use serde::{Deserialize, Serialize};
use std::hash::Hash;
+mod settle;
mod trace;
+pub use settle::{SettleLayout, SettleObject};
pub use trace::{TRACE_GROUP_BYTES, TraceLayout};
pub const RUNTIME_EVENT_CAPACITY: usize = 1024;
@@ -191,6 +193,9 @@ pub trait LayoutSource {
pub struct MemoryLayout {
/// Present only in builds that record waveforms.
pub trace: Option,
+ /// Present when the combinational settle is partitioned.
+ #[serde(default)]
+ pub settle: Option,
pub four_state: bool,
pub mode: MemoryLayoutMode,
/// Stable region offsets. Includes all declared state objects.
@@ -338,6 +343,15 @@ fn place_region(
align_up(current + LANE_SEGMENT_GUARD, LANE_SEGMENT_ALIGN)
}
+impl MemoryLayout {
+ /// Whether each settle runs a second time to cross-check its partitions
+ /// ([`SettleLayout::check`]).
+ #[inline]
+ pub fn settle_check(&self) -> bool {
+ self.settle.as_ref().is_some_and(|settle| settle.check)
+ }
+}
+
impl MemoryLayout
where
A: Copy + Eq + Hash + Ord,
@@ -553,6 +567,7 @@ where
Self {
trace: None,
+ settle: None,
four_state,
mode,
offsets,
diff --git a/crates/celox-state-layout/src/settle.rs b/crates/celox-state-layout/src/settle.rs
new file mode 100644
index 00000000000..652d5009930
--- /dev/null
+++ b/crates/celox-state-layout/src/settle.rs
@@ -0,0 +1,74 @@
+//! Dirty flags of a partitioned combinational settle.
+//!
+//! Generated code sets the flags of the partitions reading the state it
+//! writes; host writes go through [`SettleLayout::mark_range`]. Writes no
+//! one reports, through a retained raw view of the state, set the untracked
+//! byte, after which every partition runs on every settle.
+use serde::{Deserialize, Serialize};
+
+/// State written outside generated code and the partitions reading it.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SettleObject {
+ /// Byte range of the object, both planes.
+ pub start: usize,
+ pub end: usize,
+ pub partitions: Vec,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SettleLayout {
+ /// One byte per partition, then the untracked byte.
+ pub flags_offset: usize,
+ pub partitions: usize,
+ /// Sorted by `start`, disjoint.
+ pub objects: Vec,
+ /// Debug cross-check: the backends run each settle again with every
+ /// partition flagged and panic where the results differ.
+ #[serde(default)]
+ pub check: bool,
+}
+
+impl SettleLayout {
+ pub fn new(flags_offset: usize, partitions: usize, mut objects: Vec) -> Self {
+ objects.sort_unstable_by_key(|object| object.start);
+ Self {
+ flags_offset,
+ partitions,
+ objects,
+ check: false,
+ }
+ }
+
+ /// Set the flags of the partitions reading state in `offset..offset + len`.
+ ///
+ /// # Safety
+ /// `memory` must point to the writable state image this layout describes.
+ pub unsafe fn mark_range(&self, memory: *mut u8, offset: usize, len: usize) {
+ let end = offset + len.max(1);
+ let first = self.objects.partition_point(|object| object.end <= offset);
+ for object in self.objects[first..]
+ .iter()
+ .take_while(|object| object.start < end)
+ {
+ for &partition in &object.partitions {
+ // SAFETY: flags lie inside the image (caller contract).
+ unsafe { *memory.add(self.flags_offset + partition as usize) = 1 };
+ }
+ }
+ }
+
+ /// The bytes of the flags, the untracked byte included.
+ pub fn flags(&self) -> std::ops::Range {
+ self.flags_offset..self.flags_offset + self.partitions + 1
+ }
+
+ /// Run every partition on every settle from now on: a raw view of the
+ /// state can change it without reporting.
+ ///
+ /// # Safety
+ /// `memory` must point to the writable state image this layout describes.
+ pub unsafe fn mark_untracked(&self, memory: *mut u8) {
+ // SAFETY: the untracked byte follows the flags (caller contract).
+ unsafe { *memory.add(self.flags_offset + self.partitions) = 1 };
+ }
+}
diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs
index cb6cbe72434..9472313a755 100644
--- a/crates/celox-sv-analyzer/src/ast.rs
+++ b/crates/celox-sv-analyzer/src/ast.rs
@@ -1331,7 +1331,7 @@ impl Module {
// Declaration initializers run before the other initial blocks.
let first_block = initial_processes
.iter()
- .position(|process| !process.initializer)
+ .position(|process| !process.is_initializer())
.unwrap_or(initial_processes.len());
initial_processes.insert(
first_block,
@@ -1340,7 +1340,8 @@ impl Module {
site: None,
condition: None,
body: static_initializers,
- initializer: true,
+ kind: celox_design::ProcessKind::Initializer,
+ validation_body: Vec::new(),
synthetic: false,
repeats: false,
},
@@ -1379,6 +1380,7 @@ impl Module {
}
for process in &mut initial_processes {
process.body = body(std::mem::take(&mut process.body));
+ process.validation_body = body(std::mem::take(&mut process.validation_body));
}
for subroutine in &mut subroutines {
*subroutine = rename.subroutine(subroutine.clone());
@@ -2535,14 +2537,16 @@ impl FfProcess {
}
}
-/// An `initial` process.
+/// A scheduled procedure, including initial/always processes and final procedures.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitialProcess {
creation_order: usize,
site: Option,
condition: Option,
body: Vec,
- initializer: bool,
+ kind: celox_design::ProcessKind,
+ /// Folded-away statements retained only for final-procedure legality checks.
+ validation_body: Vec,
synthetic: bool,
/// An `always` process: its body runs forever.
repeats: bool,
@@ -2562,6 +2566,16 @@ impl InitialProcess {
self.condition.as_ref()
}
+ /// The procedure's simulation phase.
+ pub fn kind(&self) -> celox_design::ProcessKind {
+ self.kind
+ }
+
+ /// A final procedure runs once when the simulation finishes (9.2.3).
+ pub fn is_final(&self) -> bool {
+ self.kind == celox_design::ProcessKind::Final
+ }
+
/// Compiler-generated storage initialization, without a user static process.
pub fn is_synthetic(&self) -> bool {
self.synthetic
@@ -2569,7 +2583,7 @@ impl InitialProcess {
/// Whether this process holds variable declaration initializers.
pub fn is_initializer(&self) -> bool {
- self.initializer
+ self.kind == celox_design::ProcessKind::Initializer
}
/// Whether this is an `always` process, which runs its body forever and
diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs
index 6dfd67cbc94..8429bf932e9 100644
--- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs
+++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs
@@ -220,7 +220,8 @@ impl ArrayParameter {
rhs: value,
nonblocking: false,
}],
- initializer: false,
+ kind: celox_design::ProcessKind::Regular,
+ validation_body: Vec::new(),
synthetic: true,
repeats: false,
})
diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs
index d958288a35a..4bc6aaf825e 100644
--- a/crates/celox-sv-analyzer/src/ast/comb_process.rs
+++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs
@@ -295,7 +295,10 @@ fn comb_process_from_procedure(
parameter_literals: &HashMap,
state: &mut procedural::BodyState<'_>,
) -> Result