Factor out a calculation, write synthesizable loops, and keep RTL separate from test utilities.
Functions, tasks, and loops reduce repeated code. Their effect depends on context: RTL describes hardware, while a testbench can wait and advance simulation time.
Return a value with a function
This function counts set bits in two words:
module popcount_pair #( parameter
WIDTH
=
8
) (
input wire [WIDTH-1:0] i_a,
input wire [WIDTH-1:0] i_b,
output wire [31:0] o_count_a,
output wire [31:0] o_count_b
);
function [31:0] count_ones;
input [WIDTH-1:0] value;
integer index;
begin
count_ones = 0;
for (index = 0; index < WIDTH; index = index + 1)
count_ones = count_ones + value[index];
end
endfunction
assign o_count_a = count_ones(i_a);
assign o_count_b = count_ones(i_b);
endmodule
The call consumes no simulation time. Fixed loop bounds let synthesis build a combinational calculation. Additions may form a chain, so a loop that looks short can still create a long path.
The 32-bit result keeps the demonstration simple. In a real design, choose the result width from its maximum value, WIDTH, and check operand widths and signedness.
Return several results with a task
A task can have input, output, and bidirectional arguments. Here it orders two values:
module min_max_pair ( input wire [7:0] i_a, input wire [7:0] i_b, output reg [7:0] o_min, output reg [7:0] o_max); task order_pair; input [7:0] a; input [7:0] b; output [7:0] low; output [7:0] high; begin if (a <= b) begin low = a; high = b; end else begin low = b; high = a; end end endtask always @* begin order_pair(i_a, i_b, o_min, o_max); endendmodule
The task is combinational and assigns both outputs on every path. RTL tasks can also be called from clocked blocks; their statements must be synthesizable and suit that context.
A testbench task may wait:
task check_sum; input [7:0] a; input [7:0] b; input [8:0] expected; begin i_a = a; i_b = b; #1; if (o_sum !== expected) $display("ERROR: %0d + %0d", a, b); endendtask
#1 allows one time unit before checking the output. That delay belongs to simulation; it is not a portable hardware delay. !== fails when an output contains X or Z where a known value is expected.
Read a loop as hardware
For synthesizable RTL, use finite bounds that the tool can determine. Dependencies between iterations determine how the unrolled operations connect.
A for loop inside a clocked block does not automatically take one cycle per iteration: all iterations execute during the same activation. Multi-cycle work needs an explicit counter, registers, and control logic.
repeat, while, and forever are common in simulation. Synthesis support depends on their form and the tool. A testbench waiting loop should not be copied into the circuit.