During this week’s SystemVerilog training, a smart engineer, Sarvendranath created an interesting “derived” example from our regular lab code. After all an engineer is supposed to be “Pedantic” (See an interesting side post on this at: http://www.cvcblr.com/blog/?p=14).
The topic under discussion was arrays and out-of-bound accesses. This has been talked in detail at various websites for C++ etc. as in: http://w3.ualg.pt/~pjotr/Lectures/PI/WWW/t13.html
Consider the below code snippet:
The array has 3 unpacked dimensions with bounds at 2,3,4. The “in-bound access” shall be “0..1”, “0..2” and “0..3”. Now what happened during a lab trial was to use an incorrect for loop a shown above with the loop count running from “1..2”, “1..3”, and “1..4” –> The last index has been out-of-bound. Going by several implementation discussions, many tools will not flag this (unfortunately) as it needs to optimize for “performance” and these kind of checks are reserved for static/formal checking (if any available). Also it can be a real challenge for a static tool to verify this as the access is really RUN-time!
Some tools may provide a “debug” mode under which it runs in slow mode but provides warnings for such accesses. The IEEE 1800 LRM says:
7.4.6 Indexing and slicing of arrays
If an index expression is out of the address bounds or if any bit in the address is X or Z, then the index shall be invalid. The result of reading from an array with an invalid index shall return the default uninitialized value for the array element type. Writing to an array with an invalid index shall perform no operation. Implementations may issue a warning if an invalid index occurs for a read or write operation of an array.
But the end user is in trouble – many tools don’t do this for “dynamic access” such as in a for loop as above.
However – System Verilog does have a BETTER solution for users – the elegant foreach loop. You don’t hard-code the loop bounds, rather do it as shown below:
A sample run from Riviera-Pro (http://www.aldec.com/en/products/functional_verification/riviera-pro) is below:
So next time you access an array using a loop – remember to use your friend foreach and not old fashion for