SystemVerilog OOP Mastery · All levels
Randomization with Constraints: Code Examples
Code Examples for Randomization with Constraints.
Code examples
rand and randc with class constraints
systemverilog
class req;
rand bit [3:0] burst_len;
randc bit [1:0] qos;
rand bit write;
constraint legal_c {
burst_len inside {[1:12]};
write -> burst_len <= 8;
}
endclass
req r = new;
repeat (5) begin
if (!r.randomize()) $fatal(1, "randomize failed");
endrand solves each call from legal space; randc rotates qos values before reuse, improving short-run coverage of that field.
Inline randomize() with for scenario-specific control
systemverilog
req r = new;
if (!r.randomize() with {
write == 0;
burst_len inside {[4:10]};
}) begin
$error("Scenario randomization failed");
endInline constraints apply only to that randomize call. This is ideal for one test scenario without changing shared class constraints.
Example of over-constraint causing failure
systemverilog
class pair_gen;
rand bit [3:0] a;
rand bit [3:0] b;
constraint range_c { a inside {[0:7]}; b inside {[0:7]}; }
constraint sum_c { a + b == 20; }
endclass
pair_gen p = new;
if (!p.randomize()) begin
// No solution: max a+b is 14 in current ranges
endThis fails deterministically because constraints are mathematically incompatible. Solver failure here is expected and diagnostic.