System Verilog rand_mode() and constraint_mode()

rand_mode():

Variables who is having random nature declared as rand or randc can be turned on or off dynamically by using an in-built method called rand_mode(). It can be called either function or task.

In the below example, you can see that how rand_mode we are going to use to disabled and enabled all variables.

class rmode; 
  rand int a; 
  randc int b; 
endclass 

program main; 
  rmode rnd = new(); 
  initial begin 
    void'(rnd.randomize()); 
    $display(" 1 : a : %0d,  b : %0d ",rnd.a, rnd.b);
    
    rnd.rand_mode(0); //disable random nature of variables
    void'(rnd.randomize()); 
    $display(" 2 : a : %0d,  b : %0d ",rnd.a, rnd.b);
    
    rnd.rand_mode(1); //enable random nature of variables
    void'(rnd.randomize());
    $display(" 3 : a : %0d,  b : %0d ",rnd.a, rnd.b); 
  end 
endprogram

rand_mode() for a specific variable

class rmode; 
  rand int a; 
  randc int b; 
endclass 

program main; 
  rmode rnd = new(); 
  initial begin 
    void'(rnd.randomize()); 
    $display(" 1 : a : %0d,  b : %0d ",rnd.a, rnd.b);
    
    rnd.a.rand_mode(0); //disable randomization for a
    void'(rnd.randomize()); 
    $display(" 2 : a : %0d,  b : %0d ",rnd.a, rnd.b);
    
    rnd.b.rand_mode(0); //disable randomization for b
    void'(rnd.randomize()); 
    $display(" 3 : a : %0d,  b : %0d ",rnd.a, rnd.b);
    
    rnd.a.rand_mode(1); //enable randomization for a but not for b
    void'(rnd.randomize());
    $display(" 4 : a : %0d,  b : %0d ",rnd.a, rnd.b); 
  end 
endprogram

constraint_mode()

SystemVerilog gives such a wonderful and more powerful feature that we can change the status of constraint block dynamically. You might think how and here we go !!

The constraint_mode() method can be used to control the nature of constraints i.e. enable/disable constraint. By default, all the constraint blocks are enabled. When a constraint is disabled, it is not considered by the randomize() method.

It can be used as a task or function.

When called a task, the argument to the constraint_mode() task method determines the operation to be performed. 

When called as a function, constraint_mode() returns the current active state of the specified constraint block. It returns 1 if the constraint is enabled (ON) and a 0 if the constraint is disabled (OFF).

Let’s understand by example.

class rmode; 
  rand int a; 
  rand int b; 
  constraint ct_a { a == 50;} 
  constraint ct_b { b == 100;} 
endclass 

program main; 
  rmode rnd = new(); 
  initial begin 
    void'(rnd.randomize()); 
    $display(" 1 : a : %0d,  b : %0d ",rnd.a, rnd.b);
    
    rnd.constraint_mode(0); //disable both the constraints
    void'(rnd.randomize()); 
    $display(" 2 : a : %0d,  b : %0d ",rnd.a, rnd.b);
    
    rnd.constraint_mode(1); //enable both the constraints
    void'(rnd.randomize());
    $display(" 3 : a : %0d,  b : %0d ",rnd.a, rnd.b); 
  end 
endprogram

Similar Posts