SystemVerilog foreach loop Constraint Blocks

foreach constraint

SystemVerilog supports using the foreach loop inside a constraint block. using the foreach loop within the constraint block will make easy to constrain an array. The foreach loop iterates over the elements of an array, so constraints with the foreach loop are called Iterative constraints.
the foreach constraint will be applicable to an array with one or more than one element. so it’s required to specify or constrain the size of the dynamic array.

constraint constraint_name { foreach ( variable[iterator] )  variable[iterator] <..conditions..>  }

foreach loop constraint example

In the below example,
addr and data are the two dynamic arrays, the first size of the arrays is constrained and then the values for each array element are constrained using a foreach loop.

Constraining array sizes,
constraint asize     { addr.size < 4; }
constraint dsize     { data.size == addr.size; }

Constraining array elements,
constraint avalues { foreach ( addr[i] ) addr[i] inside {4,8,12,16}; }
constraint dvalues { foreach ( data[j] ) data[j] > 4 * j; }

class packet;
  rand byte addr [];
  rand byte data [];

  constraint avalues { foreach( addr[i] ) addr[i] inside {4,8,12,16}; }
  constraint dvalues { foreach( data[j] ) data[j] > 4 * j; }
  constraint asize   { addr.size < 4; }
  constraint dsize   { data.size == addr.size; }
endclass

module constr_iteration;
  initial begin
    packet pkt;
    pkt = new();

    $display("------------------------------------");
    repeat(2) begin
      pkt.randomize();
      $display("\taddr-size = %0d data-size = %0d",pkt.addr.size(),pkt.data.size());
      foreach(pkt.addr[i]) $display("\taddr = %0d data = %0d",pkt.addr[i],pkt.data[i]);
      $display("------------------------------------");
    end
  end
endmodule

Simulator Output

------------------------------------
addr-size = 2 data-size = 2
addr = 4 data = 101
addr = 16 data = 21
------------------------------------
addr-size = 3 data-size = 3
addr = 16 data = 89
addr = 4 data = 19
addr = 16 data = 13
------------------------------------

Click to execute on   

❮ Previous Next ❯