diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 27fabd04104..a7a1d8c72ba 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2678,8 +2678,38 @@ impl<'p, 'a> Comb<'p, 'a> { continue_flag, }); - if let sv::ir::LoopKind::For = kind - && let Some(canonical) = canonical_for_loop(init, condition, step) + let canonical = match kind { + sv::ir::LoopKind::For => canonical_for_loop(init, condition, step), + _ => None, + }; + // An `initial` block runs as a process when it cannot be folded into + // initial state, so a loop whose trip count is not known before it + // runs goes there instead of being unrolled until the limit. + if self.initial { + let counted = match kind { + sv::ir::LoopKind::Repeat(_) => true, + sv::ir::LoopKind::For => canonical.as_ref().is_some_and(|canonical| { + let mut written = HashSet::default(); + written_names(body, &mut written); + !written.contains(&canonical.var) + }), + sv::ir::LoopKind::While | sv::ir::LoopKind::DoWhile => { + match counted_while_loop(condition, body) { + Some((counted, rest)) => { + !self.loop_needs_fold(&store, frames, &counted, rest)? + } + None => false, + } + } + sv::ir::LoopKind::Forever => false, + }; + if !counted { + return Err(unsupported( + "initial block loop without a static trip count", + )); + } + } + if let Some(canonical) = canonical && self.loop_needs_fold(&store, frames, &canonical, body)? { self.folding += 1; diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index def194c3e1d..a1a1c6bddb8 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -2320,6 +2320,36 @@ pub(super) fn canonical_for_loop( }) } +/// The counted loop a `while` or `do`-`while` loop is when its condition +/// compares a variable with a bound and its last statement steps that +/// variable, as the step of a [`canonical_for_loop`] would; the loop starts +/// from the variable's current value. Also returns the statements before +/// the step, which must not write the variable or the bound. +pub(super) fn counted_while_loop<'s>( + condition: Option<&sv::ir::Expr>, + body: &'s [sv::ir::Stmt], +) -> Option<(CanonicalLoop, &'s [sv::ir::Stmt])> { + let (step, rest) = body.split_last()?; + let sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(var), + .. + } = step + else { + return None; + }; + let init = [sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(var.clone()), + rhs: sv::ir::Expr::Ident(var.clone()), + nonblocking: false, + }]; + let canonical = canonical_for_loop(&init, condition, std::slice::from_ref(step))?; + let mut written = HashSet::default(); + written_names(rest, &mut written); + let mut bound = HashSet::default(); + expr_idents(&canonical.end, &mut bound); + (!written.contains(&canonical.var) && written.is_disjoint(&bound)).then_some((canonical, rest)) +} + /// The identifiers an expression reads. pub(super) fn expr_idents(expr: &sv::ir::Expr, names: &mut HashSet) { fn const_idents(expr: &sv::ir::ConstExpr, names: &mut HashSet) { diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 867a5ff44e3..576be5cc0ee 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -280,6 +280,65 @@ (assert_eq y (+ (* i 3) 1)) (assert_eq z 0x5a))) +; An initial block whose loops have no static trip count (a condition on +; another variable than the one the step assigns, `while`, `do`-`while`) runs +; as a process instead of being unrolled into initial state (#1992). +(case initial_loops_without_a_static_trip_count_run_as_a_process + (source "initial_loops.sv" #" + module Ram; + logic [7:0] mem [16]; + endmodule + module Top; + Ram r0(), r1(); + logic [31:0] src [32]; + logic [7:0] w [8]; + integer i, j, n; + initial begin + for (n = 0; n < 32; n = n + 1) src[n] = 32'h01010101 * n; + i = 0; + for (j = 0; i < 16; i = j / 2) begin + r0.mem[i] = src[j][15:8]; + j = j + 1; + r1.mem[i] = src[j][31:24]; + j = j + 1; + end + n = 0; + while (n < 8) begin + w[n] = 8'(n * 5); + n = n + 1; + end + do n = n - 3; while (n > 0); + #1 $display("%0d %0d %h %h %h %h %h %0d", i, j, r0.mem[0], r0.mem[15], + r1.mem[0], r1.mem[15], w[7], n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "16 32 00 1e 01 1f 23 -1\n")) + +; The state such an initial block writes is visible like folded initial state. +(case initial_while_loops_define_the_state + (source "initial_while.sv" #" + module Top(input logic [1:0] index, output logic [7:0] y); + logic [7:0] mem [4]; + int n; + initial begin + n = 0; + while (n < 4) begin + mem[n] = 8'(n * 3 + 1); + n++; + end + end + assign y = mem[index]; + endmodule + "#) + (top Top) + (for i (range 0 4) + (modify (set index i)) + (assert_eq y (+ (* i 3) 1)))) + (case loop_initializer_widens_by_its_own_signedness (source "loop_start.sv" #" module Top(input logic [7:0] value, output logic [7:0] count, output logic [7:0] registered, diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 11835e6e428..b05942b9658 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -253,3 +253,12 @@ sv_backends! { @case "procedural::static_function_wide_packed_storage_keeps_all_bits"; } } + +sv_backends! { + fn initial_loops_without_a_static_trip_count_run_as_a_process(sim) { + @case "procedural::initial_loops_without_a_static_trip_count_run_as_a_process"; + } + fn initial_while_loops_define_the_state(sim) { + @case "procedural::initial_while_loops_define_the_state"; + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 04c403a1f49..ebf7590fcf2 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -42,7 +42,7 @@ synthesis and is tested at the design level. | Continuous logic | `assign`, `wire w = expr;` | | Combinational processes | `always_comb`, `always @*`, blocking `always_latch`, block-local variables, sequential and dependent blocking assignments, reads of a variable before the process writes it (its previous value) | | Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | -| Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if` / `for` and `$readmemh` / `$readmemb`, defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | +| Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if`, `$readmemh` / `$readmemb`, and loops whose trip count is known before they run (`repeat`, and `for`, `while` or `do`-`while` loops that step one variable by a constant up to a fixed bound), defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | | Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate and deferred immediate assertions | | Functions | `function` and `task` with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 5de49f53e7f..ef745e2e4bf 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -40,7 +40,7 @@ outline: [2, 3] | 連続論理 | `assign`、`wire w = expr;` | | 組み合わせプロセス | `always_comb`、`always @*`、ブロッキング代入の `always_latch`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | | 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | -| initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if` / `for`、`$readmemh` / `$readmemb` を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | +| initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if`、`$readmemh` / `$readmemb`、実行前に反復回数が分かるループ(`repeat` と、1 つの変数を定数ずつ固定の境界まで進める `for` / `while` / `do`-`while`)を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | | 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーションと遅延付き即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 |