SystemVerilog randomization:约束随机验证入门

约束随机是 SystemVerilog 验证的核心能力:用少量约束描述合法激励空间,由求解器自动生成大量测试向量。它比手写定向激励更能发现边界与组合缺陷。

1. rand 与 randomize

1
2
3
4
5
6
7
8
9
10
11
class packet;
rand bit [31:0] addr;
rand bit [31:0] data;
rand bit [3:0] len;
endclass

packet p = new();
initial begin
if (!p.randomize())
`uvm_error("RND", "randomize failed")
end

只有声明为 rand 的成员参与随机化;randc 表示无重复随机。

2. 约束驱动

1
constraint c_len { len inside {[1:8]}; }

约束在 randomize 时与求解器一起生效,保证生成值合法。

3. 种子控制

1
p.randomize() with { addr == 32'h100; };

with 内联约束只影响本次调用。固定种子可复现失败:

1
2
srandom(12345);
p.randomize();

4. 常见误区

  1. 忘记检查 randomize 返回值:约束冲突时静默失败。
  2. 在 non-rand 变量上期望随机:不会生效。
  3. 依赖未固定种子的回归:失败不可复现。

小结

随机化的三件套是 rand 声明、约束、randomize 调用。先保证约束可满足,再扩大激励空间。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog Randomization 章节(https://chipverify.com/systemverilog/systemverilog-randomization)。本文为原创中文讲解。