Home > Mobile >  Is there a means with which to constrain a random variable in a class based upon the result of the r
Is there a means with which to constrain a random variable in a class based upon the result of the r

Time:10-30

I need to randomize variable A and set variable B to 1'b1 if A == 1'b1 or randomized if A == 1'b0. Here is what I am trying:

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

This method seems to be working, but I'm mostly just wondering if there is a "correct" way of doing this. I feel as if this method is the Brute-Force-And-Difficulty method. Worse yet, I need to call the task after every randomization, which makes me feel as if there is a method I am not seeing.

Just to be clear, my expected results are that when rA is randomized and equal to 1, rB will be forced to 1. If rA is randomized and equal to 0, then rB will also be randomized. My actual results match this. Just wondering if there is a way to do this without having to call a task after every .randomize() method call.

CodePudding user response:

You can simplify your code by using a different constraint and removing the task.

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

Here is an example print out:

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

If rA is randomly selected to be 1, then rB will be forced to 1; otherwise, rB will be random.

CodePudding user response:

What you want is called an implication constraint (Section 18.5.6 in the IEEE 1800-2017 SystemVerilog LRM.

expression -> constraint_set

If can also be written as

if (expression) constraint_set

But the first is preferred since the is an equation, not procedural code. In either case, when the LHS expression is true, the constraints on the RHS must be satified.

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