Tudor Timi
Tudor Timi

Reputation: 7573

Constraining an entire array in SystemVerilog based on another array

Is it possible to constraint an entire array in SystemVerilog to have the same value as another array?

I tried this:

class some_class;
   rand bit array1[10][10];
   rand bit array2[10][10];

   constraint arrays_c {
      array1 == array2;
   }
enclass

This isn't allowed in 2 of the Big3 simulators I've tried. One says it isn't currently supported and the other refers me to the constraint BNF, complaining that it isn't a valid integral expression.

Is there any other way of doing this, aside from setting a bit foreach constraint? What I ultimately want is to return an array from a function and use it to constrain another array that is a class field.

Upvotes: 1

Views: 2535

Answers (1)

Greg
Greg

Reputation: 19122

Use a foreach, see IEEE Std 1800-2012 § 18.5.8.1 foreach iterative constraints

constraint arrays_c {
  foreach(array1[i,j]) {
    array1[i][j] == array2[i][j];
  }
}

If you want a copy of a random array, the better approach is to assign the copy in the post_randomize function. It is less CPU incentive.

class some_class;
   rand bit array1[10][10];
   bit array2[10][10];

   function void post_randomize();
     array2 = array1;
   endfuction : post_randomize
enclass

If foreach in a constraint block and post_randomize calculations are not viable solutions, then use is packed arrays.

class some_class;
   rand bit [9:0][9:0] array1; // double packed
   rand bit [9:0][9:0] array2;

   constraint arrays_c {
    array1 == array2;
   }
enclass

Or use pack arrays and bit-stream assignments to make the end result unpacked

class some_class;
   bit array1[10][10];
   bit array2[10][10];
   rand bit [$bits(array1)-1:0] flat_array1,flat_array2;

   constraint arrays_c {
    flat_array1 == flat_array2;
   }

   function void post_randomize();
     {>>{array1}} = flat_array1; // bit-stream assignment
     {>>{array2}} = flat_array2;
   endfuction : post_randomize
enclass

Upvotes: 2

Related Questions