Convert enum type to std_logic_vector VHDL - vhdl

I want to know if it is possible to convert a enum type, like FSM states to std_logic_vector or integer. I'm doing a testbench with OSVVM for a FSM and I want to use the scoreboard package to automatically compare the expected state with the actual one.
Thanks!

To convert to integer, use:
IntVal := StateType'POS(State) ;
From there, it is easy to convert to std_logic_vector, but I prefer to work with integers when possible as they are smaller in storage than std_logic_vector. For verification, it will be easier if you start to think more about integers when the value is less than 32 bits.
If you need it as std_logic_vector, using only numeric_std you can:
Slv8Val := std_logic_vector(to_unsigned(IntVal, Slv8Val'length)) ;
For verification, I liberally use numeric_std_unsigned, so the conversion is a easier:
Slv8Val := to_slv(IntVal, Slv8Val'length) ;
In the event you have an integer and want to convert it back to a enumerated value, you can use 'VAL.
State := StateType'VAL(IntVal) ;
In OSVVM, we use records with resolved values to create a transaction interface. We have a resoled types for integers (osvvm.ResolutionPkg.integer_max). We transfer enumerated values through the record using 'POS (as we put it in) and 'VAL (as we get it out).
Note don't confuse 'VAL with 'VALUE. 'VALUE converts a string to a value - opposite to 'IMAGE.
You of course learn all of this in SynthWorks' OSVVM class :).

Maybe like this...
function my_func(inp : t_my_enum) return integer is
begin
case inp is
when stateA =>
return 1;
when stateB =>
return 2;
when others =>
return 0;
end case;
end function my_func;
... <= my_func(stateB);`

Related

How to return record with unconstrained 2d array from a function

I have a record type(REC) which contains an element of type VECTOR which is an unconstrained 2d array of STD_LOGIC:
package TEST is
type VECTOR is array (NATURAL range <>, NATURAL range <>) of STD_LOGIC;
type REC is record
data : VECTOR;
end record REC;
function con(
a : REC;
b : REC)
return REC;
end package TEST;
When declaring the body of the con function I want to specify the size of the REC.data array like so:
package body TEST is
function con(
a : REC;
b : REC)
return REC is variable r : REC(
data(a.data'length(1) + b.data'length(1) - 1 downto 0, a.data'length(2) - 1 downto 0));
begin
-- . . . do things
end function con;
end package body TEST;
but in the line where I attempt to set the size of data it Vivado throws the following error:
Sliced name is allowed only on single-dimensional arrays
Does this mean I cannot have an unconstrained 2d arraign in a record or is there a different method for defining the size of it in the con function ?
---- EDIT ----
Since I now understand that it is not possible to use 2d arrays in this context what method should I use to create a function which:
Takes two 2d arrays (or arrays of arrays) of size [x][y] and [z][y] as inputs
Outputs an array of size [x+z][y]
With both input arrays being unconstrained and the output array being constrained to size [x+z][y]
And all arrays (input and return) be a record type
user1155120 I don't think I fully understand what you are trying to say. Are you saying my code is not
a minimal reproducible example, because except for me forgetting to include the STD_LOGIC library
the code reproduces the problem when I paste it into Vivado, and it is about as minimal as I can get it.
Or are you saying that the code you linked as this works works for you, because at least in my
Vivado it still throws the same error ? – Mercury 4 hours ago
The original comment was meant for Tricky. There's a missing return statement in the function con which would prevent use in an example.
It isn't clear if record constraints (a -2008 feature) are supported in Vivado Simulator. In Vivado Synthesis Guide UG901 2020.1 we see all sorts of wonderful uses of record types from everything to inferring ram to record elements of record types. Xilinx has been busy.
It'd seems odd if unconstrained elements in record type declarations were supported but not record constraints (they're pretty much a package deal, pun aside). Note the comment called it a -2008 feature.
A record constraint is limited to supply the constraint of an element or subelement that is of an unconstrained type (typically arrays). VHDL has always been capable of supplying multi-dimensional array constraints. The language of the standard is particular based on the flexibility of the syntax.
This code is VHDL -2008 compliant and provides your record constraint:
library ieee; -- ADDED for MCVe
use ieee.std_logic_1164.all; -- ADDED
package TEST is
type VECTOR is array (NATURAL range <>, NATURAL range <>) of STD_LOGIC;
type REC is record
data: VECTOR;
end record REC;
function con (a: REC; b: REC) return REC;
end package TEST;
package body TEST is
function con (a: REC; b: REC) return REC is
variable r:
REC ( -- record constraint:
data (
natural range a.data'length(1) + b.data'length(1) - 1 downto 0,
natural range a.data'length(2) - 1 downto 0
)
);
begin
-- . . . do things
return r; -- ADDED required return statement
end function con;
end package body TEST;
You'll note the changes to the record constraint from yours is the addition of natural range before each range of the element data constraint.
From IEEE Std 1076-2008 5.3.3 Record types:
record_constraint ::=
    ( record_element_constraint { , record_element_constraint } )
record_element_constraint ::= record_element_simple_name element_constraint
From 6.3 Subtype declarations:
element_constraint ::=
      array_constraint
    | record_constraint
Here the element data is an array so an array_constraint is appropriate.
From 5.3.2 Array types, 5.3.2.1:
array_constraint ::=
    index_constraint [ array_element_constraint ]
    | ( open ) [ array_element_constraint ]
Because element data array elements are scalar (enumeration type STD_LOGIC) we follow index_constraint.
index_constraint ::= ( discrete_range { , discrete_range } )
discrete_range ::= discrete_subtype_indication | range
The code shown above uses a discrete subtype indication for the index ranges of the element data dimensions and successfully analyzes (compiles).
From 5.2.2 Scalar types, 5.2.2.1:
range ::=
      range_attribute_name
    | simple_expression direction simple_expression
direction ::= to | downto
The constraint in the question uses a range with simple expressions and direction.
So why did it produce the error message about multi-dimensional slices?
In 9. Expressions, 9.1 the BNF, simple_expression -> term -> factor -> primary -> name.
In 8. Names, 8.1 name -> slice_name, only multi-dimensional slices are not allowed semantically in 8.5 Slice names who's BNF tells us it's syntactically valid:
slice_name ::= prefix ( discrete_range )
The prefix of a slice shall be appropriate for a one-dimensional array object. The base type of this array type is the type of the slice.
and semantically the prefix data is not appropriate for a one-dimensional array object.
These comments provide bit more context for the problem although it isn't clear which version the record constraint you used in the reported eventual success:
#Mercury when you add a (VHDL) file to Vivado, it's by default set to use VHDL 93, but not 2008. Go
to the property Window and change the file type from VHDL to VHDL 2008. I'm not sure why it
prints the wrong error message in your case. (Vivado likes to confuse users with wrong error messages
...). Anyhow, it should have reported your feature is only supported in 2008 mode. – Paebbels 3 hours
ago
#Paebbels Thank you, that fixed the problem, maybe add it as a sub note to your response so I can
mark it as accepted answer. You just saved me hours of frustration. And I'm already getting familiar with
Vivado's shenanigans, my Favorit one of which is "ERROR close to ..." which has to be one of the most
useless error messages I have experience in a long time :) – Mercury 3 hours ago
As far as detecting -2008 source, there are no -1993 syntax errors and no -2008 new reserved word, delimiters, separators or graphics characters in either the primary unit or the secondary.
That leaves you at the mercy of semantic analysis which failed. You could also note the unconstrained record element wasn't reported during analysis of the package declaration. It occurred during evaluation of the variable r. All declared objects are required to be constrained. VHDL doesn't have a recital of all features, semantics can be restrictive as well. It's legal in places to have unconstrained elements and objects.
Associating semantics rules found in the text of the standard with an textual element of the particular declaration or statement can be tough and the squeaky wheel gets the lubricant. Record constraints are relatively new to VHDL implementations.
The problem appears to have been one of tool familiarity.
This is the definition of row and column merges from PoC's vectors package, see lines starting at 359:
function slm_merge_rows(slm1 : T_SLM; slm2 : T_SLM) return T_SLM is
constant ROWS : positive := slm1'length(1) + slm2'length(1);
constant COLUMNS : positive := slm1'length(2);
variable slm : T_SLM(ROWS - 1 downto 0, COLUMNS - 1 downto 0);
begin
for i in slm1'range(1) loop
for j in slm1'low(2) to slm1'high(2) loop -- WORKAROUND: Xilinx iSIM work-around, because 'range(2) evaluates to 'range(1); see work-around notes at T_SLM type declaration
slm(i, j) := slm1(i, j);
end loop;
end loop;
for i in slm2'range(1) loop
for j in slm2'low(2) to slm2'high(2) loop -- WORKAROUND: Xilinx iSIM work-around, because 'range(2) evaluates to 'range(1); see work-around notes at T_SLM type declaration
slm(slm1'length(1) + i, j) := slm2(i, j);
end loop;
end loop;
return slm;
end function;
function slm_merge_cols(slm1 : T_SLM; slm2 : T_SLM) return T_SLM is
constant ROWS : positive := slm1'length(1);
constant COLUMNS : positive := slm1'length(2) + slm2'length(2);
variable slm : T_SLM(ROWS - 1 downto 0, COLUMNS - 1 downto 0);
begin
for i in slm1'range(1) loop
for j in slm1'low(2) to slm1'high(2) loop -- WORKAROUND: Xilinx iSIM work-around, because 'range(2) evaluates to 'range(1); see work-around notes at T_SLM type declaration
slm(i, j) := slm1(i, j);
end loop;
for j in slm2'low(2) to slm2'high(2) loop -- WORKAROUND: Xilinx iSIM work-around, because 'range(2) evaluates to 'range(1); see work-around notes at T_SLM type declaration
slm(i, slm1'length(2) + j) := slm2(i, j);
end loop;
end loop;
return slm;
end function;
The definition of T_SLM is:
type T_SLM is array(natural range <>, natural range <>) of std_logic;
Currently, I see no problem in nesting this code in another layer like your unconstrained record.
Edit:
Thie code above requires VHDL 2008 to be enabled in Vivado.
When VHDL files are added to Vivado, it's by default set to use VHDL 93, but not 2008. Go to the property Window and change the file type from VHDL to VHDL 2008``.
The printed error message is misleading and points to a false feature being used. The correct message should be it's a VHDL-2008 feature, please enable it.

VHDL initialize signal with maximum value of type

I have this definition:
subtype sample_t is signed(SAMPLE_WIDTH-1 downto 0);
Now in the code I want to set a signal to the maximum value of sample_t divided by 2:
signal max_sample : sample_t;
max_sample <= to_signed(max_sample'<some attribute>/2,max_sample'LENGTH);
I've looked at attributes sample_t'HIGH and sample_t'RIGHT but these seem to return the highest subscript of the array.
From this list: https://www.csee.umbc.edu/portal/help/VHDL/attribute.html
T'HIGH is the highest value of type T.
A'HIGH is the highest subscript of array A or constrained array type.
How to use the first definition on sample_t?
One of the commenters suggestions:
max_sample <= (max_sample'LEFT => '0', others => '1');
works. But this:
max_sample <= (max_sample'LEFT => '0', others => '1')/2;
fails with "OTHERS is illegal aggregate choice for unconstrained target".
why this error?
In VHDL, signed is an array type, not an integer. The core language only knows that it is a collection of std_logic objects. It's interpretation as a number is only by convention introduced by the numeric_std library functions defining the operators and type casts for signed. As such, integer specific attributes aren't going to work on an array type.
The reason why your last attempt at division fails is that the aggregate expression forming the dividend doesn't yet have a fully determined range due to the others. The aggregate is still just an intermediate temporary and can't pick up its length from max_sample. That prevents the division operator from compiling.
It will compile if you use a fully constrained range:
max_sample <= (max_sample'high => '0', max_sample'high-1 downto max_sample'low => '1') / 2;
Or if you use a qualified expression:
max_sample <= sample_t'(max_sample'high => '0', others => '1') / 2;
An alternate solution is just to subtype integer instead of using signed. Then you can use it in a more integery way:
constant SAMPLE_T_MAX : integer := 2**(SAMPLE_WIDTH-1)-1;
subtype sample_t is integer range -SAMPLE_T_MAX-1 to SAMPLE_T_MAX;
max_sample <= sample_t'high; -- Assuming that the "divide by 2" was just to avoid the sign bit
This will not work if sample_t_max exceeds the largest integer size your tooling supports which is still typically 32-bits including the sign. Also, for practical reasons, it is best not to use integer types for signals that will be exposed on the top level port after synthesis.
Otherwise you have to work within the limitations of using array types for numerics. Your options are to resort to bit twiddling as above or just directly compute the max value similarly to the integer subtype:
constant SAMPLE_T_MAX : integer := 2**(sample_t'length-1)-1;
max_sample <= to_signed(SAMPLE_T_MAX, max_sample'length);
The accepted answer from Kevin Thibedeau could not be readily reconciled with the actual question (why this error?). The answer can be explained in terms of the VHDL standard.
First a Minimum, Complete, and Verifiable example can be constructed for the question:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity foo is
end entity;
architecture fum of foo is
constant SAMPLE_WIDTH: natural := 42; -- pick a number
subtype sample_t is signed(SAMPLE_WIDTH-1 downto 0);
signal max_sample : sample_t;
begin
-- max_sample <= (max_sample'LEFT => '0', others => '1'); -- analyzes
max_sample <= (max_sample'LEFT => '0', others => '1')/2; -- Doesn't analyze
end architecture;
Because we're dealing with semantic rules during analysis (compile) the example doesn't have to do anything besides replicate the error. Error messages aren't standardized in VHDL and will vary by implementation.
The semantics for using an others choice in an aggregate:
IEEE Std 1076-2008 9.3 Aggregates, 9.3.3 Array aggregates, para 7 (in part):
The index range of an array aggregate that has an others choice shall be determinable from the context. That is, an array aggregate with an others choice shall appear only in one of the following contexts:
...
e) As a value expression in an assignment statement, where the target is a declared object (or member thereof), and either the subtype of the target is a fully constrained array subtype or the target is a slice name
This is why the first example (commented out) analyzes. sample_t is a fully constrained subtype, see 5. Types, 5.1 General the definition of fully constrained, para 6 (in part):
A composite subtype is said to be fully constrained if:
-- It is an array subtype with an index constraint and the element subtype either is not a composite subtype or is a fully constrained composite type, or
...
Where the sample_t element base type is std_ulogic and the subtype has an index constraint.
Back to the second example.
We don't satisfy rule e), the aggregate isn't a value expression for the assignment statement, it's an operand for the division operator defined by the "/" function for overload in IEEE package numeric_std:
-- Id: A.25
function "/" (L : UNRESOLVED_SIGNED; R : INTEGER) return UNRESOLVED_SIGNED;
-- Result subtype: UNRESOLVED_SIGNED(L'LENGTH-1 downto 0)
-- Result: Divides an UNRESOLVED_SIGNED vector, L, by an INTEGER, R.
-- If NO_OF_BITS(R) > L'LENGTH, result is truncated to L'LENGTH.
(For earlier revisions of numeric_std the parameter and result types would be SIGNED instead of UNRESOLVED_SIGNED, -2008 formally defines how resolution functions of composite types drivers are defined.)
Because the rules of 9.3.3 paragraph 7 are inclusive instead of exclusive we
need to find a rule that allows us to use the aggregate, and one is readily identified:
i) As the operand of a qualified expression whose type mark denotes a fully constrained array subtype
We can use a qualified expression:
max_sample <= sample_t'(max_sample'LEFT => '0', others => '1')/2;
And this analyzes (compiles) successfully.
To clarify the value expression being assigned to max_sample is the result of division by 2 which uses an operator overload and who's function does not return a constrained subtype. (UNRESOLVED_SIGNED or SIGNED is not constrained).
The reason why there are inclusive rules is to allow the code for associating values with elements of an aggregate to be determined at analysis time (compile time). You'd find by examining previous revisions of the VHDL standard that the list of inclusive rules has been expanded.
The answer to your question with respect to the second example:
max_sample <= (max_sample'LEFT => '0', others => '1')/2;
is that the elements of the aggregate can't be identified without knowing the subtype from context.
If you were to look at the output of the parser producing an abstract syntax tree used for semantic analysis the right hand side expression in the assignment statement can be expressed hierarchically. (11.6 Concurrent signal assignment statements, the waveform is comprised of one or more waveform elements, see 10.5.2 Simple signal assignments, 10.5.2.1 General, a waveform element can contain a value expression, see 10.5.2.2 Executing a simple assignment statement, 9. Expressions, 9.1 General the BNF.)
Using inclusive rules alleviates the need of traversing the expression hierarchy and calculating the subtype of the aggregate (an operand) during analysis and would require semantic characterization of the "/" function not required by the standard. You can also construct cases where the subtype can't be readily ascertained by characterization at analysis time. The result is the rules found in 9.3.3 Array aggregates paragraph 7.
The qualified expression provides the subtype directly.

Integer Range to vector

I've had an issue converting a vectors inputs to integers in my code. I am new to VHDL but the below code works with the integer RANGE commented out code but there is an error when I try to convert the vector values to an integers. Here is a copy of my code and error:
Update1:
I've tried your fix and it takes care of one of the errors but the new error message and code looks like this:
In according to your declaration in follow line type mem is array (...) of std_logic_vector(...) your memory waits for std_logic_vector type rather than unsigned like in your assignment RAMArray(unsigned(addr)) <= unsigned(din).
Here it is not sufficient to only use a type conversion to unsigned, but you have to add type conversion function to_integer in the argument. In other words
RAMArray(to_integer(unsigned(addr))) <= din
The second error is in the follow line qout <= RAMArray(addr). Here you should also use both the type conversion to unsigned as well as the type conversion function to_integer. The location parameter would be of the integer type. Example:
qout <= RAMArray(to_integer(unsigned(addr)))
Try to fix your code with my suggestions and I think it will work.

Why couldn't I convert this integer into a logic_vector?

I have been trying to convert this Signal of type integer into an std_logic vector and assign the converted value into another signal that has the same width as a VHDL integer
signal temp : std_LOGIC_VECTOR(31 downto 0) := (others => '0');
signal FrameCumulative : integer :=0;
temp <= to_stdlogicvector(to_unsigned(FrameCumulative));
However I get this error:
Error (10346): VHDL error at vga.vhd(107): formal port or parameter
"SIZE" must have actual or default value
I am using use IEEE.NUMERIC_STD.ALL; and use IEEE.STD_LOGIC_1164.ALL;
First I made the mistake of not checking the integer size within VHDL and tried to assign an integer into a 14-bit vector but after I gave it some thought I relised my mistake.
Now according to many on-line resources, what I am doing should work but my synthesiser complains about it.
If you do know the cause for this would you mind ellaborating on your answer rather than just posting the correct code, Thanks!
The function to_unsigned must be provided with a parameter specifying the width of the vector that you want it to produce. The function to_stdlogicvector is also not the correct thing to be using. Your line should look like this:
temp <= std_logic_vector(to_unsigned(FrameCumulative, temp'length));
The function to_unsigned is a conversion function, it must be provided with the target width. Here, as suggested by #BrianDrummond, the width is specified by taking the length attribute from the target vector itself (temp). The std_logic_vector is a type cast, where the unsigned value is simply interpreted directly as an std_logic_vector.

convert hex number to std_logic_vector

I have a question on converting a hex number into a std_logic_vector. I need the bit representation of the hex numbers because they are my data the simulated keyboard is sending to my board (later). At now i am in development phase:
Here is the code example that doesn't work within ISE:
Subtype ScanCode is std_logic_vector(39 downto 0);
variable binaryRep : ScanCode;
binaryRep := std_logic_vector(16#70F070#);
the conversion in the last line is where the problem appears the Compiler tells me Cannot convert type universal_integer to type std_logic_vector
I have also tried that code but got another error i don't understand
binayRep <= to_stdlogicvector(x"FC");
this was the error message i got:
Near to_stdlogicvector ; 2 visible identifiers match here
I also searched the web for other solutions but i couldn't solve the problem.
Has anyone an Idea how to fix the code ?
16#70F070# is a numerical literal and isn't appropriate directly, it needs a conversion routine. You don't have an appropriate conversion routine that matches the signature [integer return std_logic_vector].
This
binaryRep <= to_stdlogicvector(x"FC");
wouldn't work anyway because the equivalent bit string to x"FC" has a length of 8, while binaryRep has a length of 40 and you don't specify the length std_logic_vector to produce. (And x"FC" already get's converted to an equivalent bit map).
The only to_stdlogicvector function declarations I found are in package fixed_generic_pkg and aren't appropriate.
you could:
binaryRep <= x"00000000FC";
Which matches the bit string length.
Or by including package numeric_std in a use clause:
binaryRep <= std_logic_vector(to_unsigned(16#70F070#,binaryRep'length));
Which converts a natural (an integer subtype) to an unsigned which is then type converted to std_logic_vector with the length derived from binaryRep.
Or using Mentor's std_logic_arith package
binaryRep <= to_std_logicvector(16#70F070#,binaryRep'length);
Which takes an integer argument and a natural length and converts the result to a std_logic_vector.
Or using Synopsys's std_logic_arith package
binaryRep <= conv_std_logic_vector(16#70F070#,binaryRep'length);
Where both arguments are type integer.
(And there are a couple more ways, dependent on VHDL-2008 support).
According to:
https://www.altera.com/support/support-resources/design-examples/design-software/vhdl/v_hex.html
signal A : std_logic_vector(31 downto 0) := x"00000017";
Worked for me :)

Resources