Search code examples
vhdl

Type vs Subtype and down vs to for Integers in VHDL


What is the difference between type and subtype in VHDL and where should I use them ?

My understanding is that subtype is just narrowed down version of one of the primary types, such as integer: subtype small_integer is integer range -128 to 127; All the operations possible on primary type, are also possible on subtypes(of course, with certain limitations) . Also, it is better to use subtypes to prevent errors.

So what is the purpose of the type ?

What is the difference between donwto and to for the integers ? (To get the point across, here is an example)
subtype bit_index is integer range 31 downto 0;
subtype bit_index is integer range 0 to 31;

Thanks !


Solution

    • As you correctly say, a type is the base for subtypes; without type there is no subtype. However, subtypes are only safer in simulation; in real hardware, there are no boundary checks etc...

    • The standard libraries of VHDL defines a number of base types for you to build upon, like std_logic, std_ulogic, std_logic_vector (unconstrained, defined in package std_logic_1164) integer, character (defined in package standard), and so on. Your own definitions like std_logic_vector(7 downto 0) create a subtype indirectly (or directly if you define and name your subtypes explicitly)

    • When you are looking at your own enumerations, e.g., when describing the states of a state machine, you need a type:

      type tState is (IDLE, DO_SOMETHING, DONE);

    • About the downto and to for the integers: it is useless for the integer itself. However, integer, natural etc. can be array index types. In some situations with unconstrained arrays, e.g. like here constant c : std_logic_vector := "1000" the direction of the range of the index type is taken as direction of the literal. In this case, the index type of std_logic_vector is natural, which itself is defined as subtype natural is integer range 0 to integer'high;. Therefor constant c is defined as to and the literal is parsed accordingly ('1' is the LSB)