Here is the code:
class packet;
rand bit [6:0] num;
randc bit [6:0] a;
rand enum {EVEN,ODD} number;
constraint c1 {a inside {35,36,40,45,[52:128]};}
constraint c2 {num == func(a);}
function bit [6:0] func(a);
if(a%2 == 0)
begin
number = EVEN;
$display("\nThe number is %0s and %0d",number.name(),a);
end
else if(a%2 != 0)
begin
number = ODD;
$display("\nThe number is %0s and %0d",number.name(),a);
end
endfunction
endclass: packet
module even_odd_number_functional_constraint;
initial
begin
packet pkt = new;
repeat (5)
begin
pkt.randomize();
end
end
endmodule: even_odd_number_functional_constraint
Here is the OP:
The number is EVEN and 0
The number is ODD and 1
The number is EVEN and 0
The number is ODD and 1
The number is EVEN and 0
Thanks in advance!
In reply to Shashank Gurijala:
It’s working after adding the following:
class packet;
rand bit [6:0] num;
randc bit [6:0] a;
rand enum {EVEN,ODD} number;
constraint c1 {a inside {35,36,40,45,[52:128]};}
constraint c2 {num == func(a);}
function bit [6:0] func(bit[6:0]a); //edited part
if(a%2 == 0)
begin
number = EVEN;
$display("\nThe number is %0s and %0d",number.name(),a);
end
else if(a%2 != 0)
begin
number = ODD;
$display("\nThe number is %0s and %0d",number.name(),a);
end
endfunction
endclass: packet
module even_odd_number_functional_constraint;
initial
begin
packet pkt = new;
repeat (5)
begin
pkt.randomize();
end
end
endmodule: even_odd_number_functional_constraint
I want to know why there is a need to again declare the data type and the size of bits of ‘a’ inside function despite it being a global variable to the class packet.
In reply to Shashank Gurijala:
the prototype of a function has the input arguments type/size defined if you use
function bit [6:0] func(a);
This declares a method that returns a 7-bit value and uses a variable named “a” as input since the type and size is not defined by default SV uses bit so, you are defining a method that takes a 1-bit variable as input, that is why in your code you only see “0” or “1” because you are effectively passing “a[0]”, also I do not see where do you return the value in your function.
Please always check the result of the randomize call i.e if(!ptk.randomize) $fatal/$error
Also please read the LRM section 18.5.12 Functions in constraints to understand the details involved in using them.
For example:
1- Functions in constraints cannot have side-effects, $display is a side effect in this context I believe also changing the variable “number”.
2- There is an ordering is based on input arguments.
Could you please elaborate on what you want maybe people can offer some solution, is not clear to me, if you want to control ‘num’, ‘number’ based on the value of ‘a’
HTH,
-R