SystemVerilog constraint examples
Use SystemVerilog inside, dist, implication, solve-before, soft and foreach constraints with practical examples and debugging guidance.
Basic range and set constraints
Use inside to express legal sets and ranges instead of long Boolean expressions.
class packet;
rand bit [7:0] length;
rand bit [1:0] kind;
constraint legal_c {
length inside {[1:64], 128};
kind inside {0, 1, 2};
}
endclass
Distribution and conditional relationships
dist changes probability; it does not merely list legal values. The := weight applies to each value in a range, while :/ divides a weight across the range.
constraint traffic_c {
kind dist {0 := 5, 1 := 3, 2 := 1};
(kind == 2) -> length inside {[32:64]};
}
Use soft for defaults that an inline constraint may override. Use solve a before b only to influence distribution when b depends on a; it does not create a procedural calculation order.
Array constraint
rand byte payload[];
constraint payload_c {
payload.size() inside {[1:16]};
foreach (payload[i]) payload[i] != 8'h00;
}
Constrain size before relying on elements. Functions called by constraints must be free of side effects and should depend only on their inputs.
Debugging failed randomization
Always check the return value:
if (!pkt.randomize() with { length < 8; })
$fatal(1, "packet constraints are inconsistent");
Reduce the problem by disabling constraint blocks selectively with constraint_mode(0), inspecting inline constraints and looking for contradictory ranges. Keep constraints small and named by intent so failures can be isolated.