steveicarus / iverilog

Icarus Verilog
https://steveicarus.github.io/iverilog/
GNU General Public License v2.0
2.82k stars 523 forks source link

$random() w/ modulo bug #426

Closed Mop-u closed 3 years ago

Mop-u commented 3 years ago

Unusual behavior when using modulo with $random(). changing $random()%32; to $random()%'d32; fixes the issue, but obviously this can be a source of great confusion when it comes time to debug things (as I've experienced firsthand 😅)

iverilog -g2012 RandModulo.sv (using iverilog-v11-20201123-x64 windows build from http://bleyer.org/icarus/)

Test code:

module RandModulo();
reg clk = 0;
always #10 clk <= ~clk;

reg [15:0] Random = 0;
always_ff @(posedge clk) begin
    Random <= $random()%32;
    $display("%d",Random);
    if(Random > 32) $finish();
end
endmodule

Output:

    0
    4
65505
martinwhitaker commented 3 years ago

This is standard Verilog behaviour:

'd32 is an unsigned integer value, which is why it gives a different result.