Is it possible to write a function that can detect the input data width automatically? For example, consider the parity function below:
function parity;
input [31:0] data;
parity = ^ data;
endfunction
When parity(data)
is called, the input data should be limited to 32 bits.
Alternatively, one could write a macro, such as `PARITY(data)
in which the system function $bits
can detect the width of data and make the macro width-independent. Is it possible to have the same flexibility for functions?
Edit: I need my code to be synthesizable.
You can create a parameterized function. See section 13.8 in the LRM. It looks like the function must be declared inside a class like this:
virtual class C #(parameter WIDTH=32);
static function parity (input [WIDTH-1:0] data);
parity=^data;
endfunction
endclass
Then when you call the function parameterized it with the bits
task:
assign parity_bit = C#($bits(data))::parity(data);
Working example on EDA Playground.
You can use macros. The function can be declared like:
`define PARITY(FUNC_name, WIDTH) \
function FUNC_name (input [WIDTH-1:0] data); \
begin \
FUNC_name = ^ data; \
end \
endfunction
and you can call it with:
`PARITY(parity, 32);
assign parity_bit = parity(data);
This code is synthesizable in xilinx, altera and synopsys tools
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With