Home / Learn Verilog / Constrained Randomization
Constrained Randomization
Random but legal.
Quick summaryRandom but legal.
How to think about this
The basic idea
Declare fields as rand and add constraints; randomize() picks values satisfying them.
Why this comes up
Finds corner cases directed tests miss.
The mechanics
constraint blocks.
Where it is used
- Everyday RTL design
- FPGA and ASIC projects
- Testbenches and debugging
Try it
Random values with a limit (plain Verilog)Verilog: edit and run
SystemVerilog does this with a constraint block.
class Pkt;\n rand bit [7:0] len;\n constraint c_len { len inside {[1:100]}; len dist {[1:10] := 1, [11:100] := 9}; }\nendclassCareful:This simulator runs the core of SystemVerilog (logic, always_ff, always_comb, enum, typedef, int, loops with int, break/continue, inside, immediate assert). Features shown only in the grey code box need a full simulator (Icarus -g2012, Verilator, Questa, VCS, Xcelium).
Quick check
1. A constraint...
Legal ranges.