Tuesday, September 17, 2024

Constraint to have N elements distributed in M bins

Code to distribute N elements into M bins, you add unique keyword to have each bin will have unique number of elements.

class test;
  parameter int M = 5;
  parameter int N = 100;
  rand bit[31:0] arr[M];
  
  constraint c_arr { arr.sum() == N; foreach(arr[i]) { arr[i] inside {[0:N-1]}; } unique {arr}; }
  
  function void post_randomize();
    foreach(arr[i])
    $display("Array[%01d]:%02d\n",i,arr[i]);
  endfunction
  
endclass

module top;
  test t;
  
  initial begin
    t = new;
    void'(t.randomize());
  end
endmodule

RESULT:

Compiler version U-2023.03-SP2_Full64; Runtime version U-2023.03-SP2_Full64; Sep 17 10:38 2024
Array[0]:23

Array[1]:01

Array[2]:10

Array[3]:11

Array[4]:15

Array[5]:21

Array[6]:14

Array[7]:03

Array[8]:02

Array[9]:00

V C S S i m u l a t i o n R e p o r t
Time: 0 ns
CPU Time: 0.430 seconds; Data structure size: 0.0Mb
Tue Sep 17 10:38:13 2024

How to kill a thread(s) in System Verilog

 The code use process class to kill the thread. 

class base;
  int id;
  
  task display();
    int x=0;
    for(int i=0;i<5;i++) begin 
      #10ns;
      x++;
      $display("%t BASE:%0d X:%0d",$time,id,x);
    end
  endtask

endclass

class test;
  process p[4];
  task run_phase();
    for(int i=0;i<4;i++) begin //{
      base b = new;
      fork: fork_p
        automatic base b1 = b;
        automatic int j = i;
        begin: run_d
          p[j] = process::self();
          b1.id = j;
          b1.display();
        end
      join_none
    end //}
    $display("%t Threads spawned",$time);
  endtask
  
endclass

module top;
  test t;
  
  initial begin
    t = new;
    fork
    t.run_phase();
    join_none
     #30ns;
    foreach(t.p[i]) t.p[i].kill();
  end
  
endmodule
  

Result:

Compiler version U-2023.03-SP2_Full64; Runtime version U-2023.03-SP2_Full64; Sep 17 10:31 2024
0 Threads spawned
10 BASE:0 X:1
10 BASE:1 X:1
10 BASE:2 X:1
10 BASE:3 X:1
20 BASE:0 X:2
20 BASE:1 X:2
20 BASE:2 X:2
20 BASE:3 X:2
V C S S i m u l a t i o n R e p o r t
Time: 30 ns
CPU Time: 0.370 seconds; Data structure size: 0.0Mb
Tue Sep 17 10:31:42 2024

How to bind multiple instances of module inside DUT

module my_mod ( input clk, input rst );
endmodule: my_mod
 
module dut ( input clk, input rst );
  genvar i;
  generate
    for(i=0;i<2;i++) begin: gen_my_mod
      my_mod u_my_mod ( .clk(clk), .rst(rst) );
    end
  endgenerate
endmodule
 
module bind_x ( input clk, input rst );
endmodule: bind_x
 
module tb;
  bit clk;
  bit rst;
  dut u_dut ( .clk(clk), .rst(rst) );
  bind u_dut.gen_my_mod[0].u_my_mod bind_x bind_inst (.clk(clk), .rst(rst));
  bind u_dut.gen_my_mod[1].u_my_mod bind_x bind_inst (.clk(clk), .rst(rst));
endmodule: tb

Constraint to have N elements distributed in M bins

Code to distribute N elements into M bins, you add unique keyword to have each bin will have unique number of elements. class test; param...