(1) To constraint sum() of a random unpacked array to 32-bit value, user has an option to use either type cast ( int’ ) or size cast ( 32’ ).
rand bit [30:0] a[2]; // Could be dynamic array / Queue
rand bit signed [30:0] b[2]; // Could be dynamic array / Queue
constraint a_sum { a.sum() with (int'(item)) == 32'h... ; } // Some 32-bit value
constraint b_sum { b.sum() with (32'(item)) == 32'h... ; } // Some 32-bit value
(Q1) Is there any scenario ( size could be greater than 2 ) where type cast would be preferred over size cast or vice-versa ? By preferred I mean to say that constraint is unsatisfiable using one cast and solvable using the other cast
(2) For b_sum the resultant sum in LHS would be 32-bit signed value whereas the RHS is unsigned value due to sized literal.
constraint b_sum { 32'(signed'(final_sum)) == 32'h... ; } // Some 32-bit RHS value
(Q2) Due to presence of unsigned value in RHS, can we say that the resultant constraint expression is unsigned ?
It matters whether you need to represent a number greater than 2,147,483,647. In most cases, it’s best to keep all values unsigned, so 32' () would be preferred over int' (). However, in most situations, it doesn’t matter because you’re dealing with smaller unsigned integers, and int' () seems to be more descriptive.
The problem with the example values you’ve provided is that there’s no distinction between treating a 31-bit number as signed or unsigned. When you extend it to 32 bits and add the two elements, the 32nd bit is carried over to the 33rd bit and truncated; it wouldn’t have mattered whether that bit was signed or zero-extended. When adding large numbers, you need to ensure that the sum is wide enough to accommodate the result.
The with clause solely determines the data type used in the sum() method. Then, the result is treated as unsigned because the right-hand side of the assignment is unsigned. However, since both sides are 32 bits, it doesn’t matter when comparing them with an equality operator.
If you’re adding elements to an M x N array, you can search for a formula that calculates the number of bits required to store the results without overflow.