Module 5: Behavioral Verilog for Synthesis · 5.4 Loops in Verilog

while, repeat and forever

Verilog defines four loop constructs. The for loop with constant bounds is the primary construct for synthesizable RTL. The remaining three constructs—repeat, while, and forever—operate primarily in simulation testbenches. A synthesis tool must determine the exact number of hardware replications before elaboration. A loop whose termination depends on dynamic runtime data cannot determine gate counts.

Loop Construct Synthesizable Termination Condition Primary Application
for Yes, with constant bounds Constant boundary Replicated parallel hardware
repeat Tool-dependent Fixed cycle count Testbench cycle counting
while Rarely Dynamic condition Testbench synchronization
forever Never Infinite execution Clock generation and monitors

The repeat Construct

The repeat (n) construct executes its body a fixed number of times without an explicit index variable:

repeat (10) begin
    @(posedge clk);
end

Some synthesis tools support repeat statements with constant counts by unrolling logic. Other tools reject them. Therefore, write synthesizable RTL using for loops. In testbenches, repeat provides a clear method to wait for clock cycles:

initial begin
    rst_n = 1'b0;
    repeat (5) @(posedge clk);      // Assert reset for five clock cycles
    rst_n = 1'b1;

    repeat (100) @(posedge clk);
    $display("done after 105 cycles");
    $finish;
end

Because repeat lacks an iteration index, you cannot access an index directly. Use a for loop if you require indexed values such as stimulus[i].

The while Construct

The while (condition) construct represents a general loop. Do not use while statements in synthesizable RTL. A synthesis tool can theoretically unroll a while loop if it proves static termination. However, a for loop provides universal tool support.

The while loop is valuable in testbenches when waiting for handshake signals:

initial begin
    // Apply stimulus
    while (!done) begin
        @(posedge clk);
    end
    if (result !== expected)
        $display("FAIL: result=%0d expected=%0d", result, expected);
end

Do not write while or forever loops in synthesizable RTL files. To describe multi-cycle operations, use synchronous state machines and counters with register storage.

The forever Construct

A forever loop runs indefinitely and has no physical hardware equivalent. Its primary application is clock signal generation in testbenches:

`timescale 1ns / 1ps
`default_nettype none

module tb_my_design;

    reg clk;
    reg rst_n;

    wire [7:0] result;
    wire       valid;

    my_design u_dut (.clk(clk), .rst_n(rst_n), .result(result), .valid(valid));

    initial begin
        $dumpfile("tb_my_design.vcd");
        $dumpvars(0, tb_my_design);
    end

    initial begin
        clk = 1'b0;
        forever #5 clk = ~clk;      // Generates a 10 ns clock period
    end

    initial begin
        rst_n = 1'b0;
        repeat (3) @(posedge clk);
        rst_n = 1'b1;
        // Stimulus generation here
        #500 $finish;
    end

endmodule

Engineers also use always #5 clk = ~clk; with an initial clk = 0; block. The forever statement inside an initial block is helpful when setting an initial clock delay. Another application is a watchdog timer to terminate hung simulations:

initial begin
    #100_000;
    $display("WATCHDOG: time limit exceeded, possible hang");
    $finish;
end

Practice Exercise

Evaluate each code snippet. Determine if the code synthesizes to hardware. If it synthesizes, describe the resulting circuit. If it does not synthesize, identify its appropriate testbench application.

// 1
integer i;
always @(*) begin
    out = 8'h00;
    for (i = 0; i < 8; i = i + 1)
        out[i] = in_a[i] & in_b[i];
end

// 2
initial begin
    forever @(posedge clk)
        $display("clk rose at %0t", $time);
end

// 3
integer k;
always @(*) begin
    found = 1'b0;
    for (k = 7; k >= 0; k = k - 1) begin
        if (data[k] && !found) begin
            msb_pos = k[2:0];
            found   = 1'b1;
        end
    end
end

// 4
while (!rx_done) @(posedge clk);

// 5
integer m;
always @(*) begin
    result = 16'h0000;
    for (m = 0; m < WIDTH; m = m + 1)
        result = result + {{15{1'b0}}, data[m]};
end
Solution
  1. Synthesizes successfully. The synthesis tool creates eight parallel AND gates equivalent to out = in_a & in_b.
  2. Does not synthesize. This statement creates a simulation monitor that prints on every clock edge.
  3. Synthesizes successfully. The tool builds a priority encoder for the highest set bit. It unrolls into eight conditional steps. Add a default assignment to msb_pos to avoid latch inference when all input bits are zero.
  4. Does not synthesize. This construct waits dynamically on a runtime signal inside a verification environment.
  5. Synthesizes successfully if WIDTH is a parameter or constant. The tool builds an adder tree. If WIDTH is an input port, the loop bound is dynamic and synthesis fails.

Use for loops with constant boundaries in synthesizable RTL files. Use repeat, while, and forever constructs inside verification testbenches. The next article uses for loops to implement scalable bit-manipulation circuits.

← for Loops and Synthesis Loops as Hardware Generators →