constraint mode

What is Constraint Mode?

Constraint mode in System Verilog allows you to enable or disable specific constraints dynamically during simulation. By default, all constraints in a class are active, but certain scenarios may require selective activation of constraints to create specific test conditions. This is achieved using the constraint_mode() system function.

  • constraint_mode(1) means constraint block is enabled.
  • constraint_mode(0) means constraint block is disabled.
  • Default value of constraint_mode() is 1.

Example of Constraint Mode

Let’s illustrate the use of constraint mode with an example:

class Packet;
  rand bit [7:0] address;
  rand bit [3:0] data;

  constraint addr_constraint {
    address inside {8'h10, 8'h20, 8'h30};
  }

  constraint data_constraint {
    data > 4'h5 && data < 4'hA;
  }
endclass

module test_constraint_mode;
  initial begin
    Packet pkt = new();

    // Randomize with all constraints active
    if (pkt.randomize())
      $display("All Constraints: Address = %h, Data = %h", pkt.address, pkt.data);

    // Disable the address constraint
    pkt.addr_constraint.constraint_mode(0);

    // Randomize with only the data constraint active
    if (pkt.randomize())
      $display("Address Constraint Disabled: Address = %h, Data = %h", pkt.address, pkt.data);

    // Re-enable the address constraint
    pkt.addr_constraint.constraint_mode(1);

    // Randomize again with all constraints active
    if (pkt.randomize())
      $display("Address Constraint Re-enabled: Address = %h, Data = %h", pkt.address, pkt.data);
  end
endmodule

Explanation:

  1. The addr_constraint and data_constraint define rules for the address and data variables, respectively.
  2. The $constraint_mode() function is used to disable and re-enable the addr_constraint.
  3. The behavior of the randomization changes based on which constraints are active, demonstrating fine-grained control over the generation process.

Output:

All Constraints: Address = 10, Data = 6
Address Constraint Disabled: Address = 9b, Data = 9
Address Constraint Re-enabled: Address = 30, Data = 7