Using a generate with for loop in verilog

CDN picture CDN · Sep 19, 2014 · Viewed 95.7k times · Source

I'm trying to understand why we use generate in verilog along with a for loop.

Using a generate and for loop together:

reg [3:0] temp;
genvar i;
generate
for (i = 0; i < 3 ; i = i + 1) begin: 
    always @(posedge sysclk) begin
        temp[i] <= 1'b0;
    end
end
endgenerate

Using only for loop:

reg [3:0] temp;
genvar i;
always @(posedge sysclk) begin
  for (i = 0; i < 3 ; i = i + 1) begin: 
    temp[i] <= 1'b0;
    end
end

I'm considering the two snippets would basically produce the same result i.e. temp[0] to temp[10] equal to value 0. What is the difference/advantage we see by using a generate statement in this case ?

Answer

Razko picture Razko · Sep 22, 2014

In general, the main difference between generate for loop and regular for loop is that the generate for loop is generating an instance for each iteration. Meaning that in your example there will be 3 always blocks (as opposed to 1 block in the regular loop case).

A good example of code that requires generate for is:

module A();
..
endmodule;

module B();
parameter NUM_OF_A_MODULES = 2; // should be overriden from higher hierarchy
genvar i;
for (i=0 i<NUM_OF_A_MODULES; i=i+1) {
  A A_inst();
}
endmodule;

In this example a regular for cannot do the work of creating NUM_OF_A_MODULES instances.

In your example, you can acheive the required result in both ways. (as long as you fix some minor bugs :) )