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:
Then when you call the function parameterized it with the
bits
task:Working example on EDA Playground.
Interesting question. According to my knowledge, I don't think that's possible. I would also stay away from macros (even more problems). I can propose a synthesizable workaround:
assign my_parity_bits = parity({16'd0, my_data});
Hopefully, synthesis tool would ignore those 0's but you will have to check it yourself.WIDTH
parameter and actual data as aninput
vector. To do this, I would advise you to write a generic module that does exactly what your functionparity
does. Then, write a module which will be aparity wrapper
. Inside this wrapper I would perform math operations on inputWIDTH
parameter to determine number ofparity
modules needed for input data and instantiate those modules in agenerate
loop.Remember that Verilog is a hardware description language, thus such limitations. Think about what your code will synthesize into when writing RTL.
It is possible using unbounded arrays.
Unfortunately SystemVerilog doesn't have decent support for unbounded arrays. The LRM seems to equate unbounded with dynamic, which suggests it's going to be almost impossible to create something synthesisable. VHDL has unbounded arrays which are supported by tools and incredibly useful so it's a pity that SystemVerilog didn't include this feature properly.
Here is an example:
This is running on Modelsim on EDAPlayground here: http://www.edaplayground.com/x/3tS
EDIT 1: Updated the code - I just realised it's possible to call
new[]
at initialisation and thus statically, so in theory synthesis tools could support this. It would be interesting to synthesise this and see...EDIT 2: Thought I'd try synthesising and unsurprisingly Quartus doesn't like this:
You can use macros. The function can be declared like:
and you can call it with:
This code is synthesizable in xilinx, altera and synopsys tools