有没有一种方法可以根据另一个变量的随机化结果来限制 class 中的随机变量?

Is there a means with which to constrain a random variable in a class based upon the result of the randomization of another var?

我需要随机化变量 rA 并将变量 rB 设置为 1'b1 if rA == 1'b1 或者 randomized if rA == 1' b0。这是我正在尝试的:

class randomizedVars;
    rand bit rA;
    rand bit rB;
    constraint cB {
        rB == 1'b1;
    }
    task changeConstraints();
        if (this.rA == 1'b1)
            begin
            this.cB.constraint_mode(1); // turn on the constraint for rB
            this.rA.rand_mode(0); // Disable rA from being randomized
            this.randomize(); // Rerandomize to force rB to meet its constraint ?
            this.rA.rand_mode(1); // Reenable rA to be randomized later
            this.cB.constraint_mode(0); // turn off the constraint for rB for later
            end
         else
            this.cB.constraint_mode(0);
    endtask
endclass

此方法似乎有效,但我主要只是想知道是否有“正确”的方法来执行此操作。我觉得好像这个方法是蛮力和困难的方法。更糟糕的是,我需要在每次随机化后调用任务,这让我觉得好像有一种方法我没有看到。

明确一点,我的预期结果是当 rA 被随机化并等于 1 时,rB 将被强制为 1。如果 rA 被随机化并等于0,那么 rB 也会被随机化。我的实际结果与此相符。只是想知道是否有一种方法可以做到这一点而不必在每次 .randomize() 方法调用后调用任务。

您可以通过使用不同的约束并删除任务来简化代码。

class randomizedVars;
    rand bit rA;
    rand bit rB;

    constraint cB {
        solve rA before rB;
        (rA == 1) -> (rB == 1);
    }
endclass

module tb;

randomizedVars c;

initial begin
    c = new();
    repeat (8) begin
        c.randomize();
        $display("a=%b b=%b", c.rA, c.rB);
    end    
end

endmodule

这是一个打印输出的例子:

a=0 b=0
a=0 b=1
a=1 b=1
a=1 b=1
a=0 b=0
a=1 b=1
a=0 b=0
a=0 b=1

如果rA被随机选为1,则rB会被强制为1;否则,rB 将是随机的。

你想要的是所谓的蕴含约束(IEEE 1800-2017 SystemVerilog LRM.

中的第18.5.6节

expression -> constraint_set

If也可以写成

if (expression) constraint_set

但第一个是首选,因为它是一个方程式,而不是程序代码。无论哪种情况,当 LHS 表达式为真时,必须满足 RHS 上的约束。

constraint cB {
     (rA == 1) -> (rB == 1);
}