Skip to content

Commit 8788455

Browse files
committed
memories: replace ad-hoc python regex detector with Yosys $mem_v2 inference pass
1 parent 4f1e11c commit 8788455

5 files changed

Lines changed: 190 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: 112 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,10 +194,119 @@ def scan_text(text: str, source_file: str = "") -> list[schema.Memory]:
194194
return out
195195

196196

197+
def parse_param_int(val) -> int:
198+
"""Parse a integer parameter from Yosys JSON (handles ints and binary strings)."""
199+
if isinstance(val, int):
200+
return val
201+
if isinstance(val, str):
202+
if val.startswith("0x"):
203+
return int(val, 16)
204+
try:
205+
return int(val, 2)
206+
except ValueError:
207+
return int(val)
208+
return int(val)
209+
210+
211+
def scan_yosys_json(data: dict | str | Path) -> list[schema.Memory]:
212+
"""Extract memory modules from a Yosys netlist JSON output ($mem_v2 cells)."""
213+
if isinstance(data, (str, Path)):
214+
p = Path(data)
215+
if not p.is_file():
216+
return []
217+
import json
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 = [c for c in rd_clks + wr_clks if str(c) not in ("0", "1", "x", "z")]
248+
single_clock = (len(set(all_clk_bits)) <= 1)
249+
250+
# Write enable mask lanes
251+
wr_en_bits = conn.get("WR_EN", [])
252+
mask_lanes = 0
253+
if wr_ports > 0 and len(wr_en_bits) > wr_ports:
254+
mask_lanes = len(wr_en_bits) // wr_ports
255+
256+
pins: list[schema.Pin] = []
257+
258+
for i in range(rd_ports):
259+
port_id = f"R{i}"
260+
pins.extend([
261+
schema.Pin(name=f"{port_id}_clk", direction="input", width=1, port_id=port_id, function="clk"),
262+
schema.Pin(name=f"{port_id}_addr", direction="input", width=addr_w, port_id=port_id, function="addr"),
263+
schema.Pin(name=f"{port_id}_en", direction="input", width=1, port_id=port_id, function="en"),
264+
schema.Pin(name=f"{port_id}_data", direction="output", width=width, port_id=port_id, function="data_out"),
265+
])
266+
267+
for i in range(wr_ports):
268+
port_id = f"W{i}"
269+
pins.extend([
270+
schema.Pin(name=f"{port_id}_clk", direction="input", width=1, port_id=port_id, function="clk"),
271+
schema.Pin(name=f"{port_id}_addr", direction="input", width=addr_w, port_id=port_id, function="addr"),
272+
schema.Pin(name=f"{port_id}_en", direction="input", width=1, port_id=port_id, function="en"),
273+
schema.Pin(name=f"{port_id}_data", direction="input", width=width, port_id=port_id, function="data_in"),
274+
])
275+
if mask_lanes > 0:
276+
pins.append(
277+
schema.Pin(name=f"{port_id}_mask", direction="input", width=mask_lanes, port_id=port_id, function="mask")
278+
)
279+
280+
clean_cell = cell_name[1:] if cell_name.startswith("\\") else cell_name
281+
mem_name = clean_mod_name if len(cells) == 1 else clean_cell
282+
283+
mem = schema.Memory(
284+
name=mem_name,
285+
rows=size,
286+
bits=width,
287+
addr_w=addr_w,
288+
read_ports=rd_ports,
289+
write_ports=wr_ports,
290+
rw_ports=0,
291+
mask_lanes=mask_lanes,
292+
pins=pins,
293+
behavioral_model={"module": clean_mod_name},
294+
reason=f"Yosys inferred $mem_v2 ({'single-clock' if single_clock else 'multi-clock'})",
295+
)
296+
out.append(mem)
297+
298+
return out
299+
300+
197301
def scan_files(paths: list[Path]) -> list[schema.Memory]:
198-
"""Scan Verilog files; later definitions of a name win."""
302+
"""Scan Verilog files or Yosys JSON files; later definitions of a name win."""
199303
found: dict[str, schema.Memory] = {}
200304
for path in paths:
201-
for memory in scan_text(path.read_text(errors="replace"), str(path)):
202-
found[memory.name] = memory
305+
if path.suffix == ".json":
306+
for memory in scan_yosys_json(path):
307+
found[memory.name] = memory
308+
else:
309+
for memory in scan_text(path.read_text(errors="replace"), str(path)):
310+
found[memory.name] = memory
203311
return list(found.values())
312+

‎flow/scripts/memories/detect_test.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,42 @@ 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((m.name, m.rows, m.bits, m.addr_w), ("sram_256x32", 256, 32, 8))
194+
self.assertEqual((m.read_ports, m.write_ports, m.mask_lanes), (1, 1, 4))
195+
self.assertIn("single-clock", m.reason)
196+
162197

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

‎flow/scripts/memories/gen_memories.py‎

Lines changed: 14 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,8 @@ 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(args.verilog, args.memories, args.platform, args.out_dir, args.json, args.yosys_json)
147+
136148

137149

138150
if __name__ == "__main__":

0 commit comments

Comments
 (0)