This repository was archived by the owner on Aug 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmemory.v
More file actions
72 lines (61 loc) · 2.52 KB
/
memory.v
File metadata and controls
72 lines (61 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*----------------------------------------------------------------------------
Unified instruction/data memory for CPU
- Reads are combinational/instantaneous
- Writes occur on rising edge of clock
- Reads/write data are 32-bit (4 byte) words
- Addresses (PC and data_addr) should be aligned to 32-bit words
(i.e. the two LSB should be zero)
- Simulated memory size is 16KiB (rather than the maximum addressible
2^32 bytes), so the upper 18 bits of the addresses must be zero
----------------------------------------------------------------------------*/
module memory
(
// Read port for instructions
input [31:0] PC, // Program counter (instruction address)
output [31:0] instruction,
// Read/write port for data
output [31:0] data_out,
input [31:0] data_in,
input [31:0] data_addr,
input clk,
input wr_en
);
// 16KiB memory, organized as 4096 element array of 32-bit words
reg [31:0] mem [4095:0];
// Alternative: 16KiB memory, organized as 16384 element array of bytes
// This is closer to the physical implementation but makes the Verilog
// messier since you need to access multiple bytes at once.
// reg [7:0] mem [2**14-1:0];
// Simplified memory "read ports"
assign instruction = mem[ PC[13:2] ];
assign data_out = mem[ data_addr[13:2] ];
// Note: Discards the low 2 bits of the address (which should be zero)
// since we implemented the memory as an array of words instead of bytes.
// Discards upper 18 bits of address (which should be zero) because memory
// is only 16 KiB (smaller than maximum addressible 2^32 bytes).
// Data write port
always @(posedge clk) begin
if (wr_en) begin
mem[ data_addr[13:2] ] = data_in;
end
end
// Non-synthesizable debugging code for checking assertions about addresses
always @(data_addr) begin
if (| data_addr[1:0]) begin // Lower address bits != 00
$display("Warning: misaligned data_addr access, truncating: %h", data_addr);
end
if (| data_addr[31:14]) begin // Upper address bits non-zero
$display("Error: data_addr outside implemented memory range: %h", data_addr);
$stop();
end
end
always @(PC) begin
if (| PC[1:0]) begin // Lower PC bits != 00
$display("Warning: misaligned PC access, truncating: %h", PC);
end
if (| PC[31:14]) begin // Upper PC bits non-zero
$display("Error: PC outside implemented memory range: %h", PC);
$stop();
end
end
endmodule