'Getting the size of a SystemVerilog macro range
I have a code with a number of different signals whose width is defined by macro ranges like this:
`define MY_RANGE_1 8:2
`define MY_RANGE_2 12:0
`define MY_RANGE_3 5:0
I want to obtain the widths of those signals in order to later use them in new signal definitions. Such a feature should return 7 for MY_RANGE_1, then for MY_RANGE_2 it should return 13, and for MY_RANGE_3 it should return 6. Of course, there are array size methods like $size(MY_FEATURE_1), but they won't be appropriate for my purposes because they don't return a constant value (so you can't define new signal ranges through them). Is there a way to achieve this?
Solution 1:[1]
Text macros in verilog are just fragments of text and have no syntactic meaning. Therefore, there is no way to extract range info from the macro itself. However, in System verilog there is the predefine function *$bits" which returns bit width of a declared variable or a type. It can be used in subsequent variable declarations as well. For example,
`define MY_RANGE_1 8:2
module top;
reg[`MY_RANGE_1] myvar;
reg [$bits(myvar) - 1: 0] myvar1;
initial begin
$display("type: %0d", $bits(reg[`MY_RANGE_1]));
$display("var: %0d", $bits(myvar));
$display("var1: %0d", $bits(myvar1));
end
endmodule // top
The result of $bits is 7 in all cases.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |
