学习目标:
SV绿皮书第六章:随机化
学习内容:
1.在类中使用随机化,rand/randc(周期性随机–所有可能值都赋过后才可以重复)关键词来表明它们的随机属性,修饰变量
随机属性需要配合类随机函数使用std::randomize()才能随机化变量
约束constraint也同随机变量一起在类中声明
2.声明随机变量的类
class Packet;
rand bit [31:0]src,dst,data[8]; //rand永远为1/20
randc bit [7:0]kind; //randc---1/20下一次为1/19
constraint c{src>10;
src<15;}
endclass
Packet p;
p=new(); //此时变量还是默认值0
assert(p.randomize()) else //assert断点,randomize返回一个0/1,代表随机化是否成功
$fatal(0,"Packet::randomize failed");
transmit(p);
end
随机化成功则全部变量被随机化,不存在只有一部分成功随机化的情况
3.关键词dist产生随机数值的权重分布,符号(:= 😕) :=表示每一个值是相同的,:/表示权重要平均分到值范围内的每一个值
权重不用百分比表示,权重和也不必是100
4.权重分布
rand int src,dst;
constraint c_dist{
src dist{0:=40,[1:3]:=60};
//src=0,weight=40/220
//src=1,weight=60/220
//src=2,weight=60/220
//src=3,weight=60/220
dst dist{0:/40,[1:3]:/60};
//src=0,weight=40/100
//src=1,weight=20/100
//src=2,weight=20/100
//src=3,weight=20/100
}
5.常见约束运算符inside,值的集合(默认取值概率相同),集合里面也可以使用变量
rand int c;
int lo,hi; //作为上下限的非随机变量
constraint c_range{
c inside {[lo:hi]};
}
使用 指 定 最 大 值 和 最 小 值 ( 数 组 也 用 到 指定最大值和最小值(数组也用到 指定最大值和最小值(数组也用到,[$]表示数组最后一个元素)
rand bit [6:0]b;
rand bit [5:0]e;
constraint c_range{
b inside {[$:4],[20:$]}; //0<=b<=4||20<=b<=127
e inside {[$:4],[20:$]};
}
6.k可以通过->或者if-else来让一个约束表达式在特定时刻有效
class BusOp;
....
constraint c_io{
(io_space_mode)->
addr[31]==1'b1;
}
7.约束块是并行的,是声明性代码
约束也是双向的,这表示它会同时计算所有的随机变量的约束。增加或删除任何一个变量的约束都会直接或间接影响所有相关的值的选取。
8.子类继承父类,新添加约束块不能违背父类约束块
可以使用内建constraint_mode()函数打开或者关闭约束
class Pcaket;
rand int length;
constraint c_short{length inside {[1:32]};}
constraint c_long{length inside {[1000:1023]};}
endclass
Packet p;
initial begin
p=new();
p.c.short.constraint_mode(0);
assert(p.randomize());
transmit(p);
p.constraint_mode(0);
p.c.short.constraint_mode(1);
assert(p.randomize());
transmit(p);
end
10.想要产生一个每个元素都唯一的随机数组,使用randc是不对的,每个元素只会独立地随机化
11.系统随机函数
$random()平均分布,返回32位有符号随机数
$urandom()平均分布,返回32位无符号随机数
$urandom_range()在指定范围内的平均分布
12.随机化个别变量
r.randomize(a); //只随机化a,a可以是指定的或者没有被指定的rand的变量
class Rising;
byte low;
rand byte med,hi;
constraint up
{low<med;med<hi;}
endclass
initial begin
Rising r;
r=new();
r.randomize(); //随机化hi,med,但不改变low
r.randomize(med); //只随机med,保存上面随机的值及low的值
r.randomize(low); //只随机low,同理保存上面随机的值
end
例子:r.randomize();-----low,med,high=0,1,5
r.randomize(med);----low,med,high=0,X(满足约束0-5),5
13.上例改为
class Rising;
byte low;
rand byte med,hi;
constraint up
{low<med;med<hi;}
endclass
initial begin
Rising r;
r=new();
r.randomize(low);
end
结果为:low=报错,med=0,hi=0
问题:
学习时间:
晚:20-22