Sunday, 2 July 2017

Unique constraint in SystemVerilog, Yes it is "Unique"

Sometimes, there is a need to generate unique values of the variables using randomization. There are different ways to generate unique values of variables. System Verilog has provided "unique" keyword which can be used to generate unique values in randomization. 

Below is the example of randomization:
Example:
class my_class;
    rand bit [1:0] a, b, c;
    constraint u { unique {a, b, c};}
endclass
  
module top();
    initial begin
    my_class c;
    int cntr;
    c = new();
    
    for(int i = 0; i < 5; i++) begin
        c.randomize();
        $display("a=%0d, b=%0d, c = %0d",c.a, c.b, c.c);
        if((c.a == c.b) || (c.a == c.c) || (c.b == c.c)) begin
            ++cntr;
            $display("value matched at:%0d", cntr);
        end
    end
    end
endmodule
  
Output:

a=2, b=3, c = 1
a=0, b=3, c = 1
a=0, b=2, c = 3
a=2, b=1, c = 3
a=2, b=3, c = 1

As shown in above example, "c" is randomized 5 times but non of the fields of "c" has same value.

Note: randc variable shall not be used with unique constraint.