Skip to content

Commit 80f8153

Browse files
committed
memories: replace ad-hoc python regex detector with Yosys $mem_v2 inference pass
Signed-off-by: Øyvind Harboe <oyvind.harboe@zylin.com>
1 parent 4f1e11c commit 80f8153

5 files changed

Lines changed: 257 additions & 7 deletions

File tree

‎flow/Makefile‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,17 +265,22 @@ yosys-dependencies: $(YOSYS_DEPENDENCIES)
265265
# .lib/.lef macro views for them. Experimental; see
266266
# docs/user/AutoMemories.md.
267267
ifeq ($(AUTO_MEMORIES),1)
268+
$(RESULTS_DIR)/memories_inferred.json: $(VERILOG_FILES) $(SCRIPTS_DIR)/memories/extract_memories.tcl
269+
mkdir -p $(RESULTS_DIR) $(LOG_DIR)
270+
$(SCRIPTS_DIR)/synth.sh $(SCRIPTS_DIR)/memories/extract_memories.tcl $(LOG_DIR)/memories_extract.log
271+
268272
.PHONY: do-auto-memories
269-
do-auto-memories:
273+
do-auto-memories: $(RESULTS_DIR)/memories_inferred.json
270274
mkdir -p $(RESULTS_DIR)
271275
$(PYTHON_EXE) $(SCRIPTS_DIR)/memories/gen_memories.py \
272276
--platform $(PLATFORM) \
277+
--yosys-json $(RESULTS_DIR)/memories_inferred.json \
273278
--out-dir $(RESULTS_DIR)/memories \
274279
--json $(RESULTS_DIR)/memories.json \
275280
$(foreach file,$(VERILOG_FILES),--verilog $(file)) \
276281
$(foreach file,$(ADDITIONAL_MEMORIES),--memories $(file))
277282

278-
$(RESULTS_DIR)/memories.json: $(VERILOG_FILES) $(ADDITIONAL_MEMORIES) \
283+
$(RESULTS_DIR)/memories.json: $(RESULTS_DIR)/memories_inferred.json $(ADDITIONAL_MEMORIES) \
279284
$(wildcard $(SCRIPTS_DIR)/memories/*.py)
280285
$(UNSET_AND_MAKE) do-auto-memories
281286

‎flow/scripts/memories/detect.py‎

Lines changed: 171 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
from __future__ import annotations
2323

24+
import json
2425
import re
2526
from pathlib import Path
2627

@@ -194,10 +195,177 @@ def scan_text(text: str, source_file: str = "") -> list[schema.Memory]:
194195
return out
195196

196197

198+
def parse_param_int(val) -> int:
199+
"""Parse a integer parameter from Yosys JSON (handles ints and binary strings)."""
200+
if isinstance(val, int):
201+
return val
202+
if isinstance(val, str):
203+
if val.startswith("0x"):
204+
return int(val, 16)
205+
try:
206+
return int(val, 2)
207+
except ValueError:
208+
return int(val)
209+
return int(val)
210+
211+
212+
def scan_yosys_json(data: dict | str | Path) -> list[schema.Memory]:
213+
"""Extract memory modules from a Yosys netlist JSON output ($mem_v2 cells)."""
214+
if isinstance(data, (str, Path)):
215+
p = Path(data)
216+
if not p.is_file():
217+
return []
218+
data = json.loads(p.read_text())
219+
220+
out: list[schema.Memory] = []
221+
modules = data.get("modules", {})
222+
223+
for mod_name, mod_info in modules.items():
224+
clean_mod_name = mod_name[1:] if mod_name.startswith("\\") else mod_name
225+
cells = mod_info.get("cells", {})
226+
for cell_name, cell_info in cells.items():
227+
cell_type = cell_info.get("type", "")
228+
if cell_type not in ("$mem_v2", "$mem"):
229+
continue
230+
231+
params = cell_info.get("parameters", {})
232+
conn = cell_info.get("connections", {})
233+
234+
size = parse_param_int(params.get("SIZE", 0))
235+
width = parse_param_int(params.get("WIDTH", 0))
236+
rd_ports = parse_param_int(params.get("RD_PORTS", 0))
237+
wr_ports = parse_param_int(params.get("WR_PORTS", 0))
238+
239+
if size == 0 or width == 0:
240+
continue
241+
242+
addr_w = (size - 1).bit_length() if size > 1 else 1
243+
244+
# Clock net tracking & single-clock verification across ports
245+
rd_clks = conn.get("RD_CLK", [])
246+
wr_clks = conn.get("WR_CLK", [])
247+
all_clk_bits = [
248+
c for c in rd_clks + wr_clks if str(c) not in ("0", "1", "x", "z")
249+
]
250+
single_clock = len(set(all_clk_bits)) <= 1
251+
252+
# Write enable mask lanes
253+
wr_en_bits = conn.get("WR_EN", [])
254+
mask_lanes = 0
255+
if wr_ports > 0 and len(wr_en_bits) > wr_ports:
256+
mask_lanes = len(wr_en_bits) // wr_ports
257+
258+
pins: list[schema.Pin] = []
259+
260+
for i in range(rd_ports):
261+
port_id = f"R{i}"
262+
pins.extend(
263+
[
264+
schema.Pin(
265+
name=f"{port_id}_clk",
266+
direction="input",
267+
width=1,
268+
port_id=port_id,
269+
function="clk",
270+
),
271+
schema.Pin(
272+
name=f"{port_id}_addr",
273+
direction="input",
274+
width=addr_w,
275+
port_id=port_id,
276+
function="addr",
277+
),
278+
schema.Pin(
279+
name=f"{port_id}_en",
280+
direction="input",
281+
width=1,
282+
port_id=port_id,
283+
function="en",
284+
),
285+
schema.Pin(
286+
name=f"{port_id}_data",
287+
direction="output",
288+
width=width,
289+
port_id=port_id,
290+
function="data_out",
291+
),
292+
]
293+
)
294+
295+
for i in range(wr_ports):
296+
port_id = f"W{i}"
297+
pins.extend(
298+
[
299+
schema.Pin(
300+
name=f"{port_id}_clk",
301+
direction="input",
302+
width=1,
303+
port_id=port_id,
304+
function="clk",
305+
),
306+
schema.Pin(
307+
name=f"{port_id}_addr",
308+
direction="input",
309+
width=addr_w,
310+
port_id=port_id,
311+
function="addr",
312+
),
313+
schema.Pin(
314+
name=f"{port_id}_en",
315+
direction="input",
316+
width=1,
317+
port_id=port_id,
318+
function="en",
319+
),
320+
schema.Pin(
321+
name=f"{port_id}_data",
322+
direction="input",
323+
width=width,
324+
port_id=port_id,
325+
function="data_in",
326+
),
327+
]
328+
)
329+
if mask_lanes > 0:
330+
pins.append(
331+
schema.Pin(
332+
name=f"{port_id}_mask",
333+
direction="input",
334+
width=mask_lanes,
335+
port_id=port_id,
336+
function="mask",
337+
)
338+
)
339+
340+
clean_cell = cell_name[1:] if cell_name.startswith("\\") else cell_name
341+
mem_name = clean_mod_name if len(cells) == 1 else clean_cell
342+
343+
mem = schema.Memory(
344+
name=mem_name,
345+
rows=size,
346+
bits=width,
347+
addr_w=addr_w,
348+
read_ports=rd_ports,
349+
write_ports=wr_ports,
350+
rw_ports=0,
351+
mask_lanes=mask_lanes,
352+
pins=pins,
353+
behavioral_model={"module": clean_mod_name},
354+
reason=f"Yosys inferred $mem_v2 ({'single-clock' if single_clock else 'multi-clock'})",
355+
)
356+
out.append(mem)
357+
358+
return out
359+
360+
197361
def scan_files(paths: list[Path]) -> list[schema.Memory]:
198-
"""Scan Verilog files; later definitions of a name win."""
362+
"""Scan Verilog files or Yosys JSON files; later definitions of a name win."""
199363
found: dict[str, schema.Memory] = {}
200364
for path in paths:
201-
for memory in scan_text(path.read_text(errors="replace"), str(path)):
202-
found[memory.name] = memory
365+
if path.suffix == ".json":
366+
for memory in scan_yosys_json(path):
367+
found[memory.name] = memory
368+
else:
369+
for memory in scan_text(path.read_text(errors="replace"), str(path)):
370+
found[memory.name] = memory
203371
return list(found.values())

‎flow/scripts/memories/detect_test.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,43 @@ def test_parameterized_width_disqualifies(self):
159159
text = BUS_STYLE.replace("[31:0]", "[WIDTH-1:0]")
160160
self.assertEqual(detect.scan_text(text), [])
161161

162+
def test_scan_yosys_json(self):
163+
yosys_json = {
164+
"modules": {
165+
"\\sram_256x32": {
166+
"cells": {
167+
"\\$mem_0": {
168+
"type": "$mem_v2",
169+
"parameters": {
170+
"SIZE": "00000000000000000000000100000000", # 256
171+
"WIDTH": "00000000000000000000000000100000", # 32
172+
"RD_PORTS": 1,
173+
"WR_PORTS": 1,
174+
},
175+
"connections": {
176+
"RD_CLK": [10],
177+
"WR_CLK": [10],
178+
"RD_EN": [11],
179+
"WR_EN": [12, 13, 14, 15], # 4 mask lanes
180+
"RD_ADDR": [16, 17, 18, 19, 20, 21, 22, 23],
181+
"WR_ADDR": [16, 17, 18, 19, 20, 21, 22, 23],
182+
"RD_DATA": list(range(24, 56)),
183+
"WR_DATA": list(range(56, 88)),
184+
},
185+
}
186+
}
187+
}
188+
}
189+
}
190+
mems = detect.scan_yosys_json(yosys_json)
191+
self.assertEqual(len(mems), 1)
192+
m = mems[0]
193+
self.assertEqual(
194+
(m.name, m.rows, m.bits, m.addr_w), ("sram_256x32", 256, 32, 8)
195+
)
196+
self.assertEqual((m.read_ports, m.write_ports, m.mask_lanes), (1, 1, 4))
197+
self.assertIn("single-clock", m.reason)
198+
162199

163200
if __name__ == "__main__":
164201
unittest.main()
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Yosys pre-synthesis pass for memory extraction.
2+
# Elaborates RTL and collects inferred memory arrays into $mem_v2 primitives.
3+
# tclint-disable command-args
4+
5+
source $::env(SCRIPTS_DIR)/synth_preamble.tcl
6+
7+
# Read all RTL sources using active frontend (slang, verific, or yosys verilog)
8+
read_design_sources
9+
10+
# Elaborate hierarchy
11+
hierarchy -top $::env(DESIGN_NAME)
12+
13+
# Run process execution and memory collection
14+
proc
15+
memory -nomap
16+
17+
# Write netlist JSON containing inferred $mem_v2 primitives
18+
set out_json "$::env(RESULTS_DIR)/memories_inferred.json"
19+
file mkdir [file dirname $out_json]
20+
write_json $out_json
21+
22+
exit

‎flow/scripts/memories/gen_memories.py‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,17 @@ def run(
5050
platform: str,
5151
out_dir: Path,
5252
json_path: Path,
53+
yosys_json: Path | None = None,
5354
) -> int:
5455
if platform != "asap7":
5556
sys.stderr.write(f"gen_memories: unsupported platform {platform}\n")
5657
return 1
5758

58-
found = detect.scan_files(verilog)
59+
if yosys_json and yosys_json.is_file():
60+
found = detect.scan_yosys_json(yosys_json)
61+
else:
62+
found = detect.scan_files(verilog)
63+
5964
idiomatic.apply(found)
6065

6166
overrides: list[schema.Memory] = []
@@ -110,6 +115,12 @@ def main(argv: list[str] | None = None) -> int:
110115
type=Path,
111116
help="Verilog source file to scan (repeatable).",
112117
)
118+
p.add_argument(
119+
"--yosys-json",
120+
type=Path,
121+
default=None,
122+
help="Yosys netlist JSON file containing $mem_v2 primitives.",
123+
)
113124
p.add_argument(
114125
"--memories",
115126
action="append",
@@ -132,7 +143,14 @@ def main(argv: list[str] | None = None) -> int:
132143
help="Path of the memories.json inventory to write.",
133144
)
134145
args = p.parse_args(argv)
135-
return run(args.verilog, args.memories, args.platform, args.out_dir, args.json)
146+
return run(
147+
args.verilog,
148+
args.memories,
149+
args.platform,
150+
args.out_dir,
151+
args.json,
152+
args.yosys_json,
153+
)
136154

137155

138156
if __name__ == "__main__":

0 commit comments

Comments
 (0)