Close

Multi-value logic

A project log for hdlpy

Hardware definition language in Python.

willemijn-coeneWillemijn Coene 03/24/2021 at 13:010 Comments

When modelling hardware you run into the subject of multi-value logic. Inevitably, because digital logic is more than just ones and zeroes: there's also high impedance signals and their interactions with other signals to model.

Thus I had to settle upon a multi-value logic system for hdlpy.

VHDL

I'm most familiar with VHDL and its 9-valued logic system from IEEE 1164:

UUninitialised
XStrong unknown
0Strong logical zero
1Strong logical one
ZHigh impedance
WWeak unknown
LWeak logical zero
HWeak logical one
-Don't care

The main advantage of VHDL's system being that it allows you to model wired logic by using weak signals (W, L and H). However, hdlpy is intended for FPGA's, which typically don't do any wired logic (even high impedance signals are rare, only appearing on external pins).

Verilog

Verilog sticks to the much simpler 4-value logic system as defined in IEEE 1364:

0Logical zero
1Logical one
ZHigh impedance
XUnknown

Though missing weak signals, it does include high impedance signals which may appear on external FPGA pins.

hdlpy

Thus for hdlpy I settled on the Verilog system of 4-valued logic (01Z and X).

Which then led to the challenge of deriving logical operations on these values. Of course, 0 and 1 are easy:

>>> from hdlpy import logic
>>> logic(1) & logic(0)
<logic.zero: '0'>
>>> logic(1) & logic(1)
<logic.one: '1'>
>>> logic(1) | logic(0)
<logic.one: '1'>

But what if one of the operands is Z or X?

I realised that a logical AND where one of the operands is 0 can only ever result in 0, irregardless of the second operand. The same goes for OR where one of the operands is 1:

>>> logic(0) & logic('Z')
<logic.zero: '0'>
>>> logic(1) & logic('X')
<logic.unknown: 'X'>
>>> logic(0) | logic('Z')
<logic.unknown: 'X'>
>>> logic(1) | logic('X')
<logic.one: '1'>

Indeed, VHDL and Verilog both define similar truth tables.

Use the source!

Source code for hdlpy, together with a test suite, is available on GitHub.

Discussions