Search code examples
verilogsystem-verilogmodelsim

Verilog, truncate genvar width size


How do I truncate the width of a genvar variable? For instance, if I have:

parameter LENGTH = 8;

genvar i;
for(i = 0; i < LENGTH; i = i + 2) begin
   somemodule #(WIDTH($clog2(LENGTH))
               )
               tmp (.a(i)
                   ,.b(i+1)
                   ,.c(output)
                   );
end
endgenerate

When I simulate in ModelSim, I would get port size does not match connection size. I know the problem lies in that genvar is 32 bit wide, and my module's width varies.

I tried

genvar [$clog2(LENGTH)-1:0] i;

and

.a(i[$clog2(LENGTH)-1:0])

but they are not syntactically correct.

How do I get around this problem?


Solution

  • You can use an intermediate parameter declared with a data type for this

    parameter int LENGTH = 8;
    parameter int WIDTH  = $clog2(LENGTH);
    for(genvar i = 0; i < LENGTH; i = i + 2) begin
    
       parameter bit [WIDTH-1:0] A = i;
       somemodule #(.WIDTH(WIDTH))
                   )
                   tmp (.a(A)
                       ,.b(A+1'b1)
                       ,.c(output)
                       );
    end