Randomization with function

In reply to boryah:

Hi, everyone!
i cannot randomize my object, if i use function in constrainsts:

class A;
rand int a;
rand int b;
function static int foo(int i);
$display("call foo() with a: %0d, b: %0d", a, b);
return i == 0;
endfunction
constraint b_c {    
b inside {[0:5]};
};
constraint a_c {   
a == foo(b);
a inside {[1:5]};
};
endclass
A a = new();
module tb;
initial begin
void'(a.randomize());
$display("Result: %p", a);
$finish();
end
endmodule

i receive following message:
looks like solver has made one run with a = 0, b=3 and then stopped
if i do not use function, like this

class A;
rand int a;
rand int b;
function static int foo(int i);
$display("call foo() with a: %0d, b: %0d", a, b);
return (i == 0);
endfunction
constraint b_c {    
b inside {[0:5]};
};
constraint a_c {   
if (b==0) a == 1;
else a == 0;
a inside {[1:5]};
};
endclass
A a = new();
module tb;
initial begin
void'(a.randomize());
$display("Result: %p", a);
$finish();
end
endmodule

solver works correctly:
can anyone explain, why function are not working with randomization?
I use Questa 2020.1

You may need to read the LRM section 18.5.12 Functions in constraints, where there is a mention about:
*“Functions that appear in constraint expressions should be automatic (or preserve no state information)
and have no side effects.”

*

However I believe your issue is due to the ordering that is establish when using functions in constraints, basically “b” gets solved first as “3” then foo(3) = 0, which creates the conflict of a == 0 and a inside {[1:5]}

"Random variables used as function arguments shall establish an implicit variable ordering or
priority. Constraints that include only variables with higher priority are solved before other, lower
priority constraints. Random variables solved as part of a higher priority set of constraints become
state variables to the remaining set of constraints.
For example:

class B;
rand int x, y;
constraint C { x <= F(y); }
constraint D { y inside { 2, 4, 8 } ; }
endclass

forces y to be solved before x. Thus, constraint D is solved separately before constraint C, which uses
the values of y and F(y) as state variables. In SystemVerilog, the behavior for variable ordering
implied by function arguments differs from the behavior for ordering specified using the
“solve…before…” constraint; function argument variable ordering subdivides the solution space
thereby changing it. Because constraints on higher priority variables are solved without considering
lower priority constraints at all, this subdivision can cause the overall constraints to fail. Within each
prioritized set of constraints, cyclical (randc) variables are solved first.

"

BTW is always good practice to test if randomize was successful or not in your code, for example:

if(!a.randomize()) $fatal(1, "Randomize Failed");

HTH,
-R