In System Verilog, iterative constraints allow you to apply constraints across arrays or collections of variables using iteration constructs like foreach. Iterative constraints simplify the process of defining conditions for multiple elements in an array, ensuring that constraints are clean, concise, and scalable. System Verilog provides the foreach loop, which can be used inside the constraint block to iterate over elements of an array.
Key Features:
- Simplifies Constraints: Allows applying constraints to every element in an array without explicitly writing constraints for each index.
- Scalable: Works well for arrays of any size, including dynamic or associative arrays.
- Flexible: Supports relationships between array elements, such as unique values, ordering, or specific ranges.
Syntax:
constraint constraint_name {
foreach (array_name[i]) {
condition_on_array_element;
}
}
array_name refers to the array being constrained.i is the iterator that represents the index of the array element.The condition specifies the rule to apply to each array element.
Example 1: Constraining All Elements to a Range
Suppose we want all elements in an array to fall within a specific range.
class RangeConstraintExample;
rand int array[5]; // Array of size 5
// Constraint to ensure all elements are within a range
constraint array_range {
foreach (array[i]) {
array[i] inside {[10:50]}; // Each element is between 10 and 50
}
}
endclass
module tb;
initial begin
RangeConstraintExample ex = new();
// Randomize and display the array
if (ex.randomize()) begin
$display("Randomized Array: %p", ex.array);
end else begin
$error("Randomization failed!");
end
end
endmodule
Output:
Randomized Array: '{11, 14, 29, 27, 30}
Example 2: Increasing Order of Array Elements
We can enforce that the elements of an array are in strictly increasing order.
class IncreasingOrderExample;
rand int array[5]; // Array of size 5
// Constraint to ensure the array elements are in increasing order
constraint increasing_order {
foreach (array[i]) {
if (i > 0) {
array[i] > array[i-1]; // Current element is greater than the previous
}
}
}
// Range constraint for array elements
constraint array_range {
foreach (array[i]) {
array[i] inside {[1:50]};
}
}
endclass
module tb;
initial begin
IncreasingOrderExample ex = new();
// Randomize and display the array
if (ex.randomize()) begin
$display("Randomized Increasing Order Array: %p", ex.array);
end else begin
$error("Randomization failed!");
end
end
endmodule
Explanation:
foreachLoop: Iterates over all indices of the array.- Order Constraint: Ensures that each element (
array[i]) is greater than its preceding element (array[i-1]). - Range Constraint: Restricts the values of array elements to
[1:50]. - Output: The randomization generates an array in strictly increasing order.
Output:
Randomized Increasing Order Array: '{4, 19, 27, 28, 31}