In VHDL 2008
Is it possible to declare an unconsrained unsigned variable in a function?
For example:
Code:
function some_function ( x : unsigned ; y : unsigned ) return unsigned is
variable result : unsigned ; -- "result" is defined as an unconstrained unsigned.
begin
if x > y then
result := x ; -- "result" gets constrained according to the size of x
else
result := y ; -- "result" gets constrained according to the size of y
end if ;
return result ;
end function some_function ;
I don't see that VHDL 2008 provides a means to "copy" constraints by a signal or variable assignment as assumed in your code. I don't think that the syntax will be accepted by VHDL 2008.
On the other side, there's a well established method to set the range of internal procedure variables by attributes, which is used e.g. throughout IEEE package functions. Why should we use "unconstrained" bit vectors in this place?
function some_function ( x : unsigned ; y : unsigned ) return unsigned is
variable result : unsigned ; -- "result" is defined as an unconstrained unsigned. [COLOR="#FF0000"]KJ: If left as unconstrained, then how would you expect it to eventually get the size defined?[/COLOR]
begin
if x > y then
result := x ; -- "result" gets constrained according to the size of x [COLOR="#FF0000"]KJ: No it does not. What happens is that VHDL checks to see that 'result' and 'x' are both of the same type and the same size. If they are not compatible an error is declared when compiling.[/COLOR]
else
result := y ; -- "result" gets constrained according to the size of y [COLOR="#FF0000"]KJ: Ditto[/COLOR]
end if ;
return result ;
end function some_function ;
There are a couple of solutions: Since the function above is so simple, you could write it without any intermediate variables like this:
Code:
function some_function ( x : unsigned ; y : unsigned ) return unsigned is
begin
if x > y then
return x ;
else
return y ;
end if ;
end function some_function ;
More generally, if you did need to use intermediate variables and the size of those variables is different depending on the processing logic, you could use a function to compute the vector range. Imagine that you have a function called 'sel' like this...
Code:
function sel(Cond: Boolean; If_True: integer; If_False: integer) return integer is
begin
if Cond then
return If_True;
else
return If_False;
end if;
end function sel;
Then in your original code you could have the following to define the bits of the variable x
Code:
function some_function ( x : unsigned ; y : unsigned ) return unsigned is
variable result : unsigned(sel(x>y, x'high, y'high) downto sel(x>y, x'low, y'low));