I've recently been thinking about the use of variables in VHDL. As part of my musings, I've put together (and tested in ISIM, which won’t surprise those who know me) an example of using variables in a VHDL process. I start with two 8-bit bytes called "a" and "b" and two 4-bit nybbles (or nibbles if you prefer) called "c" and "d."
Depending on the value of two input flags ("f1" and "f2"), the outputs "c" and "d" are either the high or low nibbles of the results of the operations ("a"-"b") or ("b"-"a"). All of this is purely combinatorial logic -- there are no registers involved at all:
What is going on? How is this implemented? How can "diff" have two values in the same process?
In fact, this is pretty straightforward. The value originally assigned to "diff" becomes inaccessible to the bottom half of the process when it is assigned a value for the second time. This is recognized and implemented as if they are two distinct variables. A smart designer would most probably actually use two variables (or better yet, two processes), which will completely remove any chance of confusion.
Having said this, where things do start to get confusing is when a value's lifetime is not so clear cut. For example, what if the bottom half of the process did not always assign a value to "diff"?
As the logic between the two halves is no longer distinct, it rapidly becomes a mess that is much more tricky to understand -- especially when other signals may have already been assigned, in which case they will have a "next" value as well as a "current" value. This is not really a good thing at all and is best to be avoided in my book.
Another case to be avoided is when a variable is only assigned a value sometimes as illustrated below:
With the Xilinx ISE (integrated software environment), the code implements with just a warning about finding a latch on "diff$mux000." This surprised me; I assumed that it would just assign "U" or "0" to "diff" each time the process is triggered -- but it looks as though values stored in "diff" can and will be retained. It also looks as if I have some more VHDL textbook reading to do!
But what should come as no surprise to anybody is that these problems are not unique to VHDL -- similar problems occur all the time in the software world, with things like unassigned variables and coders using the same "i" variable to implement multiple loop counters. But coders develop tools and practices to avoid most of these errors.
So, are VHDL variables really so bad that they should never be used? Or is it just that they don't fit with the mindset of "assignments will be made when the process is finished" that is required for hardware design? They seem like a powerful feature to me!