SystemVerilog constraints examples

#1

Here’s a cheatsheet of SystemVerilog constraints patterns. Some are from the LRM and other are code examples of what I’ve used.

If there’s some other nifty example you can think of, add it to the thread below.

Set membership

/* using other variables as a part of a constraint */
rand integer x, y, z;
constraint c1 {x inside {3, 5, [9:15], [24:32], [y:2*y], z};}

rand integer a, b, c;
constraint c2 {a inside {b, c};}

/* constraint a variable to values from an array */
integer fives[4] = '{ 5, 10, 15, 20 }; rand integer v;
constraint c3 { v inside {fives}; }

Distribution

  • The := operator assigns the specified weight to the item or, if the item is a range, to every value in the range.
  • The :/ operator assigns the specified weight to the item or, if the item is a range, to the range as a whole. If there are n values in the range, the weight of each value is range_weight / n.
/* 
 * x is equal to 100, 101, 102, 200, or 300 with a 
 * weighted ratio of 1-1-1-2-5
 * i.e., probability of (x=100) is 1/10 and that of (x=300) is 5/10 
 */
x dist { [100:102] := 1, 200 := 2, 300 := 5};

/* x is equal to one of 100, 101, 102, 200, or 300 with 
 * a weighted ratio of 1/3-1/3-1/3-2-5
 */
x dist { [100:102] :/ 1, 200 := 2, 300 := 5}

Using foreach within a constraint

In this example

  • An IP packet is constructed
  • hdr_chain is an array and the constraint iterates over the array using a foreach loop
  • Each array entry is randomized depending upon what the previous entry was randomized to
constraint ip_pkt_cnstr {
  foreach (hdr_chain[i]) {
    if (i == 0) {
      hdr_chain[i] == ETHERNET;
    } else {
      if (hdr_chain[i-1] == ETHERNET) {
        hdr_chain[i] inside {VLAN, IPV4, IPV6};
      } else if(hdr_chain[i-1] == VLAN) {
        hdr_chain[i] inside {IPV4, IPV6};
      } else if(hdr_chain[i-1] inside {IPV4, IPV6}) {
        hdr_chain[i] inside {TCP, UDP};
      } else if(hdr_chain[i-1] inside {TCP, UDP}) {
        hdr_chain[i] inside {PAYLOAD};
      } else if(hdr_chain[i-1] == PAYLOAD) {
        hdr_chain[i] inside {END};
      } else {
        hdr_chain[i] inside {END};
      }
    }
  }
}
1 Like