Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a generate with for loop in verilog

Tags:

verilog

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 ?

like image 676
CDN Avatar asked Sep 19 '14 00:09

CDN


People also ask

Can you do a for loop in Verilog?

A for loop is the most widely used loop in software, but it is primarily used to replicate hardware logic in Verilog. The idea behind a for loop is to iterate a set of statements given within the loop as long as the given condition is true.

Why We Use generate in Verilog?

Generate blocks are a mechanism by which we can generate lots of Verilog. To quote the Sutherland HDL guide, "generate blocks provide control over the creation of many types of module items. A generate block must be defined within a module, and is used to generate code within that module."

Can we use generate in always block?

We can only use the generate statement in concurrent verilog code blocks. This means we can't include it within always blocks or initial blocks. In addition to this, we have to use either an if statement, case statement or a for loop in conjunction with the generate keyword.

Can for loop be synthesized?

For loops can be synthesized. For loops in synthesizable code are used for expanding replicated logic. They are simply a way of shrinking the amount of code that is written by the hardware designer.


1 Answers

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 :) )

like image 116
Razko Avatar answered Oct 08 '22 14:10

Razko