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

for Loops and Synthesis

Section 5.3 showed a for loop inside a priority encoder. This section explains loops in hardware design. A for loop in register transfer level (RTL) code does not execute sequentially in real time. The synthesis tool unrolls the loop once during elaboration. The resulting circuit contains $N$ parallel copies of the loop body operating concurrently.

The Software Model Versus Hardware Reality

Software developers usually read a loop as sequential execution over time:

int parity = 0;
for (int i = 0; i < 8; i++) {
    parity ^= data[i];
}

The C code runs in eight consecutive time steps. In contrast, the equivalent Verilog description creates eight chained XOR gates. All eight gates exist simultaneously in physical silicon. The circuit computes continuously without time iterations.

Requirements for Synthesizable Loops

A synthesis tool must unroll the loop completely before gate mapping. Therefore, loop bounds must evaluate to constants during elaboration. You must use literals, parameter values, or localparam constants for loop boundaries. You must declare the loop index as an integer.

The loop body must contain only synthesizable statements. The loop must also terminate deterministically. If a loop bound uses a dynamic input signal, synthesis fails. The tool cannot determine the required number of physical hardware copies.

Parameterised Parity Generator

The parity of a binary word is the XOR sum of its bits:

$$P = b_{N-1} \oplus b_{N-2} \oplus \cdots \oplus b_0$$

The following module implements this calculation:

`timescale 1ns / 1ps
`default_nettype none

module parity_gen #(
    parameter N = 8
) (
    input  wire [N-1:0] data_in,
    output reg          parity_out    // 1 when the number of ones is odd
);

    integer i;

    always @(*) begin
        parity_out = 1'b0;
        for (i = 0; i < N; i = i + 1) begin
            parity_out = parity_out ^ data_in[i];
        end
    end

endmodule

The accumulator variable begins at 0. Each unrolled iteration adds one bit to the XOR operation. When $N = 4$, the tool elaborates the following sequence:

parity_out = 0 ^ data_in[0];
parity_out = parity_out ^ data_in[1];
parity_out = parity_out ^ data_in[2];
parity_out = parity_out ^ data_in[3];

This sequence forms a cascaded chain of XOR gates (Figure 1). Most synthesis tools rebalance this chain into a balanced tree of depth $\log_2 N$. The tree implementation provides identical logic with lower propagation delay.

Unrolled parity chain
Figure 1: Four iterations, four XOR gates, all present at once

In production RTL, designers usually write the reduction operator ^data_in. This example uses a loop to illustrate the hardware unrolling mechanism.

Counting Active Bits (Population Count)

A population count circuit counts the number of active high bits in an input word:

`timescale 1ns / 1ps
`default_nettype none

module popcount #(
    parameter N = 8
) (
    input  wire [N-1:0]           data_in,
    output reg  [$clog2(N+1)-1:0] count_out    // 0 to N needs clog2(N+1) bits
);

    integer i;

    always @(*) begin
        count_out = {$clog2(N+1){1'b0}};
        for (i = 0; i < N; i = i + 1) begin
            count_out = count_out + {{($clog2(N+1)-1){1'b0}}, data_in[i]};
        end
    end

endmodule

The loop description resembles $N$ sequential additions. However, the synthesis tool does not build $N$ chained ripple-carry adders. The tool unrolls the loop into one combinational expression and generates an adder tree. The resulting carry-save adder structure matches the Wallace tree architecture introduced in Section 2.3.

Parameterised Scaling

Loops enable concise descriptions of scalable hardware blocks:

parity_gen #(.N(8))  u_p8  (.data_in(data8),  .parity_out(p8));
parity_gen #(.N(32)) u_p32 (.data_in(data32), .parity_out(p32));

The same module definition scales to 8 bits or 32 bits without code modifications. Writing scalable code prevents manual repetition and reduces verification errors during design reviews.

Verification Testbench

The following testbench verifies the parity generator module:

`timescale 1ns / 1ps
`default_nettype none

module tb_parity_gen;

    localparam N = 8;

    reg  [N-1:0] data_in;
    wire         parity_out;

    parity_gen #(.N(N)) u_dut (.data_in(data_in), .parity_out(parity_out));

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

    function automatic compute_parity;      // Reference model in simulation
        input [N-1:0] d;
        integer k;
        begin
            compute_parity = 1'b0;
            for (k = 0; k < N; k = k + 1)
                compute_parity = compute_parity ^ d[k];
        end
    endfunction

    integer fail_count, test_num;

    initial begin
        fail_count = 0;
        for (test_num = 0; test_num < (1 << N); test_num = test_num + 1) begin   // All 256 patterns
            data_in = test_num[N-1:0];
            #10;
            if (parity_out !== compute_parity(data_in)) begin
                $display("FAIL: data_in=%b expected %b got %b", data_in, compute_parity(data_in), parity_out);
                fail_count = fail_count + 1;
            end
        end
        if (fail_count == 0)
            $display("PASS: all %0d vectors.", 1 << N);
        else
            $display("FAIL: %0d failures.", fail_count);
        $finish;
    end

endmodule

The testbench contains loops inside the automatic function and the stimulus process. These simulation loops execute sequentially over simulation time. The constant-bound restriction applies only to hardware synthesis.

A synthesizable loop describes repeated physical structure rather than sequential time operations. The next article examines while, repeat, and forever loops, and explains why they remain restricted to verification testbenches.

← Priority or Parallel while, repeat and forever →