MyHDL arithmetics, in particular addition/subtraction of intbv()
signals does not account for bit widths within a chain of additions/subtractions. Therefore it is possible to create scenarios where certain values that never occur in the MyHDL model (due to intbv() min max restrictions) are left unconvered (such as truncated results) in the resulting HDL.
The IRL kernel however does account for bit widths and is stricter with respect to truncation, plus it allows expressions that are not valid using MyHDL intbvs, as elaborated below. However, the bit width accounted for is always the hard amount of bits used for a binary value, not a logical limit as applied to an intbv().
From this release on, the arithmetic handling is entirely wire type specific, with exception of intbv
, whose behaviour is now fully emulated and evaluated for Verilog and VHDL targets.
import sys
sys.path.insert(0, "../..")
from myhdl import *
@block
def calc(a, b):
@always_comb
def worker():
b.next = a + a - 8
return instances()
a = Signal(intbv(min=0, max=9))
b = Signal(intbv(min=-8, max=9))
inst = calc(a, b)
inst.convert("VHDL")
<myhdl._block._Block at 0x7f76f09da400>
! grep -A 4 resize calc.vhd
b <= signed((resize(a, 5) + a) - 8); end architecture MyHDL;
Let's recapitulate a few intbv properties:
a = intbv(8)[4:]
assert int(a.signed()) == -8
a, bin(a), a.signed()
(intbv(8), '1000', intbv(-8))
We observe this being bit accurate: since the MSB is set, casting it to a Signed type will yield its negated value.
This case may appear constructed, but is an example of 'boundaries gone wrong' or 'testing with insufficient values'. Fortunately, we get a GHDL warning on the truncated vectors, but due to lack of static bit width accounting, it will be left unnoticed in the translation stage.
from myirl.test.common_test import run_ghdl
@block
def test_arith1():
c = Signal(intbv(15)[4:])
a = Signal(intbv(0, min=0, max=9))
b = Signal(intbv(min=-8, max=9))
@always_comb
def worker():
b.next = a + a + c + c - 36
@instance
def feed():
a.next = 7
c.next = 15
yield delay(1)
print(b)
assert b == 8
# These values will also yield the same result in the HDL transfer,
# however, MyHDL simulation will notice
a.next = 6
c.next = 0
yield delay(1)
print(b)
assert b == 8
return instances()
def run():
import os
pwd = os.getcwd()
inst = test_arith1()
# Simulation would detect the above overflow in this case:
try:
inst.run_sim(10)
except ValueError as e:
print("ERROR DETECTED", e)
inst = test_arith1()
inst.convert("VHDL")
run_ghdl([pwd + "/test_arith1.vhd", pwd + "/pck_myhdl_011.vhd"], inst, debug = True)
run()
08 ERROR DETECTED intbv value -24 < minimum -8 ==== COSIM stdout ==== ../../src/ieee2008/numeric_std-body.vhdl:3089:7:@0ms:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated ../../src/ieee2008/numeric_std-body.vhdl:3089:7:@0ms:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated 08 ../../src/ieee2008/numeric_std-body.vhdl:3089:7:@1ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated 08
! grep resize test_arith1.vhd
b <= signed((((resize(a, 5) + a) + c) + c) - 36);
Important to keep in mind: an addition or subtraction involving an intbv will no longer be an intbv:
t = a + a
type(t)
int
So this will not work:
try:
t = (a + 1).signed()
assert False # Never hit
except AttributeError as e:
print(e)
'int' object has no attribute 'signed'
In fact this is not a deficiency of the intbv concept, rather, this property elegantly offloads the boundary checks to the simulation. However, apart from non-supported constructs as the above, it does not support static checking or bit accounting for pipelines from the HLS library.
The IRL kernel does not implicitely truncate, unless the bit size of the result is one more than the signal it is assigned to. In this case, a warning is emitted. If the bit size is larger, a size mismatch error will be thrown.
When the result is signed, the arguments however are unsigned, the IRL requires a more explicit specification which part is to be assumed 'signed', otherwise, an exception is thrown:
from myirl.emulation.myhdl import *
from myirl.kernel.components import DesignModule, DummyVHDLModule
a = Signal(intbv()[4:])
sa = Signal(intbv(0, min=-16, max=17))
ctx = DummyVHDLModule()
op = sa.set(a)
try:
op.emit(ctx)
assert False # Should never get here
except TypeError as e:
print("EXPECTED ERROR", e)
EXPECTED ERROR <s_4248> <= <s_c209> (<class 'myirl.emulation.signals.Signal'>): requires explicit casting
Since it is size-sensitive, a .signed()
cast will result in a negative number if the MSB of the signal wire is set. This may result in a number of pitfalls, see MODE
s below. One of them produces the wrong result. What we're trying to achieve, is the bit-correct operation for
result = a + a - 8
where result
is obviously signed and a
is unsigned. Some of the following logic constructs are incorrect. Which MODE
s would that be?
@block
def calc(a : Signal, b : Signal.Output, MODE = 0):
if MODE == 0:
@always_comb
def worker():
b.next = a.signed() + a - 8
elif MODE == 1:
@always_comb
def worker():
b.next = a + (a - 8).signed()
elif MODE == 2:
a1 = a.resize(a.size() + 1)
@always_comb
def worker():
b.next = a1.signed() + a1.signed() - 8
elif MODE == 3:
@always_comb
def worker():
b.next = (a + a - 8).signed()
return instances()
def test():
a = Signal(intbv(min=0, max=9))
b = Signal(intbv(min=-2*8, max=2*8+1))
print("Size a =", len(a), "Signed:", a.is_signed(), ", Size b =", len(b), "Signed:", b.is_signed())
for mode in [0, 1, 2, 3]:
inst = calc(a, b, MODE = mode)
f = inst.elab(targets.VHDL)
test()
Size a = 4 Signed: False , Size b = 6 Signed: True FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Writing 'calc' to file /tmp/myirl_calc_26va9u14/calc.vhdl FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Module calc: Existing instance calc, rename to calc_1 Writing 'calc_1' to file /tmp/myirl_calc_fdzupedw/calc_1.vhdl FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Module calc: Existing instance calc, rename to calc_2 Writing 'calc_2' to file /tmp/myirl_calc_liaqq6oa/calc_2.vhdl Warning: Implicit truncation of SUB(ADD(SGN(R(a, 5)), SGN(R(a, 5))), C:8) result FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Module calc: Existing instance calc, rename to calc_3 Writing 'calc_3' to file /tmp/myirl_calc_xdm6s915/calc_3.vhdl
To verify our assumption on incorrect implementations, we run the simulation for all four modes:
ctx = DesignModule("test_addsub", debug = True)
@block
def testbench_sum(mode):
a = Signal(intbv(min=0, max=9))
b = Signal(intbv(min=-2*8, max=2*8+1))
uut = calc(a, b, mode)
@instance
def stim():
for it in [ (8, 8), (0, -8), (12, 16)]:
a.next = it[0]
yield delay(1)
print(b)
assert b == it[1]
yield delay(10)
return instances()
from myirl.test import ghdl
def test_tb(mode):
tb = testbench_sum(mode)
f = tb.elab(targets.VHDL, elab_all = True)
run_ghdl(f, tb, debug = True)
return f
for mode in range(4):
ctx.log("=========== TESTING MODE %d ===========" % mode, annotation = 'info')
try:
f = test_tb(mode)
ctx.log("TEST PASS")
except (ghdl.RuntimeError, ghdl.AnalysisError):
ctx.log("TEST FAIL", annotation = 'warn')
=========== TESTING MODE 0 =========== FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Module testbench_sum: Existing instance calc, rename to calc_4 Writing 'calc_4' to file /tmp/myirl_testbench_sum_4yrpavvg/calc_4.vhdl Writing 'testbench_sum' to file /tmp/myirl_testbench_sum_4yrpavvg/testbench_sum.vhdl Creating library file /tmp/myirl_module_defs_od5ue5im/module_defs.vhdl ==== COSIM stdout ==== 0x38 /tmp/myirl_testbench_sum_4yrpavvg/testbench_sum.vhdl:40:13:@1ns:(assertion failure): Failed in /tmp/ipykernel_30244/2637647312.py:testbench_sum():15 /tmp/testbench_sum:error: assertion failed in process .testbench_sum(myhdl_emulation).stim /tmp/testbench_sum:error: simulation failed TEST FAIL =========== TESTING MODE 1 =========== FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Module testbench_sum: Existing instance testbench_sum, rename to testbench_sum_1 Module testbench_sum: Existing instance calc, rename to calc_5 Writing 'calc_5' to file /tmp/myirl_testbench_sum_iuggo8h5/calc_5.vhdl Writing 'testbench_sum_1' to file /tmp/myirl_testbench_sum_iuggo8h5/testbench_sum_1.vhdl Creating library file /tmp/myirl_module_defs_ei7v_023/module_defs.vhdl ==== COSIM stdout ==== 0x08 0x38 0x10 TEST PASS =========== TESTING MODE 2 =========== FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Module testbench_sum: Existing instance testbench_sum, rename to testbench_sum_2 Module testbench_sum: Existing instance calc, rename to calc_6 Writing 'calc_6' to file /tmp/myirl_testbench_sum_owf120zw/calc_6.vhdl Warning: Implicit truncation of SUB(ADD(SGN(R(a, 5)), SGN(R(a, 5))), C:8) result Writing 'testbench_sum_2' to file /tmp/myirl_testbench_sum_owf120zw/testbench_sum_2.vhdl Creating library file /tmp/myirl_module_defs_ojt0t8lw/module_defs.vhdl ==== COSIM stdout ==== 0x08 0x38 0x10 TEST PASS =========== TESTING MODE 3 =========== FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Module testbench_sum: Existing instance testbench_sum, rename to testbench_sum_3 Module testbench_sum: Existing instance calc, rename to calc_7 Writing 'calc_7' to file /tmp/myirl_testbench_sum_dhue4l3o/calc_7.vhdl Writing 'testbench_sum_3' to file /tmp/myirl_testbench_sum_dhue4l3o/testbench_sum_3.vhdl Creating library file /tmp/myirl_module_defs_bsjbmpwu/module_defs.vhdl ==== COSIM stdout ==== 0x08 0x38 0x10 TEST PASS
The above calculation a + a - 8
presents a few more cases specific to intbv().
We define again a
, because we include '8', we need four bits. This would allow representing 15, in synthesized or simulated hardware. Because we restricted a
to maximum 8, we can, however, impose some boundaries on the result.
a = Signal(intbv(min=0, max=9), name = 'a')
b = Signal(intbv(0, min = -8, max = 9), name = 'b')
op0 = (a + a - 8).signed()
op1 = a + (a - 8).signed()
Verify size of a:
a.size()
4
By default, the operation sizes match the 'hard' bit properties and don't respect the intbv() restrictions:
op0.size(), op1.size(), len(intbv(0, min=-8, max=22))
(6, 6, 6)
However, for a maximum result of 8
, five bits would suffice:
assert len(intbv(0, min=-8, max=8+1)) == 5
We note: the IRL kernel does not account for the effectively needed bits. It will however truncate with a warning, in the special case of an assignment where the source is an explicit addition.
If it's not, an exception will throw. See below:
d = DummyVHDLModule()
gens = [
b.set(op0), b.set(op1)
]
for g in gens:
print("*** EMIT ", g)
try:
g.emit(d)
except base.SizeMismatch as e:
print("Failed", e)
*** EMIT b <= SGN(SUB(ADD(a, a), C:8))
Failed Expression SGN(SUB(ADD(a, a), C:8))/<class 'myirl.kernel.sig.Signed'> exceeds bit size of signal (6 > 5)
*** EMIT b <= ADD(a, SGN(SUB(a, C:8)))
Warning: Implicit truncation of ADD(a, SGN(SUB(a, C:8))) result
b <= signed(resize((signed(resize(a, 6)) + signed((resize(a, 5) - "01000"))), 5));
Negation of a value will increment the number of bits by one. This obviously turns an unsigned signal into signed, and applies to the special case where a signed signal wire contains the most negative possible value.
sa.is_signed(), a.is_signed()
(True, False)
sb = -sa
b = - a
sa.size(), sb.size(), a.size(), b.size()
(6, 7, 4, 5)
Unlike the above intbv behaviour, a shift operation on an intbv returns again an intbv, however it is unlimited:
from myhdl import *
vec = intbv
a = Signal(vec(0xdeadbeef)[32:])
c = Signal(vec(1)[32:])
b = Signal(intbv(0x80000000)[32:]).signed()
u = b >> 7
y = a >> 16
z = c << 18
[ hex(x) for x in [u, y, z] ]
['-0x1000000', '0xdead', '0x40000']
a = vec(0x8000)[16:].signed()
z = a >> 5
# assert len(z) == 11
hex(y), len(y), hex(z), len(z)
('0xdead', 0, '-0x400', 0)
@block
def tb():
q = Signal(modbv()[16:])
a = Signal(intbv(0xbeef)[12:])
@instance
def stim():
yield delay(5)
q.next = a << 4
yield delay(16)
print(q)
assert q == 0xeef0
return instances()
# print(tb.unparse())
uut = tb()
uut.convert('VHDL')
/home/testing/.local/lib/python3.9/site-packages/myhdl/conversion/_toVHDL.py:500: ToVHDLWarning: Signal is not driven: a warnings.warn("%s: %s" % (_error.UndrivenSignal, s._name),
<myhdl._block._Block at 0x7f76f0178430>
When assigning to a signal, the built-in intbv
limit check will kick in and handle overflows.
However, this can lead to errors in the conversion.
# !cat tb.vhd -n
Due to discrepancies with the myIRL kernel, it was decided to not support shift operations with the base Signal class for the time being. STILL UNCLEAR HOW TO HANDLE THIS
Therefore, bit shifting is currently covered using various options:
A basic example on how to inline barrel shifters is listed in operations.ipynb, using a Mix-in class for extended signal types.
For static shift operations, the MyHDL emulation currently uses the SSignal
class from the shift
library. Currently this is regarded unstable.
See also IRL internals on arithmetic behaviour with signed values: Signed/Unsigned Arithmetic.
The myHDL emulation default behaviour was changed such that dynamic shifts track the maximum size results. Hence it is necessary to explicitely truncate (i.e. slice) the result of a left shift expression as below, in order to avoid a SizeMismatch exception:
from myirl.emulation.myhdl import *
@block
def unit_shift(clk : ClkSignal, a : Signal, sh : Signal, q : Signal.Output,
SHIFT_RIGHT = False):
@always(clk.posedge)
def worker():
if SHIFT_RIGHT:
q.next = a >> sh
else:
q.next = (a << sh)[len(q):]
return instances()
a, q = [ Signal(intbv()[32:]) for _ in range(2) ]
sh = Signal(intbv()[5:])
clk = ClkSignal()
uut = unit_shift(clk, a, sh, q)
vhdl = uut.elab(targets.VHDL)
verilog = uut.elab(targets.Verilog)
FALLBACK: UNHANDLED ROOT CLASS <class 'ipykernel.zmqshell.ZMQInteractiveShell'>, create new context Using default for SHIFT_RIGHT: False SHIFT_RIGHT: use default False Writing 'unit_shift' to file /tmp/myirl_unit_shift_yjk29gl_/unit_shift.vhdl Writing 'unit_shift' to file /tmp/myirl_unit_shift_yjk29gl_/unit_shift.v
!cat {vhdl[0]}
-- File generated from source: -- /tmp/ipykernel_30244/554209513.py -- (c) 2016-2022 section5.ch -- Modifications may be lost, edit the source file instead. library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; library work; use work.txt_util.all; use work.myirl_conversion.all; entity unit_shift is port ( clk : in std_ulogic; a : in unsigned(31 downto 0); sh : in unsigned(4 downto 0); q : out unsigned(31 downto 0) ); end entity unit_shift; architecture myhdl_emulation of unit_shift is -- Local type declarations -- Signal declarations begin worker: process(clk) begin if rising_edge(clk) then if FALSE then q <= resize(shift_right(resize(a, 32), to_integer(sh)), 32); else q <= shift_left(resize(a, 64), to_integer(sh))(32-1 downto 0); end if; end if; end process; end architecture myhdl_emulation;
!cat {verilog[0]}
// File generated from source: // /tmp/ipykernel_30244/554209513.py // (c) 2016-2022 section5.ch // Modifications may be lost, edit the source file instead. `timescale 1 ns / 1 ps `include "aux.v" // Architecture myhdl_emulation module unit_shift ( input wire clk, input wire [31:0] a, input wire [4:0] sh, output reg [31:0] q ); // Local type declarations // Signal declarations always @ (posedge clk ) begin : WORKER if (1'b0) begin q <= (a >> sh) /* implicit/casted */ /* resize 0 -> 32 */ ; end else begin q <= (((a << sh)) & 32'hffffffff); end end endmodule // unit_shift
See also arithmetic tests (myirl/test/test_arith.py) for reference.
FIXME Drop flexbv fork examples