Search code examples
classconstraintssystem-verilog

How to control the property rand_mode in a SystemVerilog class?


Suppose there is a class A like below:

class A;
rand logic [3:0] a;
rand logic [3:0] b;
rand logic [3:0] c;
constraint a_const{
    a<'h4;
}
constraint b_const{
    b<'h4;
}
endclass

When I use :

A at = new();
at.b_const.constraint_mode(0);
assert(at.randomize());

b is also randomized. But, I don't want that.

Is there a way I can only randomize a without randomizing b and c?

Because there can be many logics in a class, sometimes I just want to rand some of them. Put some of the logics in one class like A while some in other class B is one of the solutions, but it is too complicated.


Solution

  • If you only want one of the rand variables in a class to be randomized, then you can pass the variable to the randomize function:

    assert(at.randomize(a));
    

    Alternately, as you mentioned in the title to your question, you can use rand_mode to disable randomization of individual class variables:

    at.b.rand_mode(0);
    at.c.rand_mode(0);
    assert(at.randomize());
    

    Refer to IEEE Std 1800-2017, section 18.8 Disabling random variables with rand_mode().

    With either of the above approaches, only a will be randomized.


    I suspect you expected b_const.constraint_mode(0) to disable randomization of variable b. That line simply disables the named constraint, leaving b unconstrained. This means that b will be randomized in your original code (which is what you observed).