Memories: RAM & ROM

Arrays of registers, synchronous RAM with read-first behaviour, ROM look-up tables, and how tools map them to block RAM.

A memory in Verilog is an array of vectors: reg [7:0] mem [0:15] is 16 words of 8 bits. Written in the right pattern, synthesis tools recognize it and use dedicated memory blocks (block RAM on FPGAs, SRAM macros on chips) instead of thousands of flip-flops.

A RAM and a ROM

if (we) mem[addr] <= din; writes the addressed word on the rising edge.

dout <= mem[addr]; reads in the same clock; because both are non-blocking, a read of the word being written returns the OLD data (read-first).

The sine ROM stores one period of a sine wave as 8 samples between 1 and 255.

Inferring block RAM

always @(posedge clk) if (rst) for (i = 0; i < 1024; i = i + 1) mem[i] <= 0;

Reset the control logic, not the memory contents A reset loop over the whole memory forces the tool to build it from flip-flops: block RAMs cannot be cleared in one cycle. Clear memory with a write sequence if it is really needed.

Declare a memory of 256 words, 16 bits each.

reg [15:0] mem [0:255];

What does read-first mean for a RAM?

When the same address is written and read in one clock, the read returns the data that was stored before the write. Write-first returns the new data instead.