Skip to content

Commit 1cf0c31

Browse files
committed
memories: remove raw verilog regex scanner in favor of yosys json detector
Signed-off-by: Øyvind Harboe <oyvind.harboe@zylin.com>
1 parent b446a67 commit 1cf0c31

3 files changed

Lines changed: 122 additions & 373 deletions

File tree

‎flow/scripts/memories/detect.py‎

Lines changed: 9 additions & 193 deletions
Original file line numberDiff line numberDiff line change
@@ -1,202 +1,22 @@
11
#!/usr/bin/env python3
2-
"""Detect memory modules in Verilog sources by port-naming convention.
2+
"""Detect memory modules in Yosys netlist JSON outputs ($mem_v2 cells).
33
4-
Scans Verilog for modules whose entire port list follows the firtool
5-
(CIRCT) memory port convention: every port is named
6-
``<R|W|RW><n>_<function>`` — e.g. ``R0_addr``, ``W0_en``, ``RW0_wdata``,
7-
or the subword-split variants ``RW0_wdata_3`` / ``W0_mask_2``. Such
8-
modules are the memory wrappers emitted by Chisel/firtool (and by other
9-
generators that follow the same convention), and are the unit
10-
AUTO_MEMORIES turns into macros.
11-
12-
Yak-shave deliberately not done in this PR: yosys could be wired up as
13-
the memory detector instead of this ad-hoc Python scanner — its memory
14-
inference pass also finds memories that are embedded inside a larger
15-
module rather than separated out into a module with a name of its own
16-
(the case FPGA tools handle). Then again, perhaps OpenROAD SYN could
17-
become such a memory detector — it currently has no memory inference
18-
pass, which is also why this flow cannot simply lean on yosys inference.
19-
Punt on all of that with a fast, simple Python scanner.
4+
Processes the JSON netlist emitted by Yosys after `proc; memory -nomap`.
5+
Extracts memory parameters (depth, width, read/write port counts, write-enable
6+
masks) and checks clock net equivalence across ports to determine whether all
7+
ports share a single clock domain.
208
"""
219

2210
from __future__ import annotations
2311

2412
import json
25-
import re
2613
from pathlib import Path
2714

2815
import schema
2916

30-
_MODULE_HEADER_RE = re.compile(r"^\s*module\s+(\w+)\b", re.MULTILINE)
31-
# Capture every port — including names that follow a continuation comma
32-
# without their own `input`/`output` keyword (firtool emits `R0_clk` that
33-
# way). Each `input|output` group is a region running to the next
34-
# direction keyword or `);`, and the names inside are comma-separated.
35-
_DIR_REGION_RE = re.compile(
36-
r"\b(input|output|inout)\b\s*(\[[^\]]+\])?([^()]*?)"
37-
r"(?=\b(?:input|output|inout)\b|\);)",
38-
re.DOTALL,
39-
)
40-
_BUS_WIDTH_RE = re.compile(r"\[\s*(\d+)\s*:\s*(\d+)\s*\]")
41-
_NAME_RE = re.compile(r"\b([A-Za-z_]\w*)\b")
42-
_PORT_PIN_RE = re.compile(r"^(RW|R|W)(\d+)_([A-Za-z][A-Za-z0-9_]*)$")
43-
_SUBWORD_RE = re.compile(r"^(.*?)(?:_(\d+))?$")
44-
45-
46-
def _parse_module_ports(body: str) -> list[tuple[str, str, int]]:
47-
"""Return (name, direction, width) for each port of one module body."""
48-
ports: list[tuple[str, str, int]] = []
49-
open_paren = body.find("(")
50-
if open_paren < 0:
51-
return ports
52-
match = re.search(r"\)\s*;", body[open_paren:])
53-
if not match:
54-
return ports
55-
portlist = body[open_paren + 1 : open_paren + match.end()]
56-
for m in _DIR_REGION_RE.finditer(portlist):
57-
direction = m.group(1)
58-
bracket = m.group(2)
59-
rest = m.group(3)
60-
width = 1
61-
if bracket:
62-
bm = _BUS_WIDTH_RE.search(bracket)
63-
if bm:
64-
width = abs(int(bm.group(1)) - int(bm.group(2))) + 1
65-
else:
66-
# Parameterized or otherwise non-literal bus width:
67-
# disqualify the module rather than silently modeling
68-
# the port as 1 bit wide (it falls back to flops).
69-
return []
70-
for chunk in rest.split(","):
71-
nm = _NAME_RE.search(chunk)
72-
if not nm:
73-
continue
74-
name = nm.group(1)
75-
if name in ("input", "output", "inout"):
76-
continue
77-
ports.append((name, direction, width))
78-
return ports
79-
80-
81-
def _classify_tail(kind: str, tail: str) -> str | None:
82-
"""Map a pin-name tail to a schema pin function, or None if unknown.
83-
84-
Subword-split data and mask pins (`wdata_3`, `mask_0`) map to the
85-
same function as their unsplit form; the split only affects how many
86-
pins carry the function.
87-
"""
88-
if tail in ("addr", "en", "wmode", "clk"):
89-
return tail
90-
base = _SUBWORD_RE.match(tail).group(1)
91-
if base in ("mask", "wmask"):
92-
return "mask"
93-
if base == "wdata":
94-
return "data_in"
95-
if base == "rdata":
96-
return "data_out"
97-
if base == "data":
98-
if kind == "R":
99-
return "data_out"
100-
if kind == "W":
101-
return "data_in"
102-
return None # RW ports must use wdata/rdata
103-
return None
104-
105-
106-
def classify_module(
107-
name: str, ports: list[tuple[str, str, int]], source_file: str = ""
108-
) -> schema.Memory | None:
109-
"""Build a Memory from a module port list, or None if not a memory.
110-
111-
A module qualifies only when *every* port matches the convention —
112-
a single unrecognized port disqualifies it, so ordinary logic
113-
modules that happen to contain an `R0_...` name are not swept in.
114-
"""
115-
if not ports:
116-
return None
117-
pins: list[schema.Pin] = []
118-
groups: dict[str, list[schema.Pin]] = {}
119-
for pname, direction, width in ports:
120-
m = _PORT_PIN_RE.match(pname)
121-
if not m:
122-
return None
123-
kind, num, tail = m.group(1), m.group(2), m.group(3)
124-
function = _classify_tail(kind, tail)
125-
if function is None:
126-
return None
127-
pin = schema.Pin(
128-
name=pname,
129-
direction=direction,
130-
width=width,
131-
port_id=kind + num,
132-
function=function,
133-
)
134-
pins.append(pin)
135-
groups.setdefault(kind + num, []).append(pin)
136-
137-
n_read = n_write = n_rw = 0
138-
addr_w = 0
139-
bits = 0
140-
mask_lanes = 0
141-
for port_id, group in groups.items():
142-
functions = {p.function for p in group}
143-
if "clk" not in functions or "addr" not in functions:
144-
return None
145-
if port_id.startswith("RW"):
146-
if not {"wmode", "data_in", "data_out"} <= functions:
147-
return None
148-
n_rw += 1
149-
elif port_id.startswith("R"):
150-
if "data_out" not in functions:
151-
return None
152-
n_read += 1
153-
else:
154-
if "data_in" not in functions:
155-
return None
156-
n_write += 1
157-
addr_w = max(addr_w, max(p.width for p in group if p.function == "addr"))
158-
for function in ("data_in", "data_out"):
159-
bits = max(bits, sum(p.width for p in group if p.function == function))
160-
mask_lanes = max(
161-
mask_lanes, sum(p.width for p in group if p.function == "mask")
162-
)
163-
if addr_w == 0 or bits == 0:
164-
return None
165-
return schema.Memory(
166-
name=name,
167-
rows=1 << addr_w,
168-
bits=bits,
169-
addr_w=addr_w,
170-
read_ports=n_read,
171-
write_ports=n_write,
172-
rw_ports=n_rw,
173-
mask_lanes=mask_lanes,
174-
pins=pins,
175-
behavioral_model={"file": source_file, "module": name},
176-
)
177-
178-
179-
def scan_text(text: str, source_file: str = "") -> list[schema.Memory]:
180-
"""Find every memory-shaped module in one Verilog text."""
181-
out: list[schema.Memory] = []
182-
# Strip block and line comments so a comment inside a port list (or
183-
# a commented-out module) cannot confuse the port parser.
184-
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
185-
text = re.sub(r"//[^\n]*", "", text)
186-
headers = list(_MODULE_HEADER_RE.finditer(text))
187-
for i, m in enumerate(headers):
188-
start = m.start()
189-
end = headers[i + 1].start() if i + 1 < len(headers) else len(text)
190-
memory = classify_module(
191-
m.group(1), _parse_module_ports(text[start:end]), source_file
192-
)
193-
if memory is not None:
194-
out.append(memory)
195-
return out
196-
19717

19818
def parse_param_int(val) -> int:
199-
"""Parse a integer parameter from Yosys JSON (handles ints and binary strings)."""
19+
"""Parse an integer parameter from Yosys JSON (handles ints and binary strings)."""
20020
if isinstance(val, int):
20121
return val
20222
if isinstance(val, str):
@@ -359,13 +179,9 @@ def scan_yosys_json(data: dict | str | Path) -> list[schema.Memory]:
359179

360180

361181
def scan_files(paths: list[Path]) -> list[schema.Memory]:
362-
"""Scan Verilog files or Yosys JSON files; later definitions of a name win."""
182+
"""Scan Yosys netlist JSON files; later definitions of a name win."""
363183
found: dict[str, schema.Memory] = {}
364184
for path in paths:
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
185+
for memory in scan_yosys_json(path):
186+
found[memory.name] = memory
371187
return list(found.values())

0 commit comments

Comments
 (0)