Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Equal Memory Partitions

SystemVerilog Constraints

Shows how to create equal regions in memory using constraints and randomization

Open in IDE
Related tutorial:
design.v
// Enter RTL Code
testbench.v
class MemoryBlock;
  
  bit [31:0]        m_ram_start;            // Start address of RAM
  bit [31:0]        m_ram_end;              // End address of RAM
  
  rand int          m_num_part;             // Number of partitions  
  bit [31:0]        m_part_start [];        // Partition start array (Removed 'rand')
  rand int          m_part_size;            // Size of each partition
  rand int          m_tmp;
    
  // Constrain number of partitions RAM has to be divided into
  constraint c_parts { m_num_part > 4; m_num_part < 10; }
  
  // Constraint size of each partition
  constraint c_size { m_part_size == (m_ram_end - m_ram_start)/m_num_part; }
  
  // Simulator Quirk: Verilator has trouble handling complex array indexing expressions
  // So, use post_randomize to dynamically size and calculate addresses safely
  function void post_randomize();
    m_part_start = new[m_num_part]; // Allocate the array size
    foreach (m_part_start[i]) begin
      if (i == 0) 
        m_part_start[i] = m_ram_start;
      else
        m_part_start[i] = m_part_start[i-1] + m_part_size;
    end
  endfunction
  
  function void display();
    $display ("------ Memory Block --------");
    $display ("RAM StartAddr   = 0x%0h", m_ram_start);
    $display ("RAM EndAddr     = 0x%0h", m_ram_end);
    $display ("# Partitions = %0d", m_num_part);
    $display ("Partition Size = %0d bytes", m_part_size);
    $display ("------ Partitions --------");
    foreach (m_part_start[i]) 
      $display ("Partition %0d start = 0x%0h", i, m_part_start[i]);
  endfunction
endclass

module tb;
  initial begin
    MemoryBlock mb = new;
    mb.m_ram_start = 32'h0;
    mb.m_ram_end   = 32'h7FF;       // 2KB RAM
    if (!mb.randomize()) begin
      $display("Randomization failed");
    end
    mb.display();
  end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.