Gotcha: Using “rand” Modifier for Object Handles is not enough!

SystemVerilog allows rand modifier to be used for object handles and the object will be randomized only if it is not null.

The “gotcha” is that, depending on the simulator, no error or warning will be issued if you forget to initialize the randomized object.

Here is an example that illustrates the gotcha:

class item;
  rand int size;
endclass

class node;
  rand item item_1;
  rand item item_2;

  function new();
    item_2= new();
  endfunction

  function void post_randomize();
    $display($psprintf("item_1 is %p.", item_1));
    $display($psprintf("item_2 is %p.", item_2));
  endfunction
endclass

module top;
  initial begin
    automatic node a_node = new();
    void'(a_node.randomize());
  end
endmodule

The output is:

OUTPUT:
item_1 is '{null}.
item_2 is '{size:-1424717967}

This behavior is useful in case you want to avoid generation of objects: leave the object handles uninitialized and their generation will not be triggered.
However, in the majority of the cases, when you mark an object with “rand” modifier you do expect to see a randomized instance of it after every call of randomize() method.

Keep in mind that rand modifier is not sufficient for the objects members of a class to be generated, they also have to be initialized prior to randomization.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to our newsletter

Do you want to be up to date with our latest articles?