SystemVerilog 随机化与约束:从 rand 到协议约束

约束随机验证的价值在于:用少量规则描述“什么是合法激励”,让求解器生成大量测试向量。手写定向用例只能覆盖工程师想到的场景,约束随机还能撞出没想到的组合。

但约束随机也有自己的坑:randomize() 静默返回 0、约束互相冲突、randc 被当成计数器、soft 被当成硬约束。这些问题大多不是语法不会写,而是没有理解求解器的工作方式。

本文先讲随机化模型和约束语法,再讲数组、回调和 randcase,最后用 AXI 与内存分区两个例子把约束落到协议上。

1. 语法与用法

1.1 工作模型

一个类里,只有声明为 rand 或 randc 的成员参与随机化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class packet;
rand bit [31:0] addr;
rand bit [7:0] len;
rand bit [7:0] payload[];

constraint c_len { len inside {[1:64]}; }
constraint c_payload { payload.size() == len; }
endclass

packet p = new();

initial begin
if (!p.randomize())
$fatal(1, "randomize failed");
end

randomize() 做三件事:

  1. 收集当前对象所有启用的约束。
  2. 为所有 rand / randc 变量求一组满足约束的值。
  3. 成功返回 1,失败返回 0。

失败不会抛异常,也不会自动打印原因。每次调用都应该检查返回值,至少在回归环境中要检查。

内联约束在本次调用上追加,不影响类内定义:

1
2
if (!p.randomize() with { addr == 32'h1000; })
$error("inline constraint conflict");

内联约束只能追加,不能删除类内约束。类内约束与内联约束冲突时,randomize() 返回 0。

1.2 种子与复现

对象可以单独设种子:

1
2
p.srandom(32'h1234_5678);
if (!p.randomize()) ...

也可以给全局随机数发生器设种子:

1
2
$urandom(32'h1234_5678);
int x = $urandom_range(0, 15);

回归脚本应记录每个用例的种子。复现时用同一个种子、同一个约束集合、同一个仿真器版本,才能得到相同结果。

作用域里的普通变量可以用 std::randomize() 随机化:

1
2
3
4
int a, b;

if (!std::randomize(a, b) with { a < b; a inside {[0:15]}; })
$error("scope randomize failed");

它适合小段临时激励,不适合替代事务类上的约束模型。

1.3 rand、randc 与 rand_mode

rand 每次独立取值,可能连续取到相同值;randc 在满足约束的取值集合内循环,一轮取完之前不重复。

1
2
3
4
class t;
rand bit [1:0] a; // 可能 1, 1, 3, 0, ...
randc bit [1:0] b; // 0, 2, 1, 3 轮完才重复
endclass

randc 不是计数器,它只保证“不重复”,不保证递增。位宽很大时,randc 需要记录已经用过的值,开销会明显上升。

关闭某个变量的随机化:

1
2
3
p.addr.rand_mode(0);   // addr 保持当前值
p.randomize();
p.addr.rand_mode(1); // 恢复

非 rand 成员在 randomize() 中保持原值,但约束可以读取它:

1
2
3
4
5
class t;
bit [31:0] base = 32'h1000; // 不参与随机
rand bit [31:0] offset;
constraint c { offset < base; }
endclass

base 变了,offset 的取值范围也会跟着变。

1.4 约束块与开关

一个类里的多个约束块同时生效,关系是逻辑与,书写顺序不影响求解结果:

1
2
3
4
5
6
7
class txn;
rand bit [7:0] addr;
rand bit [7:0] len;

constraint c_addr { addr inside {[0:127]}; }
constraint c_len { len inside {[1:8]}; }
endclass

constraint_mode 关闭单个实例上的某条约束:

1
2
3
4
5
txn t = new();

t.c_len.constraint_mode(0); // 只关闭这个实例的 c_len
if (!t.randomize()) ...
t.c_len.constraint_mode(1); // 恢复

派生类可以定义同名约束,覆盖父类版本:

1
2
3
class ext_txn extends txn;
constraint c_len { len inside {[1:4]}; }
endclass

覆盖后只保留派生类版本。需要保留父类规则时,换一个约束名,或在派生约束里写出更完整的条件。

static constraint 的逻辑与普通约束相同,区别只在 constraint_mode() 的作用范围:静态约束的开关状态由整个类共享。

1
2
3
4
5
6
class txn;
rand bit [7:0] len;
static constraint c_len { len inside {[1:8]}; }
endclass

txn::c_len.constraint_mode(0); // 对所有实例关闭

约束实现也可以放在类外:

1
2
3
4
5
6
class txn;
rand bit [7:0] addr;
extern constraint c_addr;
endclass

constraint txn::c_addr { addr inside {[0:127]}; }

1.5 约束表达式

inside 是硬约束,值必须落在集合内:

1
2
3
4
5
6
7
constraint c_addr {
addr inside {[32'h0000:32'h00FF], 32'h200, 32'h400};
}

constraint c_excl {
!(addr inside {[32'h100:32'h1FF]});
}

dist 控制分布倾向:

1
2
3
4
5
6
7
constraint c_kind {
kind dist {READ := 8, WRITE := 2};
}

constraint c_len_dist {
len dist {[1:4] :/ 80, [5:8] :/ 20};
}
运算符 含义
:= 给列表中每个值相同的权重
:/ 把权重平均分给区间内的每个值

dist 不保证精确比例,权重是相对值,总和不必是 100。

蕴含与 if-else:

1
2
3
4
5
6
7
8
constraint c_fast {
(mode == FAST) -> (len <= 4);
}

constraint c_mode {
if (mode == FAST) len <= 4;
else len >= 8;
}

-> 是单向条件:前件为假时,后件不受任何约束。if-else 会约束两个分支。

soft 是“尽量满足”,与硬约束冲突时被丢弃:

1
2
3
4
constraint c_default {
soft len == 4;
len inside {[1:8]};
}
1
p.randomize() with { len == 8; };   // soft len == 4 被丢弃

solve...before 只影响求解顺序,不改变解空间:

1
2
3
4
5
constraint c_order {
solve mode before len;
(mode == FAST) -> (len <= 4);
(mode == SLOW) -> (len >= 8);
}
写法 含义 前件为假时
A -> B 若 A 则 B B 不受约束
if (A) B; else C; 二选一 C 必须成立
soft A 尽量满足 A 可被硬约束覆盖
solve a before b 先算 a 只影响顺序

1.6 数组与动态尺寸随机化

数组随机化通常分三层:尺寸、元素、元素之间的关系。

固定数组各元素独立取值:

1
2
3
class pkt;
rand bit [7:0] data[4];
endclass

动态数组和队列的长度也可以随机,先约束 size():

1
2
3
4
5
6
7
8
9
class frame;
rand bit [7:0] payload[];
rand int unsigned len;

constraint c_size {
len inside {[1:64]};
payload.size() == len;
}
endclass

foreach 写元素之间的关系:

1
2
3
4
5
6
7
8
class ramp;
rand bit [7:0] data[8];

constraint c_inc {
foreach (data[i])
if (i > 0) data[i] > data[i-1];
}
endclass

二维数组同样可以逐元素约束:

1
2
3
4
5
6
rand bit [7:0] grid[4][4];

constraint c_grid {
foreach (grid[i,j])
grid[i][j] == i * 4 + j;
}

注意边界索引:i == 0 时访问 data[i-1] 会越界,必须用 if 保护。

unique 让元素互不相同:

1
2
3
4
class id_pool;
rand bit [7:0] id[8];
constraint c_uniq { unique {id}; }
endclass

等价的显式写法:

1
2
3
4
5
constraint c_uniq {
foreach (id[i])
foreach (id[j])
if (i != j) id[i] != id[j];
}

唯一性是全局约束,元素越多求解越慢。元素个数接近取值范围上限时,可能直接无解。

1.7 随机化回调

pre_randomize() 在求解前执行,post_randomize() 在成功赋值后执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class txn;
rand bit [31:0] addr;
bit fast_mode;

constraint c_align { addr % 4 == 0; }

function void pre_randomize();
c_align.constraint_mode(fast_mode ? 0 : 1);
endfunction

function void post_randomize();
if (addr % 4 != 0)
`uvm_error("ALIGN", "addr not aligned")
endfunction
endclass
  • pre_randomize:根据模式打开/关闭约束,准备随机化所需的状态。
  • post_randomize:计算结果字段、做合法性检查、记录统计。

randomize() 失败时 post_randomize() 不执行;在 post_randomize() 里修改随机字段不会重新求解,可能破坏约束。回调里不要做重计算或阻塞等待。

1.8 randcase

randcase 按权重选择一个分支执行:

1
2
3
4
5
randcase
8: drive_normal();
2: drive_error();
1: drive_boundary();
endcase

权重是相对比例,总权重不必为 100。所有分支权重都为 0 时行为没有意义。

语句 选择依据
case 表达式的值
randcase 权重随机
if-else 条件真假

randcase 是过程语句,只能出现在 initial、always、task、function 中,不可综合。

2. 示例

2.1 AXI 风格事务

把协议条款逐条翻译成约束:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class axi_txn;
rand bit [31:0] addr;
rand bit [7:0] len; // AxLEN,实际拍数 = len + 1
rand bit [2:0] size; // 每拍字节数 = 1 << size
rand bit [1:0] burst; // 0 FIXED, 1 INCR, 2 WRAP

constraint c_burst { burst inside {0, 1, 2}; }
constraint c_len { len inside {[0:15]}; }
constraint c_size { size inside {[0:3]}; }
constraint c_align { addr % (1 << size) == 0; }

// 一次突发不能跨 4 KB 边界
constraint c_4k {
(addr[11:0] + (len + 1) * (1 << size)) <= 4096;
}

// WRAP 的拍数只能是 2、4、8、16
constraint c_wrap_len {
(burst == 2) -> ((len + 1) inside {2, 4, 8, 16});
}

// WRAP 的起始地址按整个传输大小对齐
constraint c_wrap_align {
(burst == 2) -> (addr % ((len + 1) * (1 << size)) == 0);
}
endclass
约束 协议含义
c_burst 只允许 FIXED / INCR / WRAP
c_len AxLEN 范围 0–15,对应 1–16 拍
c_size 每拍 1、2、4、8 字节
c_align 地址按传输宽度对齐
c_4k 突发不跨 4 KB 边界
c_wrap_len WRAP 拍数只能为 2/4/8/16
c_wrap_align WRAP 起始地址按总传输大小对齐

这些约束是“协议合法”的子集,不是全部。写完后先跑一次 randomize() 确认可满足,再逐步加入更细的规则。

2.2 内存分区

把地址空间切成若干区域,用 dist 控制访问频率,用蕴含把区域与地址绑定:

1
2
3
4
5
6
7
8
9
10
11
class mem_txn;
rand bit [31:0] addr;
rand bit [1:0] region;

constraint c_region {
region dist {0 := 5, 1 := 3, 2 := 2};
(region == 0) -> (addr inside {[32'h0000:32'h0FFF]});
(region == 1) -> (addr inside {[32'h1000:32'h1FFF]});
(region == 2) -> (addr inside {[32'h2000:32'h2FFF]});
}
endclass

dist 已经把 region 限制在 0、1、2,因此不需要额外排除 3。

2.3 错误注入

合法约束写好后,错误注入只需要临时关掉一条规则:

1
2
3
4
5
mem_txn m = new();

m.c_region.constraint_mode(0);
if (!m.randomize() with { addr == 32'hFFFF_FFFF; })
$error("injection failed");

或者用 rand_mode 固定其他字段,只让目标字段随机。

2.4 混合激励

1
2
3
4
5
6
7
task automatic run_mixed();
randcase
8: drive_normal();
2: drive_error();
1: drive_boundary();
endcase
endtask

正常、错误、边界按比例混合,比写三条独立的定向用例更容易覆盖组合。

3. 异常情况

3.1 不检查 randomize() 返回值

1
2
p.randomize();
use(p.addr); // 约束冲突时用的是旧值

约束冲突时静默失败,后续用的是上一次的值。每次调用都要检查,失败时打印约束和字段。

3.2 把 randc 当计数器

1
randc bit [1:0] b;   // 期望 0,1,2,3 递增

randc 只保证不重复,不保证递增。需要递增用 rand 加约束或显式计数器。

3.3 认为 -> 等于 if-else

1
2
constraint c { (mode == FAST) -> (len <= 4); }
// mode != FAST 时 len 完全不受约束

蕴含在前件为假时完全不约束后件。需要“否则必须如何”时用 if-else。

3.4 把 soft 当硬约束

1
2
3
4
5
constraint c {
soft len == 4;
len inside {[1:8]};
}
p.randomize() with { len == 8; }; // soft 被丢弃

冲突时 soft 会被丢弃。正确性不能只靠 soft。

3.5 以为 with 能删除类内约束

1
p.randomize() with { !(addr inside {[0:127]}); };   // 与 c_addr 冲突

with 只能追加,冲突仍然返回 0。要放宽类内约束,先 constraint_mode(0)。

3.6 约束数组时忘记 size()

1
2
3
4
class frame;
rand bit [7:0] payload[];
constraint c_elem { foreach (payload[i]) payload[i] < 128; }
endclass

动态数组长度没有约束时,元素约束可能无意义或让求解器先随意定长度。先约束 payload.size()。

3.7 对大数组使用 unique

1
2
rand bit [7:0] data[256];
constraint c { unique {data}; }

256 个 8 位值互不相同已经接近无解,求解代价极高。缩小数组或扩大元素位宽。

3.8 在 post_randomize() 中改随机值

1
2
3
function void post_randomize();
addr = 32'h1000; // 不会重新求解
endfunction

修改后可能破坏其他约束,且不会重新求解。需要参与求解的字段放到约束里。

3.9 回归不记录种子

失败用例没有种子,无法复现。回归脚本要把种子写进日志,并保证同种子、同约束、同版本可复现。

3.10 约束过紧

1
2
3
4
constraint c {
addr inside {[0:15]};
addr inside {[16:31]}; // 无解
}

看起来“更安全”,实际让求解器无解或只生成极少数组合。写完约束先跑一次 randomize() 确认可满足。

3.11 randomize() 失败的排查顺序

  1. 确认对象已经 new()。
  2. 确认目标变量声明为 rand。
  3. 逐条关闭约束,定位冲突来源。
  4. 检查数组 size() 与元素约束是否矛盾。
  5. 检查 unique 的元素个数是否超过取值范围。
  6. 检查枚举、位宽是否放得下目标值。
  7. 检查 solve before 是否形成循环依赖。
1
2
3
4
if (!p.randomize()) begin
`uvm_error("RND", "randomize failed")
p.print(); // 打印当前约束和字段,便于定位
end

3.12 性能问题

  • 用 solve before 把选择变量放在前面,减少分支。
  • 用 dist 表达分布,不要用大量重叠的 inside 区间。
  • 大数组避免全量 unique 和复杂 foreach 关系。
  • 尽量让约束是局部的,少写跨对象的长依赖链。

4. 小结

约束随机可以按四层理解:

  1. 声明:rand / randc 决定哪些字段参与随机。
  2. 规则:constraint 用 inside、dist、蕴含、foreach、unique 描述合法空间。
  3. 控制:randomize() with、constraint_mode、rand_mode、soft、solve before 调整单次行为和求解效率。
  4. 复现:检查返回值、记录种子、分析失败原因。

协议约束不是把 spec 抄一遍,而是把“必须成立”的条款转成硬约束,把“偏好”转成 soft 或 dist,再用覆盖率验证这些规则是否真的被走到。