I was wondering if integer overflow is defined in VHDL. I wasn’t able to find anything in the 2002 Specification.
As an example (Note, this might not compile, it’s just a generic example…):
entity foo is port (
clk : std_logic
);
end entity;
architecture rtl of foo is
signal x : integer range 0 to 2 := 0;
begin
process (clk)
begin
if rising_edge(clk) then
x <= x + 1;
end if;
end process;
end architecture;
It’s clear that x will go from 0 to 1, and then to 2. Is it defined what will happen on the next increment? Is that undefined behavior?
for a test bench for rtl of foo in ghdl:
I added a context clause to Bill’s foo entity and architecture:
Line 15 is the signal assignment to x:
This is a simulation error (occurs at runtime).
From IEEE 1076-1993:
7.2.4 Adding operators
This means the result of the "+" operator can be outside the subtype constraint of x. Note that a function declared to provide an overload for the "+" is not allowed to specify the result subtype. (The returned value may be an object declared with a subtype indication, which can define the value range or an array length).
and 12.6.2 Propagation of signal values
If the result of the addition doesn’t match the subtype constraint of the target x it will generate an error. That subtype constraint is provided by the object x declaration which provides a subtype indication for an integer (the range).
A run-time error causes the simulation to terminate for an LRM compliant implementation.
Without a standardized format for error reporting ghdl does not provide the current simulation time. That can be found be examining the produced waveform:
The waveform quite being updated after 20 ns. The next scheduled event:
would have been the rising edge of clk at 25 ns.
So this tells us how a constrained integer produces an overflow error.
What about an integer without a subtype constraint:
We define x as an unconstrained integer set it’s default value where we expect x to overflow.
Package standard explicity declares INTEGER "+":
The expected result is outside the range of INTEGER if as we see "+" has it’s ordinary mathematical meaning.
However, from the implementation dependent declaration in package standard:
and simulation:
We see the value of x wrap around.
The assignment of the "+" operator result violated no constraint:
3 Types:
In our second architecture and there is no constraint but there are no possible values outside the declared range for type INTEGER. The value instead rolls over.
The semantics for VHDL have been constructed to not require detection here and this matches mathematical operations on single dimensional arrays of elements representing binary bits (hardware).