All courses

Verilog · Lesson 31 of 93

Generate blocks, loops, and reusable calculations

Parameterized Design

Separate elaboration from clocked behavior

A generate loop replicates hardware during elaboration. Its genvar is not a counter that advances each clock. A procedural for loop describes operations within a procedural block; a synthesis tool may unroll a statically bounded combinational loop. Neither syntax automatically means that one adder is reused across many cycles.

Use generate-if when a parameter selects a structural variant. Use a clocked state machine when an algorithm must take several cycles. Large loops can infer more logic than expected; inspect synthesis reports instead of judging area from line count.

Give each generated scope a stable name

Verilog
module bit_mask #(parameter integer WIDTH = 8) (
  input wire [WIDTH-1:0] data,
  input wire [WIDTH-1:0] mask,
  output wire [WIDTH-1:0] result
);
  genvar bit_index;
  generate
    for (bit_index = 0; bit_index < WIDTH; bit_index = bit_index + 1) begin : g_bit
      assign result[bit_index] = data[bit_index] & mask[bit_index];
    end
  endgenerate
endmodule

This Verilog-2001 example requires WIDTH >= 1. It creates WIDTH parallel gates. In normal RTL a single vector expression would be simpler; the expanded form teaches structural replication and named scopes.

Test WIDTH values 1, 2, and 8 and compare result with data & mask. Reject WIDTH=0 in your supported-configuration checks: a negative-looking range does not mean an empty vector. For pointer widths in parameterized FIFOs, guard the depth-one case instead of assuming $clog2(1) gives a usable register width.

Verilog functions return a value without consuming simulation time. Tasks can have multiple output arguments and can consume time in a testbench; delays/event controls are not generally synthesizable. A helper containing a loop still represents hardware when used in synthesizable RTL. Distinguish constant functions used in elaboration from functions evaluated on runtime signals.

Further study and tool references

Check the language mode and supported features for your installed simulator.

Verilator language supportIcarus compiler flags