Tutorials

Learn More

As discussed in inline constraint, it is possible to change constraints during randomization and inline constraints should not conflict with constraints written in the class to avoid randomization failure. But sometimes there is a requirement to change constraints in such a way that it may conflict with constraints inside the class. For example, in the case of an error injection scenario, the variable value has to be randomized out of valid values to generate error scenarios. This can be done by using soft constraints to avoid randomization failures.

By default, constraints are hard constraints in nature. To mention constraints as a soft, specifically “soft” keyword has to be used.

Example without soft constraint

class seq_item;
  rand bit [7:0] val;
 
  constraint val_c {val inside {5, [10:15]};}
endclass

module constraint_example;
  seq_item item;
  
  initial begin
    item = new();
    
    repeat(5) begin
      item.randomize();
      $display("Before inline constraint: val = %0d", item.val);
           
      item.randomize with {val inside {[20:30]};};
      $display("After inline constraint: val = %0d", item.val);
    end
  end
endmodule

Output:

Error-[CNST-CIF] Constraints inconsistency failure
testbench.sv, 17
  Constraints are inconsistent and cannot be solved.
  Please check the inconsistent constraints being printed above and rewrite 
  them.

After inline constraint: val = 13

Example with soft constraint

class seq_item;
  rand bit [7:0] val;
 
  constraint val_c {soft val inside {5, [10:15]};}
endclass

module constraint_example;
  seq_item item;
  
  initial begin
    item = new();
    
    repeat(5) begin
      item.randomize();
      $display("Before inline constraint: val = %0d", item.val);
           
      item.randomize with {val inside {[20:30]};};
      $display("After inline constraint: val = %0d", item.val);
    end
  end
endmodule

Output:

Before inline constraint: val = 11
After inline constraint: val = 23
Before inline constraint: val = 12
After inline constraint: val = 21
Before inline constraint: val = 11
After inline constraint: val = 23
Before inline constraint: val = 10
After inline constraint: val = 22
Before inline constraint: val = 12
After inline constraint: val = 27

System Verilog Tutorials