Loops as Hardware Generators
This section demonstrates how to implement four common digital circuits with for loops. Each design benefits from parameterised loop replication and shows a distinct hardware pattern.
Gray Code Encoder
Section 3.5 described Gray code for clock domain crossing counters. Consecutive Gray code values differ by only one bit. The conversion equation is:
$$G_{N-1} = B_{N-1}, \qquad G_i = B_{i+1} \oplus B_i \ \text{for } i < N-1$$
The following module implements this equation:
`timescale 1ns / 1ps
`default_nettype none
module bin_to_gray #(
parameter N = 8
) (
input wire [N-1:0] bin_in,
output reg [N-1:0] gray_out
);
integer i;
always @(*) begin
gray_out[N-1] = bin_in[N-1];
for (i = N - 2; i >= 0; i = i - 1) begin
gray_out[i] = bin_in[i+1] ^ bin_in[i];
end
end
endmodule
When $N = 4$, the tool unrolls the loop into three XOR gates and one direct wire connection (Figure 1). When $N = 16$, the tool creates fifteen gates and one wire. Parameterised loops eliminate manual indexing errors.
A testbench verifies that consecutive output words change by only one bit:
integer t;
reg [N-1:0] prev_gray, diff;
initial begin
for (t = 0; t < (1 << N); t = t + 1) begin
bin_in = t[N-1:0];
#10;
if (t > 0) begin
diff = gray_out ^ prev_gray;
if (diff == 0 || (diff & (diff - 1)) != 0) // Zero bits or more than one bit changed
$display("FAIL at %0d: diff=%b", t, diff);
end
prev_gray = gray_out;
end
end
The expression diff & (diff - 1) clears the least significant active bit. The expression evaluates to zero when diff contains exactly one active bit.
Leading-Zero Counter
Floating-point normalizers and bus arbiters require the position of the most significant active bit. A leading-zero counter scans input bits from high to low to locate the first active bit:
`timescale 1ns / 1ps
`default_nettype none
module leading_zero_count #(
parameter N = 8
) (
input wire [N-1:0] data_in,
output reg [$clog2(N):0] lzc_out, // 0 to N, requires clog2(N)+1 bits
output reg all_zero
);
integer i;
reg found;
always @(*) begin
lzc_out = {($clog2(N)+1){1'b0}};
all_zero = 1'b0;
found = 1'b0;
for (i = N - 1; i >= 0; i = i - 1) begin
if (!found && data_in[i]) begin
lzc_out = N - 1 - i;
found = 1'b1;
end
end
if (!found) begin
lzc_out = N;
all_zero = 1'b1;
end
end
endmodule
The synthesis tool unrolls all $N$ loop iterations. The found flag ensures that only the highest active bit updates the output. The synthesized circuit forms a multiplexer chain that functions as a priority encoder. Changing the loop direction creates a trailing-zero counter.
Bit Reversal
The following module reverses the bit order of an input bus:
`timescale 1ns / 1ps
`default_nettype none
module bit_reverse #(
parameter N = 8
) (
input wire [N-1:0] data_in,
output reg [N-1:0] reversed
);
integer i;
always @(*) begin
for (i = 0; i < N; i = i + 1) begin
reversed[i] = data_in[N-1-i];
end
end
endmodule
When unrolled, this code connects wire inputs directly to wire outputs: reversed[0] = data_in[7], reversed[1] = data_in[6], and continuing through bit 7. This circuit requires zero logic gates. It uses only physical wiring resources. Fast Fourier transform (FFT) address decoders, cryptographic permutations, and byte-endian converters use this zero-cost structure.
Equality Comparator
The following module compares two binary words for equality:
`timescale 1ns / 1ps
`default_nettype none
module eq_compare #(
parameter N = 8
) (
input wire [N-1:0] a,
input wire [N-1:0] b,
output reg equal
);
integer i;
reg mismatch;
always @(*) begin
mismatch = 1'b0;
for (i = 0; i < N; i = i + 1) begin
mismatch = mismatch | (a[i] ^ b[i]);
end
equal = ~mismatch;
end
endmodule
The loop synthesizes into $N$ XOR gates that feed an OR reduction tree and an output inverter. In production RTL, write equal = (a == b). This loop example clarifies the internal structure of the comparator.
Testbench for Leading-Zero Counter
The following testbench verifies the leading-zero counter:
`timescale 1ns / 1ps
`default_nettype none
module tb_lzc;
localparam N = 4;
reg [N-1:0] data_in;
wire [$clog2(N):0] lzc_out;
wire all_zero;
leading_zero_count #(.N(N)) u_dut (.data_in(data_in), .lzc_out(lzc_out), .all_zero(all_zero));
initial begin
$dumpfile("tb_lzc.vcd");
$dumpvars(0, tb_lzc);
end
function automatic [$clog2(N):0] ref_lzc; // Behavioral reference model
input [N-1:0] d;
integer k;
begin
ref_lzc = N;
for (k = N - 1; k >= 0; k = k - 1) begin
if (d[k] && ref_lzc == N)
ref_lzc = N - 1 - k;
end
end
endfunction
integer test, fail_count;
initial begin
fail_count = 0;
for (test = 0; test < (1 << N); test = test + 1) begin
data_in = test[N-1:0];
#10;
if ((data_in == 0) !== all_zero) begin
$display("FAIL all_zero: data=%b got=%b", data_in, all_zero);
fail_count = fail_count + 1;
end
if (lzc_out !== ref_lzc(data_in)) begin
$display("FAIL lzc: data=%b expected=%0d got=%0d", data_in, ref_lzc(data_in), lzc_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 compares the synthesized module against a software behavioral reference model. Exhaustive verification is feasible for inputs up to approximately twenty bits. For larger bit widths, use constrained random stimulus.
Design Patterns Summary
Use a parameterised for loop when an identical operation applies across multiple bits or bus slices:
- Define the single-bit or adjacent-bit operation inside the loop body.
- Control the physical replication count using module parameters.
- Use flags to implement priority networks when needed.
- If logic requires state storage across clock edges, use sequential registers.
The next article examines the generate construct, which replicates module instances and structural nets rather than procedural statements.