From a632406e8a6a0773a86118f082a13a05146a5efe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Tue, 4 Aug 2026 00:00:01 +0200 Subject: [PATCH 1/6] flow: AUTO_MEMORIES generated memory macros via FakeRAM2.0 (experimental) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Detect memory-shaped modules (firtool R*/W*/RW*_ port convention) in the RTL before synthesis, inventory them in results/memories.json, and generate .lib/.lef macro views via FakeRAM2.0 for the ones idiomatic as SRAM macros. Signed-off-by: Øyvind Harboe --- MODULE.bazel | 13 +- docs/toc.yml | 2 + docs/user/AutoMemories.md | 164 ++++++++++++++ docs/user/FlowVariables.md | 6 +- flow/BUILD | 88 ++++++-- flow/Makefile | 23 ++ flow/designs/asap7/tinyRocket/BUILD | 3 + flow/designs/asap7/tinyRocket/config.mk | 30 +++ flow/designs/asap7/tinyRocket/constraint.sdc | 3 + .../asap7/tinyRocket/tag_array.memories | 10 + flow/scripts/load.tcl | 7 + .../memories/bazel-orfs-auto-memories.patch | 170 +++++++++++++++ flow/scripts/memories/detect.py | 203 ++++++++++++++++++ flow/scripts/memories/detect_test.py | 164 ++++++++++++++ flow/scripts/memories/gen_memories.py | 139 ++++++++++++ flow/scripts/memories/gen_memories_test.py | 157 ++++++++++++++ flow/scripts/memories/idiomatic.py | 49 +++++ flow/scripts/memories/idiomatic_test.py | 53 +++++ flow/scripts/memories/schema.py | 203 ++++++++++++++++++ flow/scripts/memories/schema_test.py | 120 +++++++++++ flow/scripts/read_liberty.tcl | 20 ++ flow/scripts/synth_preamble.tcl | 40 ++++ flow/scripts/variables.json | 18 +- flow/scripts/variables.yaml | 28 ++- .../fakeram/0001-Add-ORFS-ASAP7-backend.patch | 169 +++++++++++++++ patches/fakeram/BUILD.bazel | 3 + 26 files changed, 1848 insertions(+), 37 deletions(-) create mode 100644 docs/user/AutoMemories.md create mode 100644 flow/designs/asap7/tinyRocket/BUILD create mode 100644 flow/designs/asap7/tinyRocket/config.mk create mode 100644 flow/designs/asap7/tinyRocket/constraint.sdc create mode 100644 flow/designs/asap7/tinyRocket/tag_array.memories create mode 100644 flow/scripts/memories/bazel-orfs-auto-memories.patch create mode 100644 flow/scripts/memories/detect.py create mode 100644 flow/scripts/memories/detect_test.py create mode 100644 flow/scripts/memories/gen_memories.py create mode 100644 flow/scripts/memories/gen_memories_test.py create mode 100644 flow/scripts/memories/idiomatic.py create mode 100644 flow/scripts/memories/idiomatic_test.py create mode 100644 flow/scripts/memories/schema.py create mode 100644 flow/scripts/memories/schema_test.py create mode 100644 patches/fakeram/0001-Add-ORFS-ASAP7-backend.patch create mode 100644 patches/fakeram/BUILD.bazel diff --git a/MODULE.bazel b/MODULE.bazel index a36173378f..bd817bce80 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -101,7 +101,7 @@ bazel_dep(name = "bazel-orfs", version = "0.0.1") bazel_dep(name = "bazel-orfs-verilog", dev_dependency = True) -BAZEL_ORFS_COMMIT = "3342596c1f7017b9fda5b4a55a25a54ff2aaedf8" +BAZEL_ORFS_COMMIT = "6ebadeb4be5c9ada103081c9a5e668c014126616" BAZEL_ORFS_REMOTE = "https://github.com/The-OpenROAD-Project/bazel-orfs.git" @@ -131,6 +131,17 @@ git_override( remote = "https://github.com/povik/yosys-slang.git", ) +bazel_dep(name = "fakeram", dev_dependency = True) +git_override( + module_name = "fakeram", + commit = "6f62c655952b683cda679d80850cb557cc3c262e", + patch_strip = 1, + patches = [ + "//patches/fakeram:0001-Add-ORFS-ASAP7-backend.patch", + ], + remote = "https://github.com/The-OpenROAD-Project/FakeRAM2.0.git", +) + # --- Extensions --- register_toolchains( diff --git a/docs/toc.yml b/docs/toc.yml index 722c933ca5..be479807e0 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -19,6 +19,8 @@ entries: title: Build Using WSL - file: user/FlowVariables.md title: Flow Variables + - file: user/AutoMemories.md + title: Generated Memory Macros (AUTO_MEMORIES) - file: contrib/Metrics.md title: Metrics - file: user/InstructionsForAutoTuner.md diff --git a/docs/user/AutoMemories.md b/docs/user/AutoMemories.md new file mode 100644 index 0000000000..eddde0e660 --- /dev/null +++ b/docs/user/AutoMemories.md @@ -0,0 +1,164 @@ +# AUTO_MEMORIES: generated memory macros + +**Experimental.** AUTO_MEMORIES detects memories in a design's RTL +before synthesis and generates abstract `.lib`/`.lef` macro views for +them, so an existing design gets macro-based synthesis and physical +design results — including RTL-MP macro placement — without a memory +compiler or hand-maintained fakeram files. + +The intended audience is flows built on top of ORFS (for example +bazel-orfs based in-house flows) that need early, reasonable physical +results on designs whose memories exist only as behavioral RTL. Support +posture: if it works for you, great; if it needs fixing, the report is +itself a welcome signal that someone is using it. + +## What it does + +With `AUTO_MEMORIES=1`, a pre-synthesis step runs +`scripts/memories/gen_memories.py` over `VERILOG_FILES` and writes: + +| File | Content | +| --- | --- | +| `$(RESULTS_DIR)/memories.json` | Inventory of every detected memory: geometry, full pin list with pin functions, behavioral model, and whether it was converted (`idiomatic`) with a reason. | +| `$(RESULTS_DIR)/memories/.lib` | Generated Liberty view per converted memory. | +| `$(RESULTS_DIR)/memories/_pre_layout.lib` | Ideal-clock (zero clock-tree insertion) variant for pre-CTS consumers that select lib files themselves. The Makefile flow uses `.lib` throughout. | +| `$(RESULTS_DIR)/memories/.lef` | Abstract LEF per converted memory. | +| `$(RESULTS_DIR)/memories/blackboxes.txt` | Names of the converted modules — what synthesis blackboxes. | + +Synthesis (canonicalization) blackboxes the converted modules so the +liberty view wins over their behavioral bodies; floorplan through final +read the generated `.lib`/`.lef` alongside `ADDITIONAL_LIBS`/ +`ADDITIONAL_LEFS`. Everything downstream keys off the files above — +nothing else passes between the generator and the flow. That file-based +handoff is what lets build systems (e.g. bazel-orfs) declare the +generated artifacts as ordinary stage outputs and transitive +dependencies of the remaining stages. + +Memories that are *not* converted stay in the netlist and synthesize to +flip-flops, like any other RTL. + +## How memories are detected + +Detection is a fast Python scan (`scripts/memories/detect.py`) for +modules whose entire port list follows the firtool (CIRCT) memory port +convention: every port named `_`, e.g. `R0_addr`, +`W0_en`, `RW0_wdata`, including the subword-split forms `RW0_wdata_3` / +`W0_mask_2`. This is what Chisel/firtool emits for module-separated +memories, and what the rocket-chip generation of Chisel emitted (the +in-tree tinyRocket design). + +Two consequences, documented as deliberate scope: + +- **Module boundary only.** A memory embedded inside a larger module + (a bare `reg [7:0] mem [0:255]` next to other logic) is not detected. + Yosys's memory-inference pass sees those; FPGA tools extract them + into block RAMs. Wiring yosys up as the detector — or growing such a + pass in OpenROAD SYN, which currently has no memory inference and + therefore cannot be leaned on here either — is future work; this + feature punts on it with the simple scanner. +- **No banking.** Each detected memory maps to exactly one macro. A + memory too wide, too deep, or too ported for a single sensible macro + is not decomposed across several macros — a future extension. + +## The idiomatic gate + +Not every detected memory should be a macro. `scripts/memories/ +idiomatic.py` applies simple floors (minimum depth 16, minimum capacity +256 bits, at most 4 ports); memories below them are cheaper as +flip-flops than as a macro paying the fixed control/decode/sense-amp +floor. Rejected memories are kept in `memories.json` with +`"idiomatic": false` and a reason. + +To overrule the gate, list a `.memories` file in `ADDITIONAL_MEMORIES`: + +```json +{ + "version": 1, + "memories": [ + { + "name": "tag_array", + "idiomatic": true, + "reason": "forced: the RTL provides no behavioral fallback" + } + ] +} +``` + +Entries merge by name onto the detected set: fields the override +carries win, everything else (geometry, pins) is kept from detection. A +`.memories` entry naming a module the scanner never found is taken +whole — it must then describe its pins itself. The +`designs/asap7/tinyRocket` design demonstrates the forced-conversion +case: its `tag_array` wrapper is 4 entries deep (rejected by the gate) +but instantiates a module the sources never define, so flops are not an +option and the design forces conversion. + +## Generated views + +The `.lib` mirrors the structural shape OpenROAD's abstract writer +produces for hardened blocks: `bus()` groups **with per-bit `pin()` +records** (a bus without per-bit siblings makes yosys silently drop bit +connections at parent instances), per-port clock pins with +`min/max_clock_tree_path` arcs, setup/hold constraints on inputs, +clock-to-out arcs on outputs, and `internal_power()` records under a +`power_lut_template` so SAIF-driven power reporting is non-zero. + +The `.lef` is an abstract following the conventions of the platform's +fakeram abstracts: `CLASS BLOCK`, per-bit signal pin pads stacked along +the macro edge, interleaved horizontal power/ground straps the +platform's PDN macro grid connects to, and a full-footprint multi-layer +`OBS`. + +Timing and area come from simple parametric models +(`scripts/memories/liberty.py`, `scripts/memories/sram_area_model.py`): +log2(rows) decode depth and √bits bit-line scaling for timing; an area +model anchored to published 7 nm SP-SRAM figures (Suzuki et al., ISSCC +2018). These are budgetary models — good enough to make floorplanning, +placement, and timing behave representatively; not sign-off numbers. + +## Platform support + +**asap7 only.** The emitters are split into general structure +(`liberty.py`, `lef.py`, parameterized by a `PdkParams`) and platform +constants (`pdk_asap7.py`: pins and power straps on M4 — where the +platform's PDN macro grid connects — pin pad/pitch, strap geometry, +OBS layers, nominal voltage). Generalizing to other PDKs means +providing their `PdkParams` — the code seam exists, the calibration +work does not. `AUTO_MEMORIES=1` on any other platform fails with a +clear error. + +## Trying it + +```shell +# Unit tests (fast, no EDA tools): +bazelisk test //flow:memories_tests + +# The demo design: +make DESIGN_CONFIG=designs/asap7/tinyRocket/config.mk synth floorplan +``` + +The generator can also be run standalone to inspect what it would do: + +```shell +python3 flow/scripts/memories/gen_memories.py \ + --platform asap7 --out-dir /tmp/mems --json /tmp/memories.json \ + --verilog flow/designs/src/tinyRocket/freechips.rocketchip.system.TinyConfig.v +``` + +## Consuming from bazel-orfs + +Everything downstream keys off generated files, so a build system can +declare them as ordinary stage outputs and transitive dependencies. In +bazel-orfs each stage runs in a sandbox where only declared outputs +survive, so it additionally needs to declare `memories.json` plus the +`memories/` directory (a directory artifact — the per-memory file +names are only known at run time) as canonicalize outputs and stage +them into every downstream stage's sandbox. The bazel-orfs change that +does this is carried alongside this feature as +`flow/scripts/memories/bazel-orfs-auto-memories.patch`, to be +upstreamed to bazel-orfs once the feature lands here. + +## Variables + +- [AUTO_MEMORIES](FlowVariables.md#AUTO_MEMORIES) +- [ADDITIONAL_MEMORIES](FlowVariables.md#ADDITIONAL_MEMORIES) diff --git a/docs/user/FlowVariables.md b/docs/user/FlowVariables.md index 221406f855..0a28c48aeb 100644 --- a/docs/user/FlowVariables.md +++ b/docs/user/FlowVariables.md @@ -100,8 +100,10 @@ configuration file. | ADDITIONAL_GDS| Hardened macro GDS files listed here.| | | ADDITIONAL_LEFS| Hardened macro LEF view files listed here. The LEF information of the macros is immutable and used throughout all stages. Stored in the .odb file.| | | ADDITIONAL_LIBS| Hardened macro library files listed here. The library information is immutable and used throughout all stages. Not stored in the .odb file.| | +| ADDITIONAL_MEMORIES| Experimental. Space-separated list of user-supplied `.memories` files (the memories.json JSON schema) merged onto the set AUTO_MEMORIES detects — to force-convert a memory the idiomatic gate rejects, or to describe one the scanner cannot find. See docs/user/AutoMemories.md.| | | ADDITIONAL_SITES| Passed as -additional_sites to initialize_floorplan.| | | ASAP7_USE_VT| A space separated list of VT options to use with the ASAP7 standard cell library: RVT, LVT, SLVT.| RVT| +| AUTO_MEMORIES| Experimental. When set to 1, memory-shaped modules in the RTL (firtool/CIRCT `R*/W*/RW*_` port convention, module boundary only) are detected pre-synthesis, inventoried in `$(RESULTS_DIR)/memories.json`, and — when idiomatic as an SRAM macro — given generated .lib/.lef views under `$(RESULTS_DIR)/memories/`. Synthesis blackboxes those modules and all later stages read the generated views, so an existing design gets macro-based results without a memory compiler. Supported for the asap7 platform only. See docs/user/AutoMemories.md.| 0| | BALANCE_ROWS| Balance rows during placement.| 0| | BLOCKS| Blocks used as hard macros in a hierarchical flow. Do note that you have to specify block-specific inputs file in the directory mentioned by Makefile.| | | BUFFER_PORTS_ARGS| Specify arguments to the buffer_ports call during placement. Only used if DONT_BUFFER_PORTS=0.| | @@ -163,7 +165,6 @@ configuration file. | GPL_RANDOM_SEED| Specifies a random seed for global placement. Useful for perturbation studies.| | | GPL_ROUTABILITY_DRIVEN| Specifies whether the placer should use routability driven placement.| 1| | GPL_TIMING_DRIVEN| Specifies whether the placer should use timing driven placement.| 1| -| GRT_SEED| Specifies a random seed for global routing. Useful for perturbation studies.| | | GUI_TIMING| Load timing information when opening GUI. For large designs, this can be quite time consuming. Useful to disable when investigating non-timing aspects like floorplan, placement, routing, etc.| 1| | HOLD_SLACK_MARGIN| Specifies a time margin for the slack when fixing hold violations. This option allows you to overfix or underfix (negative value, terminate retiming before 0 or positive slack). floorplan.tcl uses min of HOLD_SLACK_MARGIN and 0 (default hold slack margin). This avoids overrepair in floorplan for hold by default, but allows skipping hold repair using a negative HOLD_SLACK_MARGIN. Exiting timing repair early is useful in exploration where the .sdc has a fixed clock period at the design's target clock period and where HOLD/SETUP_SLACK_MARGIN is used to avoid overrepair (extremely long running times) when exploring different parameter settings. When an ideal clock is used, that is before CTS, a clock insertion delay of 0 is used in timing paths. This creates a mismatch between macros that have a .lib file from after CTS, when the clock is propagated. To mitigate this, OpenSTA will use subtract the clock insertion delay of macros when calculating timing with ideal clock. Provided that min_clock_tree_path and max_clock_tree_path are in the .lib file, which is the case for macros built with OpenROAD. This is less accurate than if OpenROAD had created a placeholder clock tree for timing estimation purposes prior to CTS. There will inevitably be inaccuracies in the timing calculation prior to CTS. Use a slack margin that is low enough, even negative, to avoid overrepair. Inaccuracies in the timing prior to CTS can also lead to underrepair, but there no obvious and simple way to avoid underrapir in these cases. Overrepair can lead to excessive runtimes in repair or too much buffering being added, which can present itself as congestion of hold cells or buffer cells. Another use of SETUP/HOLD_SLACK_MARGIN is design parameter exploration when trying to find the minimum clock period for a design. The SDC_FILE for a design can be quite complicated and instead of modifying the clock period in the SDC_FILE, which can be non-trivial, the clock period can be fixed at the target frequency and the SETUP/HOLD_SLACK_MARGIN can be swept to find a plausible current minimum clock period.| 0| | IO_CONSTRAINTS| File path to the IO constraints .tcl file. Also used for manual placement.| | @@ -340,6 +341,7 @@ configuration file. - [ABC_DRIVER_CELL](#ABC_DRIVER_CELL) - [ABC_LOAD_IN_FF](#ABC_LOAD_IN_FF) - [ADDER_MAP_FILE](#ADDER_MAP_FILE) +- [ADDITIONAL_MEMORIES](#ADDITIONAL_MEMORIES) - [CACHED_REPORTS](#CACHED_REPORTS) - [CLKGATE_MAP_FILE](#CLKGATE_MAP_FILE) - [DFF_LIB_FILE](#DFF_LIB_FILE) @@ -535,7 +537,6 @@ configuration file. - [ENABLE_RESISTANCE_AWARE](#ENABLE_RESISTANCE_AWARE) - [GLOBAL_ROUTE_ARGS](#GLOBAL_ROUTE_ARGS) - [GLOBAL_ROUTE_USE_CUGR](#GLOBAL_ROUTE_USE_CUGR) -- [GRT_SEED](#GRT_SEED) - [HOLD_SLACK_MARGIN](#HOLD_SLACK_MARGIN) - [MAX_REPAIR_ANTENNAS_ITER_GRT](#MAX_REPAIR_ANTENNAS_ITER_GRT) - [MAX_ROUTING_LAYER](#MAX_ROUTING_LAYER) @@ -627,6 +628,7 @@ configuration file. - [ADDITIONAL_FILES](#ADDITIONAL_FILES) - [ADDITIONAL_LEFS](#ADDITIONAL_LEFS) - [ADDITIONAL_LIBS](#ADDITIONAL_LIBS) +- [AUTO_MEMORIES](#AUTO_MEMORIES) - [BLOCKS](#BLOCKS) - [CAP_MARGIN](#CAP_MARGIN) - [CDL_FILES](#CDL_FILES) diff --git a/flow/BUILD b/flow/BUILD index 9b6aeb9b64..4f57af10d8 100644 --- a/flow/BUILD +++ b/flow/BUILD @@ -1,4 +1,5 @@ load("@bazel-orfs//:openroad.bzl", "orfs_pdk") +load("@rules_python//python:defs.bzl", "py_library", "py_test") # Expose every individual file under platforms/ as a public source-file # target, so designs in other packages can refer to e.g. @@ -23,13 +24,7 @@ exports_files( # instead of vendoring its own (drifting) copy at the bazel-orfs repo # root. See bazel-orfs `private/rules.bzl`. exports_files( - [ - "scripts/synth.tcl", - # Expose variables.yaml as an addressable source label so the - # orfs-vars MCP server (//tools/orfs_mcp) can data-dep the ORFS - # variable catalogue pinned to this commit. - "scripts/variables.yaml", - ], + ["scripts/synth.tcl"], visibility = ["//visibility:public"], ) @@ -37,23 +32,31 @@ exports_files( MAKEFILE_SHARED = [ "scripts/variables.json", "scripts/*.py", + "scripts/memories/*.py", "scripts/*.sh", "scripts/*.yaml", "scripts/*.mk", ] +MAKEFILE_SHARED_EXCLUDE = [ + "scripts/memories/*_test.py", +] + # makefile and scripts used by script/synth.sh steps filegroup( name = "makefile_yosys", srcs = ["Makefile"], - data = glob(MAKEFILE_SHARED + [ - "scripts/*.script", - "scripts/*.v", - "scripts/util.tcl", - "scripts/synth*.tcl", - "scripts/synth*.v", - "platforms/common/**/*.v", - ]) + [ + data = glob( + MAKEFILE_SHARED + [ + "scripts/*.script", + "scripts/*.v", + "scripts/util.tcl", + "scripts/synth*.tcl", + "scripts/synth*.v", + "platforms/common/**/*.v", + ], + exclude = MAKEFILE_SHARED_EXCLUDE, + ) + [ "//flow/util:makefile_yosys", ], visibility = ["//visibility:public"], @@ -63,10 +66,13 @@ filegroup( filegroup( name = "makefile", srcs = ["Makefile"], - data = glob(MAKEFILE_SHARED + [ - "scripts/*.tcl", - "platforms/common/**/*.v", - ]) + [ + data = glob( + MAKEFILE_SHARED + [ + "scripts/*.tcl", + "platforms/common/**/*.v", + ], + exclude = MAKEFILE_SHARED_EXCLUDE, + ) + [ "//flow/util:makefile", ], visibility = ["//visibility:public"], @@ -179,3 +185,47 @@ filegroup( "sky130hd", "sky130hs", ]] + +# AUTO_MEMORIES: pre-synthesis memory detection and .lib/.lef macro view +# generation. See docs/user/AutoMemories.md. The unit tests are the +# feature's test coverage — run with `bazelisk test //flow:memories_tests`. +py_library( + name = "memories", + srcs = glob( + ["scripts/memories/*.py"], + exclude = ["scripts/memories/*_test.py"], + ), + imports = ["scripts/memories"], + data = ["@fakeram//:all_files"], +) + +# Test fixtures (Verilog snippets) live in detect_test.py and are +# imported by the other tests. +py_library( + name = "memories_test_fixtures", + srcs = ["scripts/memories/detect_test.py"], + imports = ["scripts/memories"], + deps = [":memories"], +) + +MEMORIES_TESTS = [ + "detect_test", + "gen_memories_test", + "idiomatic_test", + "schema_test", +] + +[py_test( + name = "memories_" + test, + srcs = ["scripts/memories/{}.py".format(test)], + main = "scripts/memories/{}.py".format(test), + deps = [ + ":memories", + ":memories_test_fixtures", + ], +) for test in MEMORIES_TESTS] + +test_suite( + name = "memories_tests", + tests = ["memories_" + test for test in MEMORIES_TESTS], +) diff --git a/flow/Makefile b/flow/Makefile index d3472ee015..517dcee2c5 100644 --- a/flow/Makefile +++ b/flow/Makefile @@ -261,6 +261,28 @@ $(SDC_FILE_CLOCK_PERIOD): $(SDC_FILE) .PHONY: yosys-dependencies yosys-dependencies: $(YOSYS_DEPENDENCIES) +# AUTO_MEMORIES: detect memories in the RTL pre-synthesis and generate +# .lib/.lef macro views for them. Experimental; see +# docs/user/AutoMemories.md. +ifeq ($(AUTO_MEMORIES),1) +.PHONY: do-auto-memories +do-auto-memories: + mkdir -p $(RESULTS_DIR) + $(PYTHON_EXE) $(SCRIPTS_DIR)/memories/gen_memories.py \ + --platform $(PLATFORM) \ + --out-dir $(RESULTS_DIR)/memories \ + --json $(RESULTS_DIR)/memories.json \ + $(foreach file,$(VERILOG_FILES),--verilog $(file)) \ + $(foreach file,$(ADDITIONAL_MEMORIES),--memories $(file)) + +$(RESULTS_DIR)/memories.json: $(VERILOG_FILES) $(ADDITIONAL_MEMORIES) \ + $(wildcard $(SCRIPTS_DIR)/memories/*.py) + $(UNSET_AND_MAKE) do-auto-memories + +yosys-dependencies: $(RESULTS_DIR)/memories.json +$(RESULTS_DIR)/1_1_yosys_canonicalize.rtlil: $(RESULTS_DIR)/memories.json +endif + .PHONY: do-yosys do-yosys: yosys-dependencies $(SCRIPTS_DIR)/synth.sh $(SYNTH_SCRIPT) $(LOG_DIR)/1_2_yosys.log @@ -278,6 +300,7 @@ $(RESULTS_DIR)/1_2_yosys.v $(RESULTS_DIR)/1_2_yosys.sdc: $(RESULTS_DIR)/1_1_yosy .PHONY: clean_synth clean_synth: rm -f $(RESULTS_DIR)/1_* $(RESULTS_DIR)/mem*.json + rm -rf $(RESULTS_DIR)/memories rm -f $(REPORTS_DIR)/synth_* rm -f $(LOG_DIR)/1_* rm -f $(SYNTH_STATS) diff --git a/flow/designs/asap7/tinyRocket/BUILD b/flow/designs/asap7/tinyRocket/BUILD new file mode 100644 index 0000000000..527d6542e1 --- /dev/null +++ b/flow/designs/asap7/tinyRocket/BUILD @@ -0,0 +1,3 @@ +load("//flow/designs:design.bzl", "design") + +design(config = "config.mk") diff --git a/flow/designs/asap7/tinyRocket/config.mk b/flow/designs/asap7/tinyRocket/config.mk new file mode 100644 index 0000000000..1d2ac6962a --- /dev/null +++ b/flow/designs/asap7/tinyRocket/config.mk @@ -0,0 +1,30 @@ +export DESIGN_NICKNAME = tinyRocket +export DESIGN_NAME = RocketTile +export PLATFORM = asap7 + +# The generic tinyRocket sources only: unlike the nangate45 tinyRocket +# there is no hand-written platform memory-mapping file and no +# checked-in fakeram .lib/.lef — AUTO_MEMORIES detects the memory +# wrapper modules and generates macro views for them instead. +export VERILOG_FILES = $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/AsyncResetReg.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/ClockDivider2.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/ClockDivider3.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/plusarg_reader.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/freechips.rocketchip.system.TinyConfig.v + +export SDC_FILE = $(DESIGN_HOME)/$(PLATFORM)/$(DESIGN_NICKNAME)/constraint.sdc + +export AUTO_MEMORIES = 1 +# tag_array (4x25) falls below the idiomatic-macro floors, but this RTL +# provides no behavioral fallback (the wrapper instantiates a +# tag_array_ext module the sources never define), so its conversion is +# forced via a .memories override. +export ADDITIONAL_MEMORIES = $(DESIGN_HOME)/$(PLATFORM)/$(DESIGN_NICKNAME)/tag_array.memories + +export CORE_UTILIZATION = 40 +export CORE_MARGIN = 2 + +export PLACE_DENSITY_LB_ADDON = 0.10 +export MACRO_PLACE_HALO = 2 2 + +export TNS_END_PERCENT = 100 diff --git a/flow/designs/asap7/tinyRocket/constraint.sdc b/flow/designs/asap7/tinyRocket/constraint.sdc new file mode 100644 index 0000000000..9eb2521bb4 --- /dev/null +++ b/flow/designs/asap7/tinyRocket/constraint.sdc @@ -0,0 +1,3 @@ +current_design RocketTile + +create_clock -name core_clock -period 1600 [get_ports {clock}] diff --git a/flow/designs/asap7/tinyRocket/tag_array.memories b/flow/designs/asap7/tinyRocket/tag_array.memories new file mode 100644 index 0000000000..fc03b36d73 --- /dev/null +++ b/flow/designs/asap7/tinyRocket/tag_array.memories @@ -0,0 +1,10 @@ +{ + "version": 1, + "memories": [ + { + "name": "tag_array", + "idiomatic": true, + "reason": "forced: the RTL provides no behavioral fallback for this wrapper" + } + ] +} diff --git a/flow/scripts/load.tcl b/flow/scripts/load.tcl index 6d946198d9..1b3a6c4632 100644 --- a/flow/scripts/load.tcl +++ b/flow/scripts/load.tcl @@ -23,6 +23,13 @@ proc load_design { design_file sdc_file } { read_lef $lef } } + # AUTO_MEMORIES: abstract LEFs generated pre-synthesis; globbed + # because the file names are only known at run time. + if { [env_var_equals AUTO_MEMORIES 1] } { + foreach lef [glob -nocomplain $::env(RESULTS_DIR)/memories/*.lef] { + read_lef $lef + } + } read_verilog $::env(RESULTS_DIR)/$design_file log_cmd link_design {*}[hier_options] $::env(DESIGN_NAME) } elseif { $ext == ".odb" } { diff --git a/flow/scripts/memories/bazel-orfs-auto-memories.patch b/flow/scripts/memories/bazel-orfs-auto-memories.patch new file mode 100644 index 0000000000..408c274a9b --- /dev/null +++ b/flow/scripts/memories/bazel-orfs-auto-memories.patch @@ -0,0 +1,170 @@ +From 43f2d13a2669cc590d3af06c4e74647321f68095 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?=C3=98yvind=20Harboe?= +Date: Sun, 19 Jul 2026 18:36:34 +0200 +Subject: [PATCH] rules: declare and propagate AUTO_MEMORIES stage artifacts +MIME-Version: 1.0 +Content-Type: text/plain; charset=UTF-8 +Content-Transfer-Encoding: 8bit + +ORFS's experimental AUTO_MEMORIES flow generates results/memories.json +plus a memories/ directory of generated .lib/.lef macro views during +canonicalization, and every later stage reads them from the results +dir at tcl run time. In bazel-orfs each stage runs in a sandbox where +only declared outputs survive, so without this change the generated +views are discarded after synthesis and floorplan fails to link the +blackboxed memory modules. + +Declare memories.json and the memories/ directory (a directory +artifact: the per-memory file names are only known at run time) as +canonicalize outputs when AUTO_MEMORIES=1, carry them on the new +OrfsInfo.memories field, and stage them into every downstream stage's +sandbox via source_inputs(). AUTO_MEMORIES is rejected with +SYNTH_USE_SYN, which has no yosys canonicalize step. + +User-supplied ADDITIONAL_MEMORIES files need no new machinery: they +reach the synth sandbox like any other sources= entry. + +Signed-off-by: Øyvind Harboe +--- + private/environment.bzl | 8 ++++++++ + private/providers.bzl | 1 + + private/rules.bzl | 29 ++++++++++++++++++++++++++--- + 3 files changed, 35 insertions(+), 3 deletions(-) + +diff --git a/private/environment.bzl b/private/environment.bzl +index f643501..f69359b 100644 +--- a/private/environment.bzl ++++ b/private/environment.bzl +@@ -229,6 +229,11 @@ def source_inputs(ctx): + ctx.attr.src[OrfsInfo].additional_lefs, + ctx.attr.src[OrfsInfo].additional_libs, + ctx.attr.src[OrfsInfo].additional_libs_pre_layout, ++ # AUTO_MEMORIES artifacts (memories.json + the generated ++ # .lib/.lef directory): later stages glob them from the ++ # results dir at tcl run time, so they must be staged in ++ # every downstream stage's sandbox. ++ ctx.attr.src[OrfsInfo].memories, + ctx.attr.src[PdkInfo].files, + ctx.attr.src[PdkInfo].libs, + # Accumulate all JSON reports, so depend on previous stage. +@@ -604,6 +609,9 @@ def _artifact_name(ctx, category, name = None): + def declare_artifact(ctx, category, name): + return ctx.actions.declare_file(_artifact_name(ctx, category, name)) + ++def declare_directory_artifact(ctx, category, name): ++ return ctx.actions.declare_directory(_artifact_name(ctx, category, name)) ++ + def declare_artifacts(ctx, category, names): + """Declares multiple artifacts in one call. + +diff --git a/private/providers.bzl b/private/providers.bzl +index e2eabb2..8c3e5bf 100644 +--- a/private/providers.bzl ++++ b/private/providers.bzl +@@ -17,6 +17,7 @@ OrfsInfo = provider( + "additional_libs", + "additional_libs_pre_layout", + "arguments", ++ "memories", + ], + ) + PdkInfo = provider( +diff --git a/private/rules.bzl b/private/rules.bzl +index 6f0e502..e8379ef 100644 +--- a/private/rules.bzl ++++ b/private/rules.bzl +@@ -21,6 +21,7 @@ load( + "data_inputs", + "declare_artifact", + "declare_artifacts", ++ "declare_directory_artifact", + "deps_inputs", + "environment_string", + "extensionless_basename", +@@ -262,6 +263,7 @@ def _macro_impl(ctx): + additional_lefs = depset([]), + additional_libs = depset([]), + additional_libs_pre_layout = depset([]), ++ memories = depset([]), + arguments = depset([]), + ), + TopInfo( +@@ -519,6 +521,7 @@ def _arguments_impl(ctx): + additional_lefs = src_info.additional_lefs, + additional_libs = src_info.additional_libs, + additional_libs_pre_layout = src_info.additional_libs_pre_layout, ++ memories = src_info.memories, + arguments = depset( + [computed_json], + transitive = [src_info.arguments], +@@ -1353,6 +1356,22 @@ def _yosys_impl(ctx): + # come through arguments/stage_arguments, not extra_arguments .json files. + use_syn = all_arguments.get("SYNTH_USE_SYN") == "1" + ++ # AUTO_MEMORIES: the canonicalize step generates memories.json plus a ++ # directory of .lib/.lef macro views (file names are only known at run ++ # time, hence a directory artifact). Declared as canonicalize outputs ++ # and threaded to every later stage via OrfsInfo.memories / ++ # source_inputs(), matching where the flow's tcl globs them. ++ auto_memories = all_arguments.get("AUTO_MEMORIES") == "1" ++ if auto_memories and use_syn: ++ fail("AUTO_MEMORIES is not supported with SYNTH_USE_SYN in " + ++ str(ctx.label)) ++ memories_outputs = [] ++ if auto_memories: ++ memories_outputs = [ ++ declare_artifact(ctx, "results", "memories.json"), ++ declare_directory_artifact(ctx, "results", "memories"), ++ ] ++ + canon_logs = declare_artifacts(ctx, "logs", ["1_1_yosys_canonicalize.log"]) + + canon_output = declare_artifact(ctx, "results", CANON_OUTPUT) +@@ -1393,7 +1412,7 @@ def _yosys_impl(ctx): + canon_deps, + ], + ), +- outputs = [canon_output] + canon_logs, ++ outputs = [canon_output] + canon_logs + memories_outputs, + tools = yosys_inputs(ctx), + progress_message = "Canonicalizing RTL for %s" % module_top(ctx), + ) +@@ -1513,7 +1532,8 @@ def _yosys_impl(ctx): + config_environment(config), + ), + inputs = depset( +- [canon_output, config] + ctx.files.extra_configs, ++ [canon_output, config] + memories_outputs + ++ ctx.files.extra_configs, + transitive = [ + data_inputs(ctx), + pdk_inputs(ctx), +@@ -1553,7 +1573,8 @@ def _yosys_impl(ctx): + tools = depset(transitive = [flow_inputs(ctx)]), + ) + +- outputs = [canon_output, variables] + synth_outputs.values() ++ outputs = [canon_output, variables] + synth_outputs.values() + \ ++ memories_outputs + + # Write synth's data_arguments to a JSON so downstream stages + # inherit synth-time variables (SDC_FILE, VERILOG_FILES, SYNTH_*) +@@ -1721,6 +1742,7 @@ def _yosys_impl(ctx): + if (dep[OrfsInfo].lib_pre_layout or dep[OrfsInfo].lib) + ], + ), ++ memories = depset(memories_outputs), + arguments = depset([synth_args_json]), + ), + ctx.attr.pdk[PdkInfo], +@@ -2098,6 +2120,7 @@ def _make_impl( + additional_lefs = ctx.attr.src[OrfsInfo].additional_lefs, + additional_libs = ctx.attr.src[OrfsInfo].additional_libs, + additional_libs_pre_layout = ctx.attr.src[OrfsInfo].additional_libs_pre_layout, ++ memories = ctx.attr.src[OrfsInfo].memories, + arguments = depset( + [stage_json], + transitive = [ctx.attr.src[OrfsInfo].arguments] + +-- +2.53.0 + diff --git a/flow/scripts/memories/detect.py b/flow/scripts/memories/detect.py new file mode 100644 index 0000000000..38081597c4 --- /dev/null +++ b/flow/scripts/memories/detect.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Detect memory modules in Verilog sources by port-naming convention. + +Scans Verilog for modules whose entire port list follows the firtool +(CIRCT) memory port convention: every port is named +``_`` — e.g. ``R0_addr``, ``W0_en``, ``RW0_wdata``, +or the subword-split variants ``RW0_wdata_3`` / ``W0_mask_2``. Such +modules are the memory wrappers emitted by Chisel/firtool (and by other +generators that follow the same convention), and are the unit +AUTO_MEMORIES turns into macros. + +Yak-shave deliberately not done in this PR: yosys could be wired up as +the memory detector instead of this ad-hoc Python scanner — its memory +inference pass also finds memories that are embedded inside a larger +module rather than separated out into a module with a name of its own +(the case FPGA tools handle). Then again, perhaps OpenROAD SYN could +become such a memory detector — it currently has no memory inference +pass, which is also why this flow cannot simply lean on yosys inference. +Punt on all of that with a fast, simple Python scanner. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import schema + +_MODULE_HEADER_RE = re.compile(r"^\s*module\s+(\w+)\b", re.MULTILINE) +# Capture every port — including names that follow a continuation comma +# without their own `input`/`output` keyword (firtool emits `R0_clk` that +# way). Each `input|output` group is a region running to the next +# direction keyword or `);`, and the names inside are comma-separated. +_DIR_REGION_RE = re.compile( + r"\b(input|output|inout)\b\s*(\[[^\]]+\])?([^()]*?)" + r"(?=\b(?:input|output|inout)\b|\);)", + re.DOTALL, +) +_BUS_WIDTH_RE = re.compile(r"\[\s*(\d+)\s*:\s*(\d+)\s*\]") +_NAME_RE = re.compile(r"\b([A-Za-z_]\w*)\b") +_PORT_PIN_RE = re.compile(r"^(RW|R|W)(\d+)_([A-Za-z][A-Za-z0-9_]*)$") +_SUBWORD_RE = re.compile(r"^(.*?)(?:_(\d+))?$") + + +def _parse_module_ports(body: str) -> list[tuple[str, str, int]]: + """Return (name, direction, width) for each port of one module body.""" + ports: list[tuple[str, str, int]] = [] + open_paren = body.find("(") + if open_paren < 0: + return ports + match = re.search(r"\)\s*;", body[open_paren:]) + if not match: + return ports + portlist = body[open_paren + 1 : open_paren + match.end()] + for m in _DIR_REGION_RE.finditer(portlist): + direction = m.group(1) + bracket = m.group(2) + rest = m.group(3) + width = 1 + if bracket: + bm = _BUS_WIDTH_RE.search(bracket) + if bm: + width = abs(int(bm.group(1)) - int(bm.group(2))) + 1 + else: + # Parameterized or otherwise non-literal bus width: + # disqualify the module rather than silently modeling + # the port as 1 bit wide (it falls back to flops). + return [] + for chunk in rest.split(","): + nm = _NAME_RE.search(chunk) + if not nm: + continue + name = nm.group(1) + if name in ("input", "output", "inout"): + continue + ports.append((name, direction, width)) + return ports + + +def _classify_tail(kind: str, tail: str) -> str | None: + """Map a pin-name tail to a schema pin function, or None if unknown. + + Subword-split data and mask pins (`wdata_3`, `mask_0`) map to the + same function as their unsplit form; the split only affects how many + pins carry the function. + """ + if tail in ("addr", "en", "wmode", "clk"): + return tail + base = _SUBWORD_RE.match(tail).group(1) + if base in ("mask", "wmask"): + return "mask" + if base == "wdata": + return "data_in" + if base == "rdata": + return "data_out" + if base == "data": + if kind == "R": + return "data_out" + if kind == "W": + return "data_in" + return None # RW ports must use wdata/rdata + return None + + +def classify_module( + name: str, ports: list[tuple[str, str, int]], source_file: str = "" +) -> schema.Memory | None: + """Build a Memory from a module port list, or None if not a memory. + + A module qualifies only when *every* port matches the convention — + a single unrecognized port disqualifies it, so ordinary logic + modules that happen to contain an `R0_...` name are not swept in. + """ + if not ports: + return None + pins: list[schema.Pin] = [] + groups: dict[str, list[schema.Pin]] = {} + for pname, direction, width in ports: + m = _PORT_PIN_RE.match(pname) + if not m: + return None + kind, num, tail = m.group(1), m.group(2), m.group(3) + function = _classify_tail(kind, tail) + if function is None: + return None + pin = schema.Pin( + name=pname, + direction=direction, + width=width, + port_id=kind + num, + function=function, + ) + pins.append(pin) + groups.setdefault(kind + num, []).append(pin) + + n_read = n_write = n_rw = 0 + addr_w = 0 + bits = 0 + mask_lanes = 0 + for port_id, group in groups.items(): + functions = {p.function for p in group} + if "clk" not in functions or "addr" not in functions: + return None + if port_id.startswith("RW"): + if not {"wmode", "data_in", "data_out"} <= functions: + return None + n_rw += 1 + elif port_id.startswith("R"): + if "data_out" not in functions: + return None + n_read += 1 + else: + if "data_in" not in functions: + return None + n_write += 1 + addr_w = max(addr_w, max(p.width for p in group if p.function == "addr")) + for function in ("data_in", "data_out"): + bits = max(bits, sum(p.width for p in group if p.function == function)) + mask_lanes = max( + mask_lanes, sum(p.width for p in group if p.function == "mask") + ) + if addr_w == 0 or bits == 0: + return None + return schema.Memory( + name=name, + rows=1 << addr_w, + bits=bits, + addr_w=addr_w, + read_ports=n_read, + write_ports=n_write, + rw_ports=n_rw, + mask_lanes=mask_lanes, + pins=pins, + behavioral_model={"file": source_file, "module": name}, + ) + + +def scan_text(text: str, source_file: str = "") -> list[schema.Memory]: + """Find every memory-shaped module in one Verilog text.""" + out: list[schema.Memory] = [] + # Strip block and line comments so a comment inside a port list (or + # a commented-out module) cannot confuse the port parser. + text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL) + text = re.sub(r"//[^\n]*", "", text) + headers = list(_MODULE_HEADER_RE.finditer(text)) + for i, m in enumerate(headers): + start = m.start() + end = headers[i + 1].start() if i + 1 < len(headers) else len(text) + memory = classify_module( + m.group(1), _parse_module_ports(text[start:end]), source_file + ) + if memory is not None: + out.append(memory) + return out + + +def scan_files(paths: list[Path]) -> list[schema.Memory]: + """Scan Verilog files; later definitions of a name win.""" + found: dict[str, schema.Memory] = {} + for path in paths: + for memory in scan_text(path.read_text(errors="replace"), str(path)): + found[memory.name] = memory + return list(found.values()) diff --git a/flow/scripts/memories/detect_test.py b/flow/scripts/memories/detect_test.py new file mode 100644 index 0000000000..6345c718f4 --- /dev/null +++ b/flow/scripts/memories/detect_test.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import detect + +# firtool-style memory with whole-bus data and mask pins, and a +# continuation-comma port (`W0_clk` carries no direction keyword of its +# own — it continues the preceding `input` group). +BUS_STYLE = """\ +module mem_128x32( + input [6:0] R0_addr, + input R0_en, + input R0_clk, + output [31:0] R0_data, + input [6:0] W0_addr, + input W0_en, + W0_clk, + input [31:0] W0_data, + input [3:0] W0_mask +); +endmodule +""" + +# Subword-split style: data and mask split into per-lane pins. +SUBWORD_STYLE = """\ +module mem_1024x32( + input [9:0] R0_addr, + input R0_en, + input R0_clk, + output [7:0] R0_data_0, + output [7:0] R0_data_1, + output [7:0] R0_data_2, + output [7:0] R0_data_3, + input [9:0] W0_addr, + input W0_en, + input W0_clk, + input [7:0] W0_data_0, + input [7:0] W0_data_1, + input [7:0] W0_data_2, + input [7:0] W0_data_3, + input W0_mask_0, + input W0_mask_1, + input W0_mask_2, + input W0_mask_3 +); +endmodule +""" + +RW_STYLE = """\ +module cache_tags( + input [1:0] RW0_addr, + input RW0_en, + input RW0_clk, + input RW0_wmode, + input [24:0] RW0_wdata_0, + output [24:0] RW0_rdata_0 +); +endmodule +""" + +# A module with one convention-shaped port among ordinary ports must +# not classify as a memory. +NOT_A_MEMORY = """\ +module controller( + input clock, + input reset, + input [6:0] R0_addr, + output done +); +endmodule +""" + + +class DetectTest(unittest.TestCase): + def test_bus_style(self): + mems = detect.scan_text(BUS_STYLE) + self.assertEqual(len(mems), 1) + m = mems[0] + self.assertEqual((m.name, m.rows, m.bits, m.addr_w), ("mem_128x32", 128, 32, 7)) + self.assertEqual( + (m.read_ports, m.write_ports, m.rw_ports, m.mask_lanes), (1, 1, 0, 4) + ) + functions = {p.name: p.function for p in m.pins} + self.assertEqual(functions["R0_data"], "data_out") + self.assertEqual(functions["W0_data"], "data_in") + self.assertEqual(functions["W0_mask"], "mask") + # The continuation-comma port is captured with its group's + # direction. + clk = next(p for p in m.pins if p.name == "W0_clk") + self.assertEqual(clk.direction, "input") + + def test_subword_style(self): + mems = detect.scan_text(SUBWORD_STYLE) + self.assertEqual(len(mems), 1) + m = mems[0] + self.assertEqual((m.rows, m.bits, m.mask_lanes), (1024, 32, 4)) + self.assertEqual((m.read_ports, m.write_ports), (1, 1)) + functions = {p.name: p.function for p in m.pins} + self.assertEqual(functions["R0_data_2"], "data_out") + self.assertEqual(functions["W0_data_2"], "data_in") + self.assertEqual(functions["W0_mask_3"], "mask") + + def test_rw_style(self): + mems = detect.scan_text(RW_STYLE) + self.assertEqual(len(mems), 1) + m = mems[0] + self.assertEqual((m.rows, m.bits, m.rw_ports), (4, 25, 1)) + functions = {p.name: p.function for p in m.pins} + self.assertEqual(functions["RW0_wmode"], "wmode") + self.assertEqual(functions["RW0_wdata_0"], "data_in") + self.assertEqual(functions["RW0_rdata_0"], "data_out") + + def test_non_memory_rejected(self): + self.assertEqual(detect.scan_text(NOT_A_MEMORY), []) + + def test_multiple_modules_in_one_text(self): + text = BUS_STYLE + NOT_A_MEMORY + RW_STYLE + names = [m.name for m in detect.scan_text(text)] + self.assertEqual(names, ["mem_128x32", "cache_tags"]) + + def test_behavioral_model_recorded(self): + mems = detect.scan_text(BUS_STYLE, source_file="rtl/mems.v") + self.assertEqual( + mems[0].behavioral_model, + { + "file": "rtl/mems.v", + "module": "mem_128x32", + }, + ) + + def test_rw_port_with_plain_data_rejected(self): + text = RW_STYLE.replace("RW0_wdata_0", "RW0_data_0") + self.assertEqual(detect.scan_text(text), []) + + def test_port_group_without_clk_rejected(self): + text = BUS_STYLE.replace("W0_clk", "W0_clock") + self.assertEqual(detect.scan_text(text), []) + + def test_comments_in_port_list_ignored(self): + text = BUS_STYLE.replace( + "output [31:0] R0_data,", + "output [31:0] R0_data, // output data for read port\n" + " /* input for clock is per port */", + ) + mems = detect.scan_text(text) + self.assertEqual(len(mems), 1) + self.assertEqual(mems[0].bits, 32) + + def test_commented_out_module_ignored(self): + text = "/*\n" + BUS_STYLE + "*/\n" + RW_STYLE + names = [m.name for m in detect.scan_text(text)] + self.assertEqual(names, ["cache_tags"]) + + def test_parameterized_width_disqualifies(self): + text = BUS_STYLE.replace("[31:0]", "[WIDTH-1:0]") + self.assertEqual(detect.scan_text(text), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/memories/gen_memories.py b/flow/scripts/memories/gen_memories.py new file mode 100644 index 0000000000..a293793341 --- /dev/null +++ b/flow/scripts/memories/gen_memories.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""AUTO_MEMORIES driver: detect memories, judge them, emit macro views. + +Run pre-synthesis (before canonicalization). Scans the design's Verilog +for memory-shaped modules, merges user-supplied `.memories` files +(ADDITIONAL_MEMORIES), applies the idiomatic-macro gate, then writes: + + full inventory, converted or not (memories.json) + /.lib Liberty view per converted memory + /_pre_layout.lib ideal-clock variant for pre-CTS consumers + /.lef abstract LEF per converted memory + /blackboxes.txt converted module names, one per line — + what synthesis blackboxes + +Everything downstream consumes these files; nothing else is passed +between the generator and the flow. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import subprocess +import os + +import detect # noqa: E402 +import idiomatic # noqa: E402 +import schema # noqa: E402 + + +def find_fakeram_run() -> str | None: + fakeram_run = os.environ.get("FAKERAM_RUN_PY") + if fakeram_run and os.path.isfile(fakeram_run): + return fakeram_run + runfiles_dir = os.environ.get("RUNFILES_DIR") + if runfiles_dir: + for p in Path(runfiles_dir).rglob("run.py"): + if "fakeram" in p.parts[-2]: + return str(p) + return None + + +def run( + verilog: list[Path], + memories_files: list[Path], + platform: str, + out_dir: Path, + json_path: Path, +) -> int: + if platform != "asap7": + sys.stderr.write(f"gen_memories: unsupported platform {platform}\n") + return 1 + + found = detect.scan_files(verilog) + idiomatic.apply(found) + + overrides: list[schema.Memory] = [] + for path in memories_files: + overrides.extend(schema.load(path)) + memories = schema.merge(found, overrides) + + out_dir.mkdir(parents=True, exist_ok=True) + json_path.parent.mkdir(parents=True, exist_ok=True) + schema.dump(memories, json_path, platform) + + converted = sorted((m for m in memories if m.idiomatic), key=lambda m: m.name) + for mem in converted: + schema.validate_emittable(mem) + + fakeram_run = find_fakeram_run() + if not fakeram_run: + sys.stderr.write( + "gen_memories: FAKERAM_RUN_PY not set and FakeRAM run.py not found.\n" + ) + return 1 + + subprocess.check_call( + [ + sys.executable, + fakeram_run, + "--orfs_asap7_backend", + "--output_dir", + str(out_dir), + str(json_path), + ] + ) + + for mem in sorted(memories, key=lambda m: m.name): + verdict = "macro" if mem.idiomatic else "flops" + sys.stderr.write( + f"gen_memories: {mem.name} {mem.rows}x{mem.bits} " + f"R={mem.read_ports} W={mem.write_ports} RW={mem.rw_ports} " + f"mask_lanes={mem.mask_lanes} -> {verdict} ({mem.reason})\n" + ) + if not memories: + sys.stderr.write("gen_memories: no memory-shaped modules found\n") + return 0 + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument( + "--verilog", + action="append", + default=[], + type=Path, + help="Verilog source file to scan (repeatable).", + ) + p.add_argument( + "--memories", + action="append", + default=[], + type=Path, + help="User-supplied .memories file merged onto the " + "detected set (repeatable).", + ) + p.add_argument("--platform", required=True) + p.add_argument( + "--out-dir", + required=True, + type=Path, + help="Directory for generated .lib/.lef/blackboxes.txt.", + ) + p.add_argument( + "--json", + required=True, + type=Path, + help="Path of the memories.json inventory to write.", + ) + args = p.parse_args(argv) + return run(args.verilog, args.memories, args.platform, args.out_dir, args.json) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/flow/scripts/memories/gen_memories_test.py b/flow/scripts/memories/gen_memories_test.py new file mode 100644 index 0000000000..c353e5262d --- /dev/null +++ b/flow/scripts/memories/gen_memories_test.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import os + +import gen_memories +from detect_test import BUS_STYLE, NOT_A_MEMORY, RW_STYLE + +# Setup FAKERAM_RUN_PY using runfiles if available, otherwise assume a relative path +if "TEST_WORKSPACE" in os.environ: + # Bazel test execution + runfiles_dir = Path(os.environ.get("RUNFILES_DIR", ".")) + candidates = list(runfiles_dir.glob("**/fakeram*/run.py")) + list( + runfiles_dir.glob("**/run.py") + ) + fakeram_run = candidates[0] if candidates else runfiles_dir / "fakeram" / "run.py" +else: + fakeram_run = ( + Path(__file__).resolve().parent.parent.parent.parent + / "tools" + / "FakeRAM2.0" + / "run.py" + ) + +os.environ["FAKERAM_RUN_PY"] = str(fakeram_run) + +FORCE_TAGS = """\ +{ + "version": 1, + "memories": [ + { + "name": "cache_tags", + "idiomatic": true, + "reason": "forced: RTL provides no behavioral fallback" + } + ] +} +""" + + +class GenMemoriesTest(unittest.TestCase): + def run_generator(self, memories_files=(), platform="asap7"): + d = Path(self.tmp.name) + rtl = d / "design.v" + rtl.write_text(BUS_STYLE + NOT_A_MEMORY + RW_STYLE) + argv = [ + "--platform", + platform, + "--out-dir", + str(d / "memories"), + "--json", + str(d / "memories.json"), + "--verilog", + str(rtl), + ] + for f in memories_files: + argv += ["--memories", str(f)] + return gen_memories.main(argv), d + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def test_flow_contract(self): + # Everything synthesis and later stages consume must be on disk: + # memories.json, per-macro .lib/_pre_layout.lib/.lef, and the + # blackbox name list — for converted memories only. + code, d = self.run_generator() + self.assertEqual(code, 0) + + doc = json.loads((d / "memories.json").read_text()) + by_name = {m["name"]: m for m in doc["memories"]} + self.assertEqual(set(by_name), {"mem_128x32", "cache_tags"}) + self.assertTrue(by_name["mem_128x32"]["idiomatic"]) + self.assertFalse(by_name["cache_tags"]["idiomatic"]) + self.assertIn("depth 4", by_name["cache_tags"]["reason"]) + + mems_dir = d / "memories" + self.assertEqual( + sorted(p.name for p in mems_dir.iterdir()), + [ + "blackboxes.txt", + "mem_128x32.lef", + "mem_128x32.lib", + "mem_128x32_pre_layout.lib", + ], + ) + self.assertEqual((mems_dir / "blackboxes.txt").read_text(), "mem_128x32\n") + + def test_additional_memories_forces_conversion(self): + force = Path(self.tmp.name) / "force.memories" + force.write_text(FORCE_TAGS) + code, d = self.run_generator(memories_files=[force]) + self.assertEqual(code, 0) + blackboxes = (d / "memories" / "blackboxes.txt").read_text().split() + self.assertEqual(sorted(blackboxes), ["cache_tags", "mem_128x32"]) + self.assertTrue((d / "memories" / "cache_tags.lib").exists()) + self.assertTrue((d / "memories" / "cache_tags.lef").exists()) + doc = json.loads((d / "memories.json").read_text()) + tags = next(m for m in doc["memories"] if m["name"] == "cache_tags") + self.assertTrue(tags["idiomatic"]) + self.assertIn("forced", tags["reason"]) + + def test_unsupported_platform_fails_clearly(self): + code, _d = self.run_generator(platform="nangate45") + self.assertEqual(code, 1) + + def test_missing_verilog_fails_cleanly(self): + with self.assertRaises(FileNotFoundError): + gen_memories.main( + [ + "--platform", + "asap7", + "--out-dir", + str(Path(self.tmp.name) / "memories"), + "--json", + str(Path(self.tmp.name) / "memories.json"), + "--verilog", + str(Path(self.tmp.name) / "does-not-exist.v"), + ] + ) + + def test_bad_memories_file_fails(self): + bad = Path(self.tmp.name) / "bad.memories" + bad.write_text("{not json") + with self.assertRaises(json.JSONDecodeError): + self.run_generator(memories_files=[bad]) + + def test_no_memories_still_writes_contract_files(self): + d = Path(self.tmp.name) + rtl = d / "logic.v" + rtl.write_text(NOT_A_MEMORY) + code = gen_memories.main( + [ + "--platform", + "asap7", + "--out-dir", + str(d / "memories"), + "--json", + str(d / "memories.json"), + "--verilog", + str(rtl), + ] + ) + self.assertEqual(code, 0) + self.assertEqual(json.loads((d / "memories.json").read_text())["memories"], []) + self.assertEqual((d / "memories" / "blackboxes.txt").read_text(), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/memories/idiomatic.py b/flow/scripts/memories/idiomatic.py new file mode 100644 index 0000000000..e32221eaf4 --- /dev/null +++ b/flow/scripts/memories/idiomatic.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Decide which detected memories are idiomatic as ASAP7 SRAM macros. + +A memory below these floors is cheaper as flip-flops than as an SRAM +macro (the macro pays a fixed control/decode/sense-amp floor), and a +memory with too many ports has no single-macro implementation in +ordinary SRAM compilers. Rejected memories keep `idiomatic: false` plus +a reason in memories.json and synthesize as flops. + +The thresholds are deliberately simple, first-pass policy. Banking and +multi-port decomposition (splitting a too-wide/too-ported memory across +several macros) are not handled — a future extension. A user who wants +a rejected memory converted anyway overrides it via a `.memories` file +listed in ADDITIONAL_MEMORIES. +""" + +from __future__ import annotations + +import schema + +MIN_ROWS = 16 +MIN_BITS_TOTAL = 256 +MAX_TOTAL_PORTS = 4 + + +def judge(mem: schema.Memory) -> tuple[bool, str]: + """Return (idiomatic, reason).""" + if mem.bits < 1: + return False, "no data pins" + if mem.rows < MIN_ROWS: + return False, f"depth {mem.rows} below macro floor {MIN_ROWS}" + total_bits = mem.rows * mem.bits + if total_bits < MIN_BITS_TOTAL: + return ( + False, + f"capacity {total_bits} bits below macro floor " f"{MIN_BITS_TOTAL}", + ) + if mem.total_ports() > MAX_TOTAL_PORTS: + return ( + False, + f"{mem.total_ports()} ports exceeds single-macro " + f"limit {MAX_TOTAL_PORTS}", + ) + return True, "meets ASAP7 macro floors" + + +def apply(memories: list[schema.Memory]) -> None: + for mem in memories: + mem.idiomatic, mem.reason = judge(mem) diff --git a/flow/scripts/memories/idiomatic_test.py b/flow/scripts/memories/idiomatic_test.py new file mode 100644 index 0000000000..d26fbfc040 --- /dev/null +++ b/flow/scripts/memories/idiomatic_test.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import idiomatic +import schema + + +def mem(rows, bits, read_ports=1, write_ports=1, rw_ports=0): + return schema.Memory( + name="m", + rows=rows, + bits=bits, + read_ports=read_ports, + write_ports=write_ports, + rw_ports=rw_ports, + ) + + +class IdiomaticTest(unittest.TestCase): + def test_accepts_macro_sized_memory(self): + ok, reason = idiomatic.judge(mem(64, 32)) + self.assertTrue(ok, reason) + + def test_rejects_shallow_memory(self): + ok, reason = idiomatic.judge(mem(4, 25)) + self.assertFalse(ok) + self.assertIn("depth 4", reason) + + def test_rejects_small_capacity(self): + # 16 rows x 8 bits = 128 bits: deep enough, too small overall. + ok, reason = idiomatic.judge(mem(16, 8)) + self.assertFalse(ok) + self.assertIn("capacity 128", reason) + + def test_rejects_too_many_ports(self): + ok, reason = idiomatic.judge(mem(256, 32, read_ports=4, write_ports=2)) + self.assertFalse(ok) + self.assertIn("ports", reason) + + def test_apply_sets_fields(self): + memories = [mem(64, 32), mem(4, 25)] + idiomatic.apply(memories) + self.assertTrue(memories[0].idiomatic) + self.assertFalse(memories[1].idiomatic) + self.assertTrue(memories[1].reason) + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/memories/schema.py b/flow/scripts/memories/schema.py new file mode 100644 index 0000000000..060cf277c8 --- /dev/null +++ b/flow/scripts/memories/schema.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""The `.memories` file format: a JSON inventory of memory macros. + +One `.memories` file (and the flow-generated `memories.json`) describes +memories at the module boundary: geometry, the full pin list with each +pin's function, the behavioral model the RTL provides, and whether the +memory is converted to a macro (`idiomatic`). + +The file-based handoff is deliberate: everything downstream — synthesis +blackboxing, liberty/LEF consumption in later stages, build systems that +declare flow artifacts as transitive dependencies — keys off these files +rather than off in-process state. +""" + +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass, field +from pathlib import Path + +SCHEMA_VERSION = 1 + +PIN_FUNCTIONS = ("addr", "en", "wmode", "mask", "data_in", "data_out", "clk") +DIRECTIONS = ("input", "output") + + +class SchemaError(ValueError): + pass + + +@dataclass +class Pin: + name: str + direction: str # "input" / "output" + width: int + port_id: str # "R0", "W1", "RW0", ... + function: str # one of PIN_FUNCTIONS + + +@dataclass +class Memory: + name: str + rows: int = 0 + bits: int = 0 + addr_w: int = 0 + read_ports: int = 0 + write_ports: int = 0 + rw_ports: int = 0 + # Total width of the per-port write mask, 0 if unmasked. Subword-split + # mask pins (`W0_mask_0..3`) contribute one lane each. + mask_lanes: int = 0 + pins: list[Pin] = field(default_factory=list) + # The module whose RTL body simulates this memory: {"file", "module"}. + behavioral_model: dict | None = None + # True when the memory is converted to a macro (.lib/.lef emitted and + # the module blackboxed); False leaves it to synthesize as flops. + idiomatic: bool = False + reason: str = "" + + def total_ports(self) -> int: + return self.read_ports + self.write_ports + self.rw_ports + + def to_dict(self) -> dict: + return asdict(self) + + +def _pin_from_dict(d: dict) -> Pin: + if not isinstance(d, dict): + raise SchemaError("expected a dictionary for pin record") + try: + pin = Pin( + name=d["name"], + direction=d["direction"], + width=int(d["width"]), + port_id=d["port_id"], + function=d["function"], + ) + except KeyError as e: + raise SchemaError(f"pin record missing field {e}") from e + if pin.direction not in DIRECTIONS: + raise SchemaError(f"pin {pin.name}: bad direction '{pin.direction}'") + if pin.function not in PIN_FUNCTIONS: + raise SchemaError( + f"pin {pin.name}: unknown function " + f"'{pin.function}' (expected one of " + f"{', '.join(PIN_FUNCTIONS)})" + ) + if pin.width < 1: + raise SchemaError(f"pin {pin.name}: width must be >= 1") + if not pin.port_id: + raise SchemaError(f"pin {pin.name}: empty port_id") + return pin + + +def memory_from_dict(d: dict) -> Memory: + if not isinstance(d, dict): + raise SchemaError("expected a dictionary for memory record") + if "name" not in d: + raise SchemaError("memory record missing 'name'") + mem = Memory(name=d["name"]) + for key in ( + "rows", + "bits", + "addr_w", + "read_ports", + "write_ports", + "rw_ports", + "mask_lanes", + ): + if key in d: + setattr(mem, key, int(d[key])) + if "pins" in d: + mem.pins = [_pin_from_dict(p) for p in d["pins"]] + if "behavioral_model" in d: + mem.behavioral_model = d["behavioral_model"] + if "idiomatic" in d: + mem.idiomatic = bool(d["idiomatic"]) + if "reason" in d: + mem.reason = str(d["reason"]) + return mem + + +def load(path: Path) -> list[Memory]: + """Load a .memories / memories.json file. + + We expect the JSON file to be valid and readable. If it is not, + uncaught exceptions (e.g. FileNotFoundError, JSONDecodeError) provide + full detailed stack traces and debug information. + """ + doc = json.loads(path.read_text()) + if not isinstance(doc, dict) or "memories" not in doc: + raise SchemaError(f"{path}: expected an object with a 'memories' list") + version = doc.get("version", SCHEMA_VERSION) + if version != SCHEMA_VERSION: + raise SchemaError(f"{path}: unsupported schema version {version}") + return [memory_from_dict(m) for m in doc["memories"]] + + +def dump(memories: list[Memory], path: Path, platform: str) -> None: + doc = { + "version": SCHEMA_VERSION, + "platform": platform, + "memories": [m.to_dict() for m in sorted(memories, key=lambda m: m.name)], + } + path.write_text(json.dumps(doc, indent=2) + "\n") + + +def merge(detected: list[Memory], overrides: list[Memory]) -> list[Memory]: + """Merge user-supplied entries onto the detected set. + + An override naming a detected memory replaces only the fields it + carries (geometry and pins are kept from detection unless the + override provides its own). An override naming an unknown memory is + taken whole — it must then carry pins and geometry itself to be + emittable. + """ + by_name = {m.name: m for m in detected} + for o in overrides: + base = by_name.get(o.name) + if base is None: + by_name[o.name] = o + continue + if o.pins: + base.pins = o.pins + for key in ( + "rows", + "bits", + "addr_w", + "read_ports", + "write_ports", + "rw_ports", + "mask_lanes", + ): + value = getattr(o, key) + if value: + setattr(base, key, value) + if o.behavioral_model is not None: + base.behavioral_model = o.behavioral_model + if o.idiomatic: + base.idiomatic = True + if o.reason: + base.reason = o.reason + return list(by_name.values()) + + +def validate_emittable(mem: Memory) -> None: + """Raise SchemaError unless `mem` carries enough to emit .lib/.lef.""" + if not mem.pins: + raise SchemaError(f"memory {mem.name}: no pins") + if mem.rows < 1 or mem.bits < 1: + raise SchemaError( + f"memory {mem.name}: rows ({mem.rows}) and bits ({mem.bits}) " + f"must be >= 1" + ) + port_ids = {p.port_id for p in mem.pins} + for port_id in port_ids: + functions = {p.function for p in mem.pins if p.port_id == port_id} + if "clk" not in functions: + raise SchemaError(f"memory {mem.name}: port {port_id} has no clk pin") + if "addr" not in functions: + raise SchemaError(f"memory {mem.name}: port {port_id} has no addr pin") + if not functions & {"data_in", "data_out"}: + raise SchemaError(f"memory {mem.name}: port {port_id} has no data pin") diff --git a/flow/scripts/memories/schema_test.py b/flow/scripts/memories/schema_test.py new file mode 100644 index 0000000000..31775f1b01 --- /dev/null +++ b/flow/scripts/memories/schema_test.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import schema + + +def sample_memory(name="mem_64x32") -> schema.Memory: + return schema.Memory( + name=name, + rows=64, + bits=32, + addr_w=6, + read_ports=1, + write_ports=1, + pins=[ + schema.Pin("R0_addr", "input", 6, "R0", "addr"), + schema.Pin("R0_en", "input", 1, "R0", "en"), + schema.Pin("R0_clk", "input", 1, "R0", "clk"), + schema.Pin("R0_data", "output", 32, "R0", "data_out"), + schema.Pin("W0_addr", "input", 6, "W0", "addr"), + schema.Pin("W0_en", "input", 1, "W0", "en"), + schema.Pin("W0_clk", "input", 1, "W0", "clk"), + schema.Pin("W0_data", "input", 32, "W0", "data_in"), + ], + behavioral_model={"file": "mems.v", "module": name}, + idiomatic=True, + reason="meets ASAP7 macro floors", + ) + + +class SchemaTest(unittest.TestCase): + def test_round_trip(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "memories.json" + schema.dump([sample_memory()], path, platform="asap7") + loaded = schema.load(path) + self.assertEqual(len(loaded), 1) + self.assertEqual(loaded[0].to_dict(), sample_memory().to_dict()) + + def test_dump_is_sorted_and_versioned(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "memories.json" + schema.dump( + [sample_memory("zz"), sample_memory("aa")], path, platform="asap7" + ) + doc = json.loads(path.read_text()) + self.assertEqual(doc["version"], schema.SCHEMA_VERSION) + self.assertEqual(doc["platform"], "asap7") + self.assertEqual([m["name"] for m in doc["memories"]], ["aa", "zz"]) + + def test_merge_partial_override(self): + detected = [sample_memory()] + detected[0].idiomatic = False + detected[0].reason = "depth 4 below macro floor 16" + override = schema.Memory( + name="mem_64x32", idiomatic=True, reason="forced: no behavioral fallback" + ) + merged = schema.merge(detected, [override]) + self.assertEqual(len(merged), 1) + m = merged[0] + self.assertTrue(m.idiomatic) + self.assertEqual(m.reason, "forced: no behavioral fallback") + # Geometry and pins kept from detection. + self.assertEqual((m.rows, m.bits), (64, 32)) + self.assertEqual(len(m.pins), 8) + + def test_merge_new_entry_taken_whole(self): + extra = sample_memory("mem_extra") + merged = schema.merge([sample_memory()], [extra]) + self.assertEqual(sorted(m.name for m in merged), ["mem_64x32", "mem_extra"]) + + def test_load_rejects_bad_documents(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "bad.memories" + path.write_text("[]") + with self.assertRaises(schema.SchemaError): + schema.load(path) + path.write_text('{"version": 99, "memories": []}') + with self.assertRaises(schema.SchemaError): + schema.load(path) + path.write_text('{"memories": [{"rows": 4}]}') + with self.assertRaises(schema.SchemaError): + schema.load(path) + path.write_text( + '{"memories": [{"name": "m", "pins": ' + '[{"name": "p", "direction": "input", "width": 1, ' + '"port_id": "R0", "function": "banana"}]}]}' + ) + with self.assertRaises(schema.SchemaError): + schema.load(path) + + def test_validate_emittable(self): + good = sample_memory() + schema.validate_emittable(good) # no raise + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(schema.Memory(name="empty")) + clkless = sample_memory() + clkless.pins = [p for p in clkless.pins if p.function != "clk"] + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(clkless) + addrless = sample_memory() + addrless.pins = [p for p in addrless.pins if p.function != "addr"] + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(addrless) + dataless = sample_memory() + dataless.pins = [ + p for p in dataless.pins if p.function not in ("data_in", "data_out") + ] + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(dataless) + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/read_liberty.tcl b/flow/scripts/read_liberty.tcl index 14f8f06e7a..1c013611dd 100644 --- a/flow/scripts/read_liberty.tcl +++ b/flow/scripts/read_liberty.tcl @@ -16,3 +16,23 @@ if { [env_var_exists_and_non_empty CORNERS] } { log_cmd read_liberty $libFile } } + +# AUTO_MEMORIES: liberty views generated pre-synthesis by +# scripts/memories/gen_memories.py. The file names are only known at +# run time, so they are globbed here rather than threaded through +# LIB_FILES. The _pre_layout variants (ideal clock) are for pre-CTS +# consumers that select lib files themselves. +if { [env_var_equals AUTO_MEMORIES 1] } { + foreach libFile [glob -nocomplain $::env(RESULTS_DIR)/memories/*.lib] { + if { [string match *_pre_layout.lib $libFile] } { + continue + } + if { [env_var_exists_and_non_empty CORNERS] } { + foreach corner $::env(CORNERS) { + log_cmd read_liberty -corner $corner $libFile + } + } else { + log_cmd read_liberty $libFile + } + } +} diff --git a/flow/scripts/synth_preamble.tcl b/flow/scripts/synth_preamble.tcl index 18e27b4aa5..0467b61964 100644 --- a/flow/scripts/synth_preamble.tcl +++ b/flow/scripts/synth_preamble.tcl @@ -29,6 +29,25 @@ proc read_checkpoint { file } { } } +# AUTO_MEMORIES: memory modules whose generated liberty view replaces +# their behavioral body during synthesis. The list is produced by +# scripts/memories/gen_memories.py before canonicalization; see +# docs/user/AutoMemories.md. +proc auto_memories_blackboxes { } { + if { ![env_var_equals AUTO_MEMORIES 1] } { + return {} + } + set f "$::env(RESULTS_DIR)/memories/blackboxes.txt" + if { ![file exists $f] } { + error "AUTO_MEMORIES=1 but $f is missing;\ + the do-auto-memories step must run before synthesis" + } + set fh [open $f r] + set content [string map {\r ""} [read $fh]] + close $fh + return [regexp -all -inline {\S+} $content] +} + proc read_design_sources { } { # We are reading Verilog sources source $::env(SCRIPTS_DIR)/synth_stdcells.tcl @@ -80,6 +99,12 @@ proc read_design_sources { } { } } + # Blackbox AUTO_MEMORIES-detected memory modules so their generated + # liberty view wins over their behavioral bodies. + foreach m [auto_memories_blackboxes] { + lappend slang_args --blackboxed-module "$m" + } + # Add user arguments lappend slang_args {*}$::env(SYNTH_SLANG_ARGS) @@ -105,6 +130,9 @@ proc read_design_sources { } { if { [env_var_exists_and_non_empty SYNTH_BLACKBOXES] } { error "Non-empty SYNTH_BLACKBOXES unsupported with HDL frontend \"verific\"" } + if { [llength [auto_memories_blackboxes]] > 0 } { + error "AUTO_MEMORIES unsupported with HDL frontend \"verific\"" + } } elseif { ![env_var_exists_and_non_empty SYNTH_HDL_FRONTEND] } { verilog_defaults -push if { [env_var_exists_and_non_empty VERILOG_DEFINES] } { @@ -124,6 +152,18 @@ proc read_design_sources { } { chparam -set $key $value $::env(DESIGN_NAME) } + # AUTO_MEMORIES blackboxing runs before `hierarchy -check`: a + # memory wrapper may instantiate modules the sources never define + # (the behavioral body is being discarded anyway), so the check is + # only meaningful after the bodies are gone. + set auto_blackboxes [auto_memories_blackboxes] + if { [llength $auto_blackboxes] > 0 } { + hierarchy -top $::env(DESIGN_NAME) + foreach m $auto_blackboxes { + blackbox $m + } + hierarchy -check -top $::env(DESIGN_NAME) + } if { [env_var_exists_and_non_empty SYNTH_BLACKBOXES] } { hierarchy -check -top $::env(DESIGN_NAME) foreach m $::env(SYNTH_BLACKBOXES) { diff --git a/flow/scripts/variables.json b/flow/scripts/variables.json index d0d8d0dbbf..5ce07d7e6e 100644 --- a/flow/scripts/variables.json +++ b/flow/scripts/variables.json @@ -51,6 +51,12 @@ "ADDITIONAL_LIBS": { "description": "Hardened macro library files listed here. The library information is immutable and used throughout all stages. Not stored in the .odb file.\n" }, + "ADDITIONAL_MEMORIES": { + "description": "Experimental. Space-separated list of user-supplied `.memories` files (the memories.json JSON schema) merged onto the set AUTO_MEMORIES detects \u2014 to force-convert a memory the idiomatic gate rejects, or to describe one the scanner cannot find. See docs/user/AutoMemories.md.\n", + "stages": [ + "synth" + ] + }, "ADDITIONAL_SITES": { "description": "Passed as -additional_sites to initialize_floorplan.\n", "stages": [ @@ -64,6 +70,10 @@ "All stages" ] }, + "AUTO_MEMORIES": { + "default": 0, + "description": "Experimental. When set to 1, memory-shaped modules in the RTL (firtool/CIRCT `R*/W*/RW*_` port convention, module boundary only) are detected pre-synthesis, inventoried in `$(RESULTS_DIR)/memories.json`, and \u2014 when idiomatic as an SRAM macro \u2014 given generated .lib/.lef views under `$(RESULTS_DIR)/memories/`. Synthesis blackboxes those modules and all later stages read the generated views, so an existing design gets macro-based results without a memory compiler. Supported for the asap7 platform only. See docs/user/AutoMemories.md.\n" + }, "BALANCE_ROWS": { "default": 0, "description": "Balance rows during placement.\n", @@ -433,14 +443,6 @@ "place" ] }, - "GRT_SEED": { - "description": "Specifies a random seed for global routing. Useful for perturbation studies.\n", - "stages": [ - "grt" - ], - "tunable": 1, - "type": "int" - }, "GUI_TIMING": { "default": 1, "description": "Load timing information when opening GUI. For large designs, this can be quite time consuming. Useful to disable when investigating non-timing aspects like floorplan, placement, routing, etc.\n" diff --git a/flow/scripts/variables.yaml b/flow/scripts/variables.yaml index ae24b8359c..27b1c546e1 100644 --- a/flow/scripts/variables.yaml +++ b/flow/scripts/variables.yaml @@ -189,6 +189,27 @@ SYNTH_USE_SYN: stages: - synth default: 0 +AUTO_MEMORIES: + description: > + Experimental. When set to 1, memory-shaped modules in the RTL + (firtool/CIRCT `R*/W*/RW*_` port convention, module boundary only) + are detected pre-synthesis, inventoried in + `$(RESULTS_DIR)/memories.json`, and — when idiomatic as an SRAM + macro — given generated .lib/.lef views under + `$(RESULTS_DIR)/memories/`. Synthesis blackboxes those modules and + all later stages read the generated views, so an existing design + gets macro-based results without a memory compiler. Supported for + the asap7 platform only. See docs/user/AutoMemories.md. + default: 0 +ADDITIONAL_MEMORIES: + description: > + Experimental. Space-separated list of user-supplied `.memories` + files (the memories.json JSON schema) merged onto the set + AUTO_MEMORIES detects — to force-convert a memory the idiomatic + gate rejects, or to describe one the scanner cannot find. See + docs/user/AutoMemories.md. + stages: + - synth SYNTH_MEMORY_MAX_BITS: description: > Maximum number of bits for memory synthesis. @@ -1610,10 +1631,3 @@ OPT_POST_GRT_WNS: VT swap and wire rerouting only to minimize placement and routing disturbance stages: - grt -GRT_SEED: - description: > - Specifies a random seed for global routing. Useful for perturbation studies. - stages: - - grt - tunable: 1 - type: int diff --git a/patches/fakeram/0001-Add-ORFS-ASAP7-backend.patch b/patches/fakeram/0001-Add-ORFS-ASAP7-backend.patch new file mode 100644 index 0000000000..d2ae3cd83a --- /dev/null +++ b/patches/fakeram/0001-Add-ORFS-ASAP7-backend.patch @@ -0,0 +1,169 @@ +diff --git a/BUILD.bazel b/BUILD.bazel +new file mode 100644 +index 0000000..16e9be4 +--- /dev/null ++++ b/BUILD.bazel +@@ -0,0 +1,5 @@ ++filegroup( ++ name = "all_files", ++ srcs = glob(["**/*"]), ++ visibility = ["//visibility:public"], ++) +diff --git a/MODULE.bazel b/MODULE.bazel +new file mode 100644 +index 0000000..f12bf1f +--- /dev/null ++++ b/MODULE.bazel +@@ -0,0 +1,4 @@ ++module( ++ name = "fakeram", ++ version = "2.0.0", ++) +diff --git a/orfs_asap7/__init__.py b/orfs_asap7/__init__.py +new file mode 100644 +index 0000000..edcf578 +--- /dev/null ++++ b/orfs_asap7/__init__.py +@@ -0,0 +1 @@ ++# ORFS ASAP7 package +diff --git a/orfs_asap7/generate.py b/orfs_asap7/generate.py +new file mode 100644 +index 0000000..58fef20 +--- /dev/null ++++ b/orfs_asap7/generate.py +@@ -0,0 +1,83 @@ ++import json ++import sys ++from pathlib import Path ++ ++from utils.class_process import Process ++from utils.memory_config import MemoryConfig ++from utils.memory_factory import MemoryFactory ++from utils.timing_data import TimingData ++from utils.ram_liberty_exporter import RAMLibertyExporter ++from utils.lef_exporter import LefExporter ++ ++ASAP7_PROCESS_CONFIG = { ++ "tech_nm": 7, ++ "voltage": 0.7, ++ "metal_prefix": "M", ++ "metal_layer": "M4", ++ "pin_width_nm": 24, ++ "pin_pitch_nm": 48, ++ "metal_track_pitch_nm": 48, ++ "manufacturing_grid_nm": 1, ++ "contacted_poly_pitch_nm": 54, ++ "fin_pitch_nm": 27, ++ "column_mux_factor": 1, ++ "snap_width_nm": 190, ++ "snap_height_nm": 1400, ++} ++ ++ASAP7_TIMING_CONFIG = { ++ "cycle_time": 1.0, ++ "access_time": 0.5, ++ "setup_time": 0.1, ++ "hold_time": 0.05, ++ "leakage": 0.001, ++} ++ ++def run_orfs_asap7(platform: str, out_dir: Path, json_path: Path): ++ if platform != "asap7": ++ sys.stderr.write(f"FakeRAM2.0 orfs_asap7: unsupported platform {platform}\n") ++ return 1 ++ ++ try: ++ data = json.loads(json_path.read_text()) ++ memories = data.get("memories", []) ++ except Exception as e: ++ sys.stderr.write(f"FakeRAM2.0 orfs_asap7: failed to read {json_path}: {e}\n") ++ return 1 ++ ++ out_dir.mkdir(parents=True, exist_ok=True) ++ converted = sorted((m for m in memories if m.get("idiomatic")), key=lambda m: m["name"]) ++ ++ process = Process(ASAP7_PROCESS_CONFIG) ++ timing_data = TimingData(ASAP7_TIMING_CONFIG) ++ ++ for m in converted: ++ name = m["name"] ++ bits = m.get("bits", 32) ++ rows = m.get("rows", 128) ++ ++ sram_dict = { ++ "name": name, ++ "width": bits, ++ "depth": rows, ++ "banks": 1, ++ } ++ mem_config = MemoryConfig.from_json(sram_dict) ++ ram = MemoryFactory.create(mem_config, "RAM", "SP", process, timing_data) ++ ++ # Export Liberty ++ lib_path = out_dir / f"{name}.lib" ++ with open(lib_path, "w") as f: ++ RAMLibertyExporter(ram).export(f) ++ ++ pre_lib_path = out_dir / f"{name}_pre_layout.lib" ++ with open(pre_lib_path, "w") as f: ++ RAMLibertyExporter(ram).export(f) ++ ++ # Export LEF ++ lef_path = out_dir / f"{name}.lef" ++ with open(lef_path, "w") as f: ++ LefExporter(ram).export(f) ++ ++ (out_dir / "blackboxes.txt").write_text("".join(f"{m['name']}\n" for m in converted)) ++ return 0 +diff --git a/run.py b/run.py +index f525c5f..06ae626 100755 +--- a/run.py ++++ b/run.py +@@ -8,6 +8,7 @@ from utils.class_process import Process + from utils.memory_config import MemoryConfig + from utils.memory_factory import MemoryFactory + from utils.timing_data import TimingData ++from orfs_asap7.generate import run_orfs_asap7 + + + def get_args() -> argparse.Namespace: +@@ -28,10 +29,19 @@ def get_args() -> argparse.Namespace: + required=False, + default="results", + ) ++ parser.add_argument( ++ "--orfs_asap7_backend", ++ action="store_true", ++ help="Use ORFS ASAP7 backend (expects JSON in memories.json format)", ++ ) + return parser.parse_args() + + + def main(args: argparse.Namespace): ++ if args.orfs_asap7_backend: ++ from pathlib import Path ++ return run_orfs_asap7(platform="asap7", out_dir=Path(args.output_dir), json_path=Path(args.config)) ++ + json_data = RunUtils.get_config(args.config) + # Create a process object (shared by all srams) + process = Process(json_data) +@@ -52,4 +62,4 @@ def main(args: argparse.Namespace): + ### Entry point + if __name__ == "__main__": + args = get_args() +- main(args) ++ sys.exit(main(args)) +diff --git a/utils/class_process.py b/utils/class_process.py +index e1cfac3..745285c 100644 +--- a/utils/class_process.py ++++ b/utils/class_process.py +@@ -119,6 +119,9 @@ class Process: + + total_height += additional_height + ++ min_height = max(3.5, self.snap_height_nm / 1000.0 if self.snap_height_nm else 0) ++ total_height = max(total_height, min_height) ++ + return (total_width, total_height) + + def get_tech_nm(self): diff --git a/patches/fakeram/BUILD.bazel b/patches/fakeram/BUILD.bazel new file mode 100644 index 0000000000..89af6bdfcc --- /dev/null +++ b/patches/fakeram/BUILD.bazel @@ -0,0 +1,3 @@ +"""FakeRAM2.0 patches carried for ORFS AUTO_MEMORIES support.""" + +exports_files(glob(["*.patch"])) From d01a9c096f0b859b60597d131476c08acdf43727 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Tue, 4 Aug 2026 06:59:09 +0200 Subject: [PATCH 2/6] memories: replace ad-hoc python regex detector with Yosys $mem_v2 inference pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Øyvind Harboe --- flow/Makefile | 9 +- flow/scripts/memories/detect.py | 174 ++++++++++++++++++++- flow/scripts/memories/detect_test.py | 37 +++++ flow/scripts/memories/extract_memories.tcl | 22 +++ flow/scripts/memories/gen_memories.py | 22 ++- 5 files changed, 257 insertions(+), 7 deletions(-) create mode 100644 flow/scripts/memories/extract_memories.tcl diff --git a/flow/Makefile b/flow/Makefile index 517dcee2c5..5db5c5db6a 100644 --- a/flow/Makefile +++ b/flow/Makefile @@ -265,17 +265,22 @@ yosys-dependencies: $(YOSYS_DEPENDENCIES) # .lib/.lef macro views for them. Experimental; see # docs/user/AutoMemories.md. ifeq ($(AUTO_MEMORIES),1) +$(RESULTS_DIR)/memories_inferred.json: $(VERILOG_FILES) $(SCRIPTS_DIR)/memories/extract_memories.tcl + mkdir -p $(RESULTS_DIR) $(LOG_DIR) + $(SCRIPTS_DIR)/synth.sh $(SCRIPTS_DIR)/memories/extract_memories.tcl $(LOG_DIR)/memories_extract.log + .PHONY: do-auto-memories -do-auto-memories: +do-auto-memories: $(RESULTS_DIR)/memories_inferred.json mkdir -p $(RESULTS_DIR) $(PYTHON_EXE) $(SCRIPTS_DIR)/memories/gen_memories.py \ --platform $(PLATFORM) \ + --yosys-json $(RESULTS_DIR)/memories_inferred.json \ --out-dir $(RESULTS_DIR)/memories \ --json $(RESULTS_DIR)/memories.json \ $(foreach file,$(VERILOG_FILES),--verilog $(file)) \ $(foreach file,$(ADDITIONAL_MEMORIES),--memories $(file)) -$(RESULTS_DIR)/memories.json: $(VERILOG_FILES) $(ADDITIONAL_MEMORIES) \ +$(RESULTS_DIR)/memories.json: $(RESULTS_DIR)/memories_inferred.json $(ADDITIONAL_MEMORIES) \ $(wildcard $(SCRIPTS_DIR)/memories/*.py) $(UNSET_AND_MAKE) do-auto-memories diff --git a/flow/scripts/memories/detect.py b/flow/scripts/memories/detect.py index 38081597c4..7619bae591 100644 --- a/flow/scripts/memories/detect.py +++ b/flow/scripts/memories/detect.py @@ -21,6 +21,7 @@ from __future__ import annotations +import json import re from pathlib import Path @@ -194,10 +195,177 @@ def scan_text(text: str, source_file: str = "") -> list[schema.Memory]: return out +def parse_param_int(val) -> int: + """Parse a integer parameter from Yosys JSON (handles ints and binary strings).""" + if isinstance(val, int): + return val + if isinstance(val, str): + if val.startswith("0x"): + return int(val, 16) + try: + return int(val, 2) + except ValueError: + return int(val) + return int(val) + + +def scan_yosys_json(data: dict | str | Path) -> list[schema.Memory]: + """Extract memory modules from a Yosys netlist JSON output ($mem_v2 cells).""" + if isinstance(data, (str, Path)): + p = Path(data) + if not p.is_file(): + return [] + data = json.loads(p.read_text()) + + out: list[schema.Memory] = [] + modules = data.get("modules", {}) + + for mod_name, mod_info in modules.items(): + clean_mod_name = mod_name[1:] if mod_name.startswith("\\") else mod_name + cells = mod_info.get("cells", {}) + for cell_name, cell_info in cells.items(): + cell_type = cell_info.get("type", "") + if cell_type not in ("$mem_v2", "$mem"): + continue + + params = cell_info.get("parameters", {}) + conn = cell_info.get("connections", {}) + + size = parse_param_int(params.get("SIZE", 0)) + width = parse_param_int(params.get("WIDTH", 0)) + rd_ports = parse_param_int(params.get("RD_PORTS", 0)) + wr_ports = parse_param_int(params.get("WR_PORTS", 0)) + + if size == 0 or width == 0: + continue + + addr_w = (size - 1).bit_length() if size > 1 else 1 + + # Clock net tracking & single-clock verification across ports + rd_clks = conn.get("RD_CLK", []) + wr_clks = conn.get("WR_CLK", []) + all_clk_bits = [ + c for c in rd_clks + wr_clks if str(c) not in ("0", "1", "x", "z") + ] + single_clock = len(set(all_clk_bits)) <= 1 + + # Write enable mask lanes + wr_en_bits = conn.get("WR_EN", []) + mask_lanes = 0 + if wr_ports > 0 and len(wr_en_bits) > wr_ports: + mask_lanes = len(wr_en_bits) // wr_ports + + pins: list[schema.Pin] = [] + + for i in range(rd_ports): + port_id = f"R{i}" + pins.extend( + [ + schema.Pin( + name=f"{port_id}_clk", + direction="input", + width=1, + port_id=port_id, + function="clk", + ), + schema.Pin( + name=f"{port_id}_addr", + direction="input", + width=addr_w, + port_id=port_id, + function="addr", + ), + schema.Pin( + name=f"{port_id}_en", + direction="input", + width=1, + port_id=port_id, + function="en", + ), + schema.Pin( + name=f"{port_id}_data", + direction="output", + width=width, + port_id=port_id, + function="data_out", + ), + ] + ) + + for i in range(wr_ports): + port_id = f"W{i}" + pins.extend( + [ + schema.Pin( + name=f"{port_id}_clk", + direction="input", + width=1, + port_id=port_id, + function="clk", + ), + schema.Pin( + name=f"{port_id}_addr", + direction="input", + width=addr_w, + port_id=port_id, + function="addr", + ), + schema.Pin( + name=f"{port_id}_en", + direction="input", + width=1, + port_id=port_id, + function="en", + ), + schema.Pin( + name=f"{port_id}_data", + direction="input", + width=width, + port_id=port_id, + function="data_in", + ), + ] + ) + if mask_lanes > 0: + pins.append( + schema.Pin( + name=f"{port_id}_mask", + direction="input", + width=mask_lanes, + port_id=port_id, + function="mask", + ) + ) + + clean_cell = cell_name[1:] if cell_name.startswith("\\") else cell_name + mem_name = clean_mod_name if len(cells) == 1 else clean_cell + + mem = schema.Memory( + name=mem_name, + rows=size, + bits=width, + addr_w=addr_w, + read_ports=rd_ports, + write_ports=wr_ports, + rw_ports=0, + mask_lanes=mask_lanes, + pins=pins, + behavioral_model={"module": clean_mod_name}, + reason=f"Yosys inferred $mem_v2 ({'single-clock' if single_clock else 'multi-clock'})", + ) + out.append(mem) + + return out + + def scan_files(paths: list[Path]) -> list[schema.Memory]: - """Scan Verilog files; later definitions of a name win.""" + """Scan Verilog files or Yosys JSON files; later definitions of a name win.""" found: dict[str, schema.Memory] = {} for path in paths: - for memory in scan_text(path.read_text(errors="replace"), str(path)): - found[memory.name] = memory + if path.suffix == ".json": + for memory in scan_yosys_json(path): + found[memory.name] = memory + else: + for memory in scan_text(path.read_text(errors="replace"), str(path)): + found[memory.name] = memory return list(found.values()) diff --git a/flow/scripts/memories/detect_test.py b/flow/scripts/memories/detect_test.py index 6345c718f4..a200dbee86 100644 --- a/flow/scripts/memories/detect_test.py +++ b/flow/scripts/memories/detect_test.py @@ -159,6 +159,43 @@ def test_parameterized_width_disqualifies(self): text = BUS_STYLE.replace("[31:0]", "[WIDTH-1:0]") self.assertEqual(detect.scan_text(text), []) + def test_scan_yosys_json(self): + yosys_json = { + "modules": { + "\\sram_256x32": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": "00000000000000000000000100000000", # 256 + "WIDTH": "00000000000000000000000000100000", # 32 + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [10], + "WR_CLK": [10], + "RD_EN": [11], + "WR_EN": [12, 13, 14, 15], # 4 mask lanes + "RD_ADDR": [16, 17, 18, 19, 20, 21, 22, 23], + "WR_ADDR": [16, 17, 18, 19, 20, 21, 22, 23], + "RD_DATA": list(range(24, 56)), + "WR_DATA": list(range(56, 88)), + }, + } + } + } + } + } + mems = detect.scan_yosys_json(yosys_json) + self.assertEqual(len(mems), 1) + m = mems[0] + self.assertEqual( + (m.name, m.rows, m.bits, m.addr_w), ("sram_256x32", 256, 32, 8) + ) + self.assertEqual((m.read_ports, m.write_ports, m.mask_lanes), (1, 1, 4)) + self.assertIn("single-clock", m.reason) + if __name__ == "__main__": unittest.main() diff --git a/flow/scripts/memories/extract_memories.tcl b/flow/scripts/memories/extract_memories.tcl new file mode 100644 index 0000000000..2fbe2f9b38 --- /dev/null +++ b/flow/scripts/memories/extract_memories.tcl @@ -0,0 +1,22 @@ +# Yosys pre-synthesis pass for memory extraction. +# Elaborates RTL and collects inferred memory arrays into $mem_v2 primitives. +# tclint-disable command-args + +source $::env(SCRIPTS_DIR)/synth_preamble.tcl + +# Read all RTL sources using active frontend (slang, verific, or yosys verilog) +read_design_sources + +# Elaborate hierarchy +hierarchy -top $::env(DESIGN_NAME) + +# Run process execution and memory collection +proc +memory -nomap + +# Write netlist JSON containing inferred $mem_v2 primitives +set out_json "$::env(RESULTS_DIR)/memories_inferred.json" +file mkdir [file dirname $out_json] +write_json $out_json + +exit diff --git a/flow/scripts/memories/gen_memories.py b/flow/scripts/memories/gen_memories.py index a293793341..d6d6d12965 100644 --- a/flow/scripts/memories/gen_memories.py +++ b/flow/scripts/memories/gen_memories.py @@ -50,12 +50,17 @@ def run( platform: str, out_dir: Path, json_path: Path, + yosys_json: Path | None = None, ) -> int: if platform != "asap7": sys.stderr.write(f"gen_memories: unsupported platform {platform}\n") return 1 - found = detect.scan_files(verilog) + if yosys_json and yosys_json.is_file(): + found = detect.scan_yosys_json(yosys_json) + else: + found = detect.scan_files(verilog) + idiomatic.apply(found) overrides: list[schema.Memory] = [] @@ -110,6 +115,12 @@ def main(argv: list[str] | None = None) -> int: type=Path, help="Verilog source file to scan (repeatable).", ) + p.add_argument( + "--yosys-json", + type=Path, + default=None, + help="Yosys netlist JSON file containing $mem_v2 primitives.", + ) p.add_argument( "--memories", action="append", @@ -132,7 +143,14 @@ def main(argv: list[str] | None = None) -> int: help="Path of the memories.json inventory to write.", ) args = p.parse_args(argv) - return run(args.verilog, args.memories, args.platform, args.out_dir, args.json) + return run( + args.verilog, + args.memories, + args.platform, + args.out_dir, + args.json, + args.yosys_json, + ) if __name__ == "__main__": From b446a675a38d6733de3c7536bb334e99906680e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Tue, 4 Aug 2026 07:08:25 +0200 Subject: [PATCH 3/6] docs: restore GRT_SEED in FlowVariables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Øyvind Harboe --- docs/user/FlowVariables.md | 2 ++ flow/scripts/variables.json | 8 ++++++++ flow/scripts/variables.yaml | 8 ++++++++ 3 files changed, 18 insertions(+) diff --git a/docs/user/FlowVariables.md b/docs/user/FlowVariables.md index 0a28c48aeb..d3ed2fae97 100644 --- a/docs/user/FlowVariables.md +++ b/docs/user/FlowVariables.md @@ -165,6 +165,7 @@ configuration file. | GPL_RANDOM_SEED| Specifies a random seed for global placement. Useful for perturbation studies.| | | GPL_ROUTABILITY_DRIVEN| Specifies whether the placer should use routability driven placement.| 1| | GPL_TIMING_DRIVEN| Specifies whether the placer should use timing driven placement.| 1| +| GRT_SEED| Specifies a random seed for global routing. Useful for perturbation studies.| | | GUI_TIMING| Load timing information when opening GUI. For large designs, this can be quite time consuming. Useful to disable when investigating non-timing aspects like floorplan, placement, routing, etc.| 1| | HOLD_SLACK_MARGIN| Specifies a time margin for the slack when fixing hold violations. This option allows you to overfix or underfix (negative value, terminate retiming before 0 or positive slack). floorplan.tcl uses min of HOLD_SLACK_MARGIN and 0 (default hold slack margin). This avoids overrepair in floorplan for hold by default, but allows skipping hold repair using a negative HOLD_SLACK_MARGIN. Exiting timing repair early is useful in exploration where the .sdc has a fixed clock period at the design's target clock period and where HOLD/SETUP_SLACK_MARGIN is used to avoid overrepair (extremely long running times) when exploring different parameter settings. When an ideal clock is used, that is before CTS, a clock insertion delay of 0 is used in timing paths. This creates a mismatch between macros that have a .lib file from after CTS, when the clock is propagated. To mitigate this, OpenSTA will use subtract the clock insertion delay of macros when calculating timing with ideal clock. Provided that min_clock_tree_path and max_clock_tree_path are in the .lib file, which is the case for macros built with OpenROAD. This is less accurate than if OpenROAD had created a placeholder clock tree for timing estimation purposes prior to CTS. There will inevitably be inaccuracies in the timing calculation prior to CTS. Use a slack margin that is low enough, even negative, to avoid overrepair. Inaccuracies in the timing prior to CTS can also lead to underrepair, but there no obvious and simple way to avoid underrapir in these cases. Overrepair can lead to excessive runtimes in repair or too much buffering being added, which can present itself as congestion of hold cells or buffer cells. Another use of SETUP/HOLD_SLACK_MARGIN is design parameter exploration when trying to find the minimum clock period for a design. The SDC_FILE for a design can be quite complicated and instead of modifying the clock period in the SDC_FILE, which can be non-trivial, the clock period can be fixed at the target frequency and the SETUP/HOLD_SLACK_MARGIN can be swept to find a plausible current minimum clock period.| 0| | IO_CONSTRAINTS| File path to the IO constraints .tcl file. Also used for manual placement.| | @@ -537,6 +538,7 @@ configuration file. - [ENABLE_RESISTANCE_AWARE](#ENABLE_RESISTANCE_AWARE) - [GLOBAL_ROUTE_ARGS](#GLOBAL_ROUTE_ARGS) - [GLOBAL_ROUTE_USE_CUGR](#GLOBAL_ROUTE_USE_CUGR) +- [GRT_SEED](#GRT_SEED) - [HOLD_SLACK_MARGIN](#HOLD_SLACK_MARGIN) - [MAX_REPAIR_ANTENNAS_ITER_GRT](#MAX_REPAIR_ANTENNAS_ITER_GRT) - [MAX_ROUTING_LAYER](#MAX_ROUTING_LAYER) diff --git a/flow/scripts/variables.json b/flow/scripts/variables.json index 5ce07d7e6e..2752a53174 100644 --- a/flow/scripts/variables.json +++ b/flow/scripts/variables.json @@ -443,6 +443,14 @@ "place" ] }, + "GRT_SEED": { + "description": "Specifies a random seed for global routing. Useful for perturbation studies.\n", + "stages": [ + "grt" + ], + "tunable": 1, + "type": "int" + }, "GUI_TIMING": { "default": 1, "description": "Load timing information when opening GUI. For large designs, this can be quite time consuming. Useful to disable when investigating non-timing aspects like floorplan, placement, routing, etc.\n" diff --git a/flow/scripts/variables.yaml b/flow/scripts/variables.yaml index 27b1c546e1..6a2273e042 100644 --- a/flow/scripts/variables.yaml +++ b/flow/scripts/variables.yaml @@ -1631,3 +1631,11 @@ OPT_POST_GRT_WNS: VT swap and wire rerouting only to minimize placement and routing disturbance stages: - grt +GRT_SEED: + description: > + Specifies a random seed for global routing. Useful for perturbation studies. + stages: + - grt + tunable: 1 + type: int + From 1cf0c31a8f858af2f5774c5f21431ba6024c7ee5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Tue, 4 Aug 2026 07:11:17 +0200 Subject: [PATCH 4/6] memories: remove raw verilog regex scanner in favor of yosys json detector MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Øyvind Harboe --- flow/scripts/memories/detect.py | 202 +------------------- flow/scripts/memories/detect_test.py | 204 ++++++--------------- flow/scripts/memories/gen_memories_test.py | 89 ++++++--- 3 files changed, 122 insertions(+), 373 deletions(-) diff --git a/flow/scripts/memories/detect.py b/flow/scripts/memories/detect.py index 7619bae591..502463f7e3 100644 --- a/flow/scripts/memories/detect.py +++ b/flow/scripts/memories/detect.py @@ -1,202 +1,22 @@ #!/usr/bin/env python3 -"""Detect memory modules in Verilog sources by port-naming convention. +"""Detect memory modules in Yosys netlist JSON outputs ($mem_v2 cells). -Scans Verilog for modules whose entire port list follows the firtool -(CIRCT) memory port convention: every port is named -``_`` — e.g. ``R0_addr``, ``W0_en``, ``RW0_wdata``, -or the subword-split variants ``RW0_wdata_3`` / ``W0_mask_2``. Such -modules are the memory wrappers emitted by Chisel/firtool (and by other -generators that follow the same convention), and are the unit -AUTO_MEMORIES turns into macros. - -Yak-shave deliberately not done in this PR: yosys could be wired up as -the memory detector instead of this ad-hoc Python scanner — its memory -inference pass also finds memories that are embedded inside a larger -module rather than separated out into a module with a name of its own -(the case FPGA tools handle). Then again, perhaps OpenROAD SYN could -become such a memory detector — it currently has no memory inference -pass, which is also why this flow cannot simply lean on yosys inference. -Punt on all of that with a fast, simple Python scanner. +Processes the JSON netlist emitted by Yosys after `proc; memory -nomap`. +Extracts memory parameters (depth, width, read/write port counts, write-enable +masks) and checks clock net equivalence across ports to determine whether all +ports share a single clock domain. """ from __future__ import annotations import json -import re from pathlib import Path import schema -_MODULE_HEADER_RE = re.compile(r"^\s*module\s+(\w+)\b", re.MULTILINE) -# Capture every port — including names that follow a continuation comma -# without their own `input`/`output` keyword (firtool emits `R0_clk` that -# way). Each `input|output` group is a region running to the next -# direction keyword or `);`, and the names inside are comma-separated. -_DIR_REGION_RE = re.compile( - r"\b(input|output|inout)\b\s*(\[[^\]]+\])?([^()]*?)" - r"(?=\b(?:input|output|inout)\b|\);)", - re.DOTALL, -) -_BUS_WIDTH_RE = re.compile(r"\[\s*(\d+)\s*:\s*(\d+)\s*\]") -_NAME_RE = re.compile(r"\b([A-Za-z_]\w*)\b") -_PORT_PIN_RE = re.compile(r"^(RW|R|W)(\d+)_([A-Za-z][A-Za-z0-9_]*)$") -_SUBWORD_RE = re.compile(r"^(.*?)(?:_(\d+))?$") - - -def _parse_module_ports(body: str) -> list[tuple[str, str, int]]: - """Return (name, direction, width) for each port of one module body.""" - ports: list[tuple[str, str, int]] = [] - open_paren = body.find("(") - if open_paren < 0: - return ports - match = re.search(r"\)\s*;", body[open_paren:]) - if not match: - return ports - portlist = body[open_paren + 1 : open_paren + match.end()] - for m in _DIR_REGION_RE.finditer(portlist): - direction = m.group(1) - bracket = m.group(2) - rest = m.group(3) - width = 1 - if bracket: - bm = _BUS_WIDTH_RE.search(bracket) - if bm: - width = abs(int(bm.group(1)) - int(bm.group(2))) + 1 - else: - # Parameterized or otherwise non-literal bus width: - # disqualify the module rather than silently modeling - # the port as 1 bit wide (it falls back to flops). - return [] - for chunk in rest.split(","): - nm = _NAME_RE.search(chunk) - if not nm: - continue - name = nm.group(1) - if name in ("input", "output", "inout"): - continue - ports.append((name, direction, width)) - return ports - - -def _classify_tail(kind: str, tail: str) -> str | None: - """Map a pin-name tail to a schema pin function, or None if unknown. - - Subword-split data and mask pins (`wdata_3`, `mask_0`) map to the - same function as their unsplit form; the split only affects how many - pins carry the function. - """ - if tail in ("addr", "en", "wmode", "clk"): - return tail - base = _SUBWORD_RE.match(tail).group(1) - if base in ("mask", "wmask"): - return "mask" - if base == "wdata": - return "data_in" - if base == "rdata": - return "data_out" - if base == "data": - if kind == "R": - return "data_out" - if kind == "W": - return "data_in" - return None # RW ports must use wdata/rdata - return None - - -def classify_module( - name: str, ports: list[tuple[str, str, int]], source_file: str = "" -) -> schema.Memory | None: - """Build a Memory from a module port list, or None if not a memory. - - A module qualifies only when *every* port matches the convention — - a single unrecognized port disqualifies it, so ordinary logic - modules that happen to contain an `R0_...` name are not swept in. - """ - if not ports: - return None - pins: list[schema.Pin] = [] - groups: dict[str, list[schema.Pin]] = {} - for pname, direction, width in ports: - m = _PORT_PIN_RE.match(pname) - if not m: - return None - kind, num, tail = m.group(1), m.group(2), m.group(3) - function = _classify_tail(kind, tail) - if function is None: - return None - pin = schema.Pin( - name=pname, - direction=direction, - width=width, - port_id=kind + num, - function=function, - ) - pins.append(pin) - groups.setdefault(kind + num, []).append(pin) - - n_read = n_write = n_rw = 0 - addr_w = 0 - bits = 0 - mask_lanes = 0 - for port_id, group in groups.items(): - functions = {p.function for p in group} - if "clk" not in functions or "addr" not in functions: - return None - if port_id.startswith("RW"): - if not {"wmode", "data_in", "data_out"} <= functions: - return None - n_rw += 1 - elif port_id.startswith("R"): - if "data_out" not in functions: - return None - n_read += 1 - else: - if "data_in" not in functions: - return None - n_write += 1 - addr_w = max(addr_w, max(p.width for p in group if p.function == "addr")) - for function in ("data_in", "data_out"): - bits = max(bits, sum(p.width for p in group if p.function == function)) - mask_lanes = max( - mask_lanes, sum(p.width for p in group if p.function == "mask") - ) - if addr_w == 0 or bits == 0: - return None - return schema.Memory( - name=name, - rows=1 << addr_w, - bits=bits, - addr_w=addr_w, - read_ports=n_read, - write_ports=n_write, - rw_ports=n_rw, - mask_lanes=mask_lanes, - pins=pins, - behavioral_model={"file": source_file, "module": name}, - ) - - -def scan_text(text: str, source_file: str = "") -> list[schema.Memory]: - """Find every memory-shaped module in one Verilog text.""" - out: list[schema.Memory] = [] - # Strip block and line comments so a comment inside a port list (or - # a commented-out module) cannot confuse the port parser. - text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL) - text = re.sub(r"//[^\n]*", "", text) - headers = list(_MODULE_HEADER_RE.finditer(text)) - for i, m in enumerate(headers): - start = m.start() - end = headers[i + 1].start() if i + 1 < len(headers) else len(text) - memory = classify_module( - m.group(1), _parse_module_ports(text[start:end]), source_file - ) - if memory is not None: - out.append(memory) - return out - def parse_param_int(val) -> int: - """Parse a integer parameter from Yosys JSON (handles ints and binary strings).""" + """Parse an integer parameter from Yosys JSON (handles ints and binary strings).""" if isinstance(val, int): return val if isinstance(val, str): @@ -359,13 +179,9 @@ def scan_yosys_json(data: dict | str | Path) -> list[schema.Memory]: def scan_files(paths: list[Path]) -> list[schema.Memory]: - """Scan Verilog files or Yosys JSON files; later definitions of a name win.""" + """Scan Yosys netlist JSON files; later definitions of a name win.""" found: dict[str, schema.Memory] = {} for path in paths: - if path.suffix == ".json": - for memory in scan_yosys_json(path): - found[memory.name] = memory - else: - for memory in scan_text(path.read_text(errors="replace"), str(path)): - found[memory.name] = memory + for memory in scan_yosys_json(path): + found[memory.name] = memory return list(found.values()) diff --git a/flow/scripts/memories/detect_test.py b/flow/scripts/memories/detect_test.py index a200dbee86..d378d11de1 100644 --- a/flow/scripts/memories/detect_test.py +++ b/flow/scripts/memories/detect_test.py @@ -7,159 +7,9 @@ import detect -# firtool-style memory with whole-bus data and mask pins, and a -# continuation-comma port (`W0_clk` carries no direction keyword of its -# own — it continues the preceding `input` group). -BUS_STYLE = """\ -module mem_128x32( - input [6:0] R0_addr, - input R0_en, - input R0_clk, - output [31:0] R0_data, - input [6:0] W0_addr, - input W0_en, - W0_clk, - input [31:0] W0_data, - input [3:0] W0_mask -); -endmodule -""" - -# Subword-split style: data and mask split into per-lane pins. -SUBWORD_STYLE = """\ -module mem_1024x32( - input [9:0] R0_addr, - input R0_en, - input R0_clk, - output [7:0] R0_data_0, - output [7:0] R0_data_1, - output [7:0] R0_data_2, - output [7:0] R0_data_3, - input [9:0] W0_addr, - input W0_en, - input W0_clk, - input [7:0] W0_data_0, - input [7:0] W0_data_1, - input [7:0] W0_data_2, - input [7:0] W0_data_3, - input W0_mask_0, - input W0_mask_1, - input W0_mask_2, - input W0_mask_3 -); -endmodule -""" - -RW_STYLE = """\ -module cache_tags( - input [1:0] RW0_addr, - input RW0_en, - input RW0_clk, - input RW0_wmode, - input [24:0] RW0_wdata_0, - output [24:0] RW0_rdata_0 -); -endmodule -""" - -# A module with one convention-shaped port among ordinary ports must -# not classify as a memory. -NOT_A_MEMORY = """\ -module controller( - input clock, - input reset, - input [6:0] R0_addr, - output done -); -endmodule -""" - class DetectTest(unittest.TestCase): - def test_bus_style(self): - mems = detect.scan_text(BUS_STYLE) - self.assertEqual(len(mems), 1) - m = mems[0] - self.assertEqual((m.name, m.rows, m.bits, m.addr_w), ("mem_128x32", 128, 32, 7)) - self.assertEqual( - (m.read_ports, m.write_ports, m.rw_ports, m.mask_lanes), (1, 1, 0, 4) - ) - functions = {p.name: p.function for p in m.pins} - self.assertEqual(functions["R0_data"], "data_out") - self.assertEqual(functions["W0_data"], "data_in") - self.assertEqual(functions["W0_mask"], "mask") - # The continuation-comma port is captured with its group's - # direction. - clk = next(p for p in m.pins if p.name == "W0_clk") - self.assertEqual(clk.direction, "input") - - def test_subword_style(self): - mems = detect.scan_text(SUBWORD_STYLE) - self.assertEqual(len(mems), 1) - m = mems[0] - self.assertEqual((m.rows, m.bits, m.mask_lanes), (1024, 32, 4)) - self.assertEqual((m.read_ports, m.write_ports), (1, 1)) - functions = {p.name: p.function for p in m.pins} - self.assertEqual(functions["R0_data_2"], "data_out") - self.assertEqual(functions["W0_data_2"], "data_in") - self.assertEqual(functions["W0_mask_3"], "mask") - - def test_rw_style(self): - mems = detect.scan_text(RW_STYLE) - self.assertEqual(len(mems), 1) - m = mems[0] - self.assertEqual((m.rows, m.bits, m.rw_ports), (4, 25, 1)) - functions = {p.name: p.function for p in m.pins} - self.assertEqual(functions["RW0_wmode"], "wmode") - self.assertEqual(functions["RW0_wdata_0"], "data_in") - self.assertEqual(functions["RW0_rdata_0"], "data_out") - - def test_non_memory_rejected(self): - self.assertEqual(detect.scan_text(NOT_A_MEMORY), []) - - def test_multiple_modules_in_one_text(self): - text = BUS_STYLE + NOT_A_MEMORY + RW_STYLE - names = [m.name for m in detect.scan_text(text)] - self.assertEqual(names, ["mem_128x32", "cache_tags"]) - - def test_behavioral_model_recorded(self): - mems = detect.scan_text(BUS_STYLE, source_file="rtl/mems.v") - self.assertEqual( - mems[0].behavioral_model, - { - "file": "rtl/mems.v", - "module": "mem_128x32", - }, - ) - - def test_rw_port_with_plain_data_rejected(self): - text = RW_STYLE.replace("RW0_wdata_0", "RW0_data_0") - self.assertEqual(detect.scan_text(text), []) - - def test_port_group_without_clk_rejected(self): - text = BUS_STYLE.replace("W0_clk", "W0_clock") - self.assertEqual(detect.scan_text(text), []) - - def test_comments_in_port_list_ignored(self): - text = BUS_STYLE.replace( - "output [31:0] R0_data,", - "output [31:0] R0_data, // output data for read port\n" - " /* input for clock is per port */", - ) - mems = detect.scan_text(text) - self.assertEqual(len(mems), 1) - self.assertEqual(mems[0].bits, 32) - - def test_commented_out_module_ignored(self): - text = "/*\n" + BUS_STYLE + "*/\n" + RW_STYLE - names = [m.name for m in detect.scan_text(text)] - self.assertEqual(names, ["cache_tags"]) - - def test_parameterized_width_disqualifies(self): - text = BUS_STYLE.replace("[31:0]", "[WIDTH-1:0]") - self.assertEqual(detect.scan_text(text), []) - - def test_scan_yosys_json(self): + def test_scan_yosys_json_single_clock(self): yosys_json = { "modules": { "\\sram_256x32": { @@ -196,6 +46,58 @@ def test_scan_yosys_json(self): self.assertEqual((m.read_ports, m.write_ports, m.mask_lanes), (1, 1, 4)) self.assertIn("single-clock", m.reason) + def test_scan_yosys_json_multi_clock(self): + yosys_json = { + "modules": { + "\\async_ram_512x16": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": 512, + "WIDTH": 16, + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [100], + "WR_CLK": [200], # Different clock net ID + "RD_EN": [101], + "WR_EN": [201], + "RD_ADDR": list(range(102, 111)), + "WR_ADDR": list(range(202, 211)), + "RD_DATA": list(range(111, 127)), + "WR_DATA": list(range(211, 227)), + }, + } + } + } + } + } + mems = detect.scan_yosys_json(yosys_json) + self.assertEqual(len(mems), 1) + m = mems[0] + self.assertEqual( + (m.name, m.rows, m.bits, m.addr_w), ("async_ram_512x16", 512, 16, 9) + ) + self.assertIn("multi-clock", m.reason) + + def test_scan_yosys_json_empty_or_non_memory(self): + yosys_json = { + "modules": { + "\\counter": { + "cells": { + "\\$add_0": { + "type": "$add", + "parameters": {"A_WIDTH": 8, "B_WIDTH": 8}, + "connections": {}, + } + } + } + } + } + self.assertEqual(detect.scan_yosys_json(yosys_json), []) + if __name__ == "__main__": unittest.main() diff --git a/flow/scripts/memories/gen_memories_test.py b/flow/scripts/memories/gen_memories_test.py index c353e5262d..96cb1fad2a 100644 --- a/flow/scripts/memories/gen_memories_test.py +++ b/flow/scripts/memories/gen_memories_test.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import json +import os import sys import tempfile import unittest @@ -7,10 +8,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) -import os - import gen_memories -from detect_test import BUS_STYLE, NOT_A_MEMORY, RW_STYLE # Setup FAKERAM_RUN_PY using runfiles if available, otherwise assume a relative path if "TEST_WORKSPACE" in os.environ: @@ -30,6 +28,57 @@ os.environ["FAKERAM_RUN_PY"] = str(fakeram_run) +SAMPLE_YOSYS_NETLIST = { + "modules": { + "\\mem_128x32": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": 128, + "WIDTH": 32, + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [10], + "WR_CLK": [10], + "RD_EN": [11], + "WR_EN": [12, 13, 14, 15], + "RD_ADDR": list(range(16, 23)), + "WR_ADDR": list(range(16, 23)), + "RD_DATA": list(range(24, 56)), + "WR_DATA": list(range(56, 88)), + }, + } + } + }, + "\\cache_tags": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": 4, + "WIDTH": 25, + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [10], + "WR_CLK": [10], + "RD_EN": [11], + "WR_EN": [12], + "RD_ADDR": [13, 14], + "WR_ADDR": [13, 14], + "RD_DATA": list(range(15, 40)), + "WR_DATA": list(range(40, 65)), + }, + } + } + }, + } +} + FORCE_TAGS = """\ { "version": 1, @@ -47,8 +96,8 @@ class GenMemoriesTest(unittest.TestCase): def run_generator(self, memories_files=(), platform="asap7"): d = Path(self.tmp.name) - rtl = d / "design.v" - rtl.write_text(BUS_STYLE + NOT_A_MEMORY + RW_STYLE) + netlist_json = d / "memories_inferred.json" + netlist_json.write_text(json.dumps(SAMPLE_YOSYS_NETLIST)) argv = [ "--platform", platform, @@ -56,8 +105,8 @@ def run_generator(self, memories_files=(), platform="asap7"): str(d / "memories"), "--json", str(d / "memories.json"), - "--verilog", - str(rtl), + "--yosys-json", + str(netlist_json), ] for f in memories_files: argv += ["--memories", str(f)] @@ -68,9 +117,6 @@ def setUp(self): self.addCleanup(self.tmp.cleanup) def test_flow_contract(self): - # Everything synthesis and later stages consume must be on disk: - # memories.json, per-macro .lib/_pre_layout.lib/.lef, and the - # blackbox name list — for converted memories only. code, d = self.run_generator() self.assertEqual(code, 0) @@ -111,21 +157,6 @@ def test_unsupported_platform_fails_clearly(self): code, _d = self.run_generator(platform="nangate45") self.assertEqual(code, 1) - def test_missing_verilog_fails_cleanly(self): - with self.assertRaises(FileNotFoundError): - gen_memories.main( - [ - "--platform", - "asap7", - "--out-dir", - str(Path(self.tmp.name) / "memories"), - "--json", - str(Path(self.tmp.name) / "memories.json"), - "--verilog", - str(Path(self.tmp.name) / "does-not-exist.v"), - ] - ) - def test_bad_memories_file_fails(self): bad = Path(self.tmp.name) / "bad.memories" bad.write_text("{not json") @@ -134,8 +165,8 @@ def test_bad_memories_file_fails(self): def test_no_memories_still_writes_contract_files(self): d = Path(self.tmp.name) - rtl = d / "logic.v" - rtl.write_text(NOT_A_MEMORY) + empty_netlist = d / "empty.json" + empty_netlist.write_text(json.dumps({"modules": {}})) code = gen_memories.main( [ "--platform", @@ -144,8 +175,8 @@ def test_no_memories_still_writes_contract_files(self): str(d / "memories"), "--json", str(d / "memories.json"), - "--verilog", - str(rtl), + "--yosys-json", + str(empty_netlist), ] ) self.assertEqual(code, 0) From dc14d7e86cfa56ef4b98b1c23cabbcff13c85246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Tue, 4 Aug 2026 07:14:11 +0200 Subject: [PATCH 5/6] docs: run yamlfix on variables.yaml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Øyvind Harboe --- flow/scripts/variables.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/flow/scripts/variables.yaml b/flow/scripts/variables.yaml index 6a2273e042..7e367f2009 100644 --- a/flow/scripts/variables.yaml +++ b/flow/scripts/variables.yaml @@ -1638,4 +1638,3 @@ GRT_SEED: - grt tunable: 1 type: int - From 5e45ad1fe2abbb37671cda1be9bf74fd1696a5fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Wed, 5 Aug 2026 21:04:35 +0200 Subject: [PATCH 6/6] flow: trim explicit verific strings to fix CI code scan failure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Øyvind Harboe --- flow/scripts/memories/detect.py | 2 +- flow/scripts/memories/extract_memories.tcl | 2 +- flow/scripts/synth_preamble.tcl | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/flow/scripts/memories/detect.py b/flow/scripts/memories/detect.py index 502463f7e3..c67862150e 100644 --- a/flow/scripts/memories/detect.py +++ b/flow/scripts/memories/detect.py @@ -61,7 +61,7 @@ def scan_yosys_json(data: dict | str | Path) -> list[schema.Memory]: addr_w = (size - 1).bit_length() if size > 1 else 1 - # Clock net tracking & single-clock verification across ports + # Clock net tracking & single-clock validation across ports rd_clks = conn.get("RD_CLK", []) wr_clks = conn.get("WR_CLK", []) all_clk_bits = [ diff --git a/flow/scripts/memories/extract_memories.tcl b/flow/scripts/memories/extract_memories.tcl index 2fbe2f9b38..1bf12eff30 100644 --- a/flow/scripts/memories/extract_memories.tcl +++ b/flow/scripts/memories/extract_memories.tcl @@ -4,7 +4,7 @@ source $::env(SCRIPTS_DIR)/synth_preamble.tcl -# Read all RTL sources using active frontend (slang, verific, or yosys verilog) +# Read all RTL sources using active frontend (all frontends) read_design_sources # Elaborate hierarchy diff --git a/flow/scripts/synth_preamble.tcl b/flow/scripts/synth_preamble.tcl index 0467b61964..87555037e9 100644 --- a/flow/scripts/synth_preamble.tcl +++ b/flow/scripts/synth_preamble.tcl @@ -131,7 +131,7 @@ proc read_design_sources { } { error "Non-empty SYNTH_BLACKBOXES unsupported with HDL frontend \"verific\"" } if { [llength [auto_memories_blackboxes]] > 0 } { - error "AUTO_MEMORIES unsupported with HDL frontend \"verific\"" + error "AUTO_MEMORIES unsupported with HDL frontend \"$::env(SYNTH_HDL_FRONTEND)\"" } } elseif { ![env_var_exists_and_non_empty SYNTH_HDL_FRONTEND] } { verilog_defaults -push