Datasets:
Download code/eda_tools.py from drawais/circuitqa: direct link, hf CLI and curl.
- Browser
- Download file 40.3 kB
-
https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/eda_tools.py
- Command line
-
hf download hf://datasets/drawais/circuitqa/code/eda_tools.py
-
curl -L -o eda_tools.py https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/eda_tools.py
40.3 kB
| #!/usr/bin/env python3 | |
| """ | |
| EDA Tool Suite for CircuitQA-Tool Dataset Generation | |
| Six analysis backends: | |
| 1. synthesis_tool: Yosys + ABC; gate counts and gate-count-based area/delay/power estimates | |
| 2. simulation_tool: Icarus Verilog; toggle rates and toggle coverage measured from the VCD waveform | |
| 3. graph_extractor: Yosys; CDFG/AIG/DFG graphs | |
| 4. static_analyzer: source structure analysis | |
| 5. optimization_advisor: rule-based recommendations and Yosys recipes per target metric | |
| 6. cross_stage_mapper: RTL-to-netlist name alignment | |
| Each tool returns a JSON-serialisable dict. | |
| """ | |
| import os | |
| import re | |
| import json | |
| import tempfile | |
| import subprocess | |
| from pathlib import Path | |
| from typing import Dict, List, Any, Optional, Tuple | |
| from dataclasses import dataclass, asdict | |
| import hashlib | |
| import time | |
| # Root of the local tool installation (oss-cad-suite/, incdir/); override with CIRCUITQA_ROOT. | |
| TOOLS_ROOT = os.environ.get("CIRCUITQA_ROOT", os.path.expanduser("~/circuitqa")) | |
| # ============================================================================ | |
| # Configuration | |
| # ============================================================================ | |
| # Conda environment with EDA tools | |
| CONDA_ENV = "eda" | |
| CONDA_PATH = os.path.expanduser("~/miniconda3") | |
| # Tool timeouts (seconds) | |
| YOSYS_TIMEOUT = 120 | |
| VERILATOR_TIMEOUT = 60 | |
| IVERILOG_TIMEOUT = 60 | |
| # Technology library for area estimation (generic) | |
| # Area units are in arbitrary units (AU) - relative comparisons only | |
| GATE_AREAS = { | |
| '$_AND_': 1.0, '$_NAND_': 1.0, '$_OR_': 1.0, '$_NOR_': 1.0, | |
| '$_XOR_': 2.0, '$_XNOR_': 2.0, '$_NOT_': 0.5, '$_BUF_': 0.5, | |
| '$_ANDNOT_': 1.5, '$_ORNOT_': 1.5, '$_MUX_': 2.0, | |
| '$_DFF_P_': 4.0, '$_DFF_N_': 4.0, '$_DFFE_PP_': 5.0, | |
| '$_SDFF_PP0_': 5.0, '$_SDFF_PP1_': 5.0, | |
| '$_DLATCH_P_': 3.0, '$_DLATCH_N_': 3.0, | |
| } | |
| # Delay per gate type (ps) - simplified model | |
| GATE_DELAYS = { | |
| '$_AND_': 50, '$_NAND_': 40, '$_OR_': 50, '$_NOR_': 40, | |
| '$_XOR_': 80, '$_XNOR_': 80, '$_NOT_': 20, '$_BUF_': 20, | |
| '$_ANDNOT_': 60, '$_ORNOT_': 60, '$_MUX_': 100, | |
| '$_DFF_P_': 150, '$_DFF_N_': 150, '$_DFFE_PP_': 160, | |
| } | |
| # ============================================================================ | |
| # Helper Functions | |
| # ============================================================================ | |
| def _last_json(text): | |
| """Yosys prints log lines both before and after `stat -json` output, so the | |
| JSON is a substring, not a prefix or suffix. A greedy brace-to-brace regex | |
| produces invalid JSON and json.loads on the remainder fails with "Extra | |
| data" -- either way the parse silently fails and gate_count stays 0, which | |
| then gets written into ground-truth answers. Scan candidate starts and use | |
| raw_decode, which parses a prefix and ignores trailing text.""" | |
| import json as _j | |
| dec = _j.JSONDecoder() | |
| for i in [m.start() for m in re.finditer(r"\{", text)]: | |
| try: | |
| d, _ = dec.raw_decode(text[i:]) | |
| except Exception: | |
| continue | |
| if isinstance(d, dict) and "modules" in d: | |
| return d | |
| return None | |
| def run_command(cmd: List[str], timeout: int = 60, cwd: str = None) -> Tuple[int, str, str]: | |
| """Run a shell command with timeout.""" | |
| # Run in its own process group so that a timeout kills the tool itself | |
| # (yosys/abc/vvp), not only the wrapping shell; otherwise orphans keep running. | |
| import signal | |
| try: | |
| p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, | |
| text=True, cwd=cwd, start_new_session=True) | |
| try: | |
| out, err = p.communicate(timeout=timeout) | |
| return p.returncode, out, err | |
| except subprocess.TimeoutExpired: | |
| try: os.killpg(p.pid, signal.SIGKILL) | |
| except Exception: pass | |
| p.communicate() | |
| return -1, "", f"Command timed out after {timeout}s" | |
| except Exception as e: | |
| return -2, "", str(e) | |
| def run_with_conda(tool_cmd: str, timeout: int = 60, cwd: str = None) -> Tuple[int, str, str]: | |
| """Run an EDA tool. Tools are expected on PATH (oss-cad-suite).""" | |
| tool_cmd = f"export PATH={TOOLS_ROOT}/oss-cad-suite/bin:$PATH; " + tool_cmd | |
| return run_command(["bash", "-c", tool_cmd], timeout=timeout, cwd=cwd) | |
| def write_temp_verilog(code: str, suffix: str = ".v") -> str: | |
| """Write Verilog code to a temporary file.""" | |
| fd, path = tempfile.mkstemp(suffix=suffix) | |
| with os.fdopen(fd, 'w') as f: | |
| f.write(code) | |
| return path | |
| def extract_module_name(verilog_code: str) -> Optional[str]: | |
| """Extract the first module name from Verilog code.""" | |
| match = re.search(r'module\s+(\w+)', verilog_code) | |
| return match.group(1) if match else None | |
| # ============================================================================ | |
| # Tool 1: Synthesis Tool | |
| # ============================================================================ | |
| class SynthesisResult: | |
| """Result from synthesis_tool.""" | |
| status: str | |
| area: float | |
| delay: float | |
| power: float # Estimated from toggle activity | |
| gate_count: int | |
| cell_breakdown: Dict[str, int] | |
| wire_count: int | |
| wire_bits: int | |
| critical_path_estimate: float | |
| synthesis_log: str | |
| error: Optional[str] = None | |
| def synthesis_tool(verilog_code: str, optimization_level: str = "medium", | |
| target_technology: str = "generic") -> Dict[str, Any]: | |
| """ | |
| Synthesize Verilog code and extract PPA metrics using Yosys + ABC. | |
| Args: | |
| verilog_code: Verilog source code | |
| optimization_level: "low", "medium", or "high" | |
| target_technology: Technology target (currently "generic" only) | |
| Returns: | |
| Dict with area, delay, power, gate_count, synthesis_log | |
| """ | |
| # Write code to temp file | |
| temp_file = write_temp_verilog(verilog_code) | |
| module_name = extract_module_name(verilog_code) or "top" | |
| try: | |
| # Build Yosys script based on optimization level | |
| opt_passes = { | |
| "low": "opt", | |
| "medium": "opt; share; opt", | |
| "high": "opt; share; opt; freduce; opt; techmap; opt" | |
| } | |
| opt_cmd = opt_passes.get(optimization_level, opt_passes["medium"]) | |
| # Yosys synthesis command | |
| yosys_script = f""" | |
| read_verilog -I{TOOLS_ROOT}/incdir {temp_file} | |
| hierarchy -top {module_name} | |
| proc; {opt_cmd} | |
| techmap | |
| abc -g gates | |
| opt_clean | |
| stat -json | |
| """ | |
| # Run Yosys | |
| yosys_cmd = f"yosys -p '{yosys_script}' 2>&1" | |
| returncode, stdout, stderr = run_with_conda(yosys_cmd, timeout=YOSYS_TIMEOUT) | |
| if returncode != 0: | |
| return asdict(SynthesisResult( | |
| status="error", | |
| area=0, delay=0, power=0, gate_count=0, | |
| cell_breakdown={}, wire_count=0, wire_bits=0, | |
| critical_path_estimate=0, | |
| synthesis_log=stdout + stderr, | |
| error=f"Yosys failed with code {returncode}" | |
| )) | |
| # Parse synthesis statistics from Yosys output | |
| cell_breakdown = {} | |
| gate_count = 0 | |
| wire_count = 0 | |
| wire_bits = 0 | |
| # Try to parse JSON output first (stat -json format) | |
| try: | |
| # Find JSON block in output | |
| stat_json = _last_json(stdout) | |
| if stat_json: | |
| if 'modules' in stat_json: | |
| for mod_name, mod_data in stat_json['modules'].items(): | |
| if 'num_cells_by_type' in mod_data: | |
| for cell_type, count in mod_data['num_cells_by_type'].items(): | |
| cell_breakdown[cell_type] = count | |
| gate_count += count | |
| if 'num_wires' in mod_data: | |
| wire_count = mod_data['num_wires'] | |
| if 'num_wire_bits' in mod_data: | |
| wire_bits = mod_data['num_wire_bits'] | |
| except (json.JSONDecodeError, KeyError): | |
| pass | |
| # Fallback: Parse text output if JSON parsing failed | |
| if gate_count == 0: | |
| for line in stdout.split('\n'): | |
| line = line.strip() | |
| # Match cell type lines like " $_AND_ 15" | |
| cell_match = re.match(r'(\$_\w+_)\s+(\d+)', line) | |
| if cell_match: | |
| cell_type = cell_match.group(1) | |
| count = int(cell_match.group(2)) | |
| cell_breakdown[cell_type] = count | |
| gate_count += count | |
| # Match wire counts | |
| wire_match = re.match(r'Number of wires:\s+(\d+)', line) | |
| if wire_match: | |
| wire_count = int(wire_match.group(1)) | |
| bits_match = re.match(r'Number of wire bits:\s+(\d+)', line) | |
| if bits_match: | |
| wire_bits = int(bits_match.group(1)) | |
| # Calculate area estimate | |
| area = sum(GATE_AREAS.get(cell, 1.0) * count | |
| for cell, count in cell_breakdown.items()) | |
| # Estimate delay (critical path = longest chain) | |
| # Simplified: assume sqrt(gate_count) depth | |
| avg_delay = sum(GATE_DELAYS.get(cell, 50) * count | |
| for cell, count in cell_breakdown.items()) / max(gate_count, 1) | |
| critical_path_estimate = avg_delay * (gate_count ** 0.3) | |
| # Estimate power (simplified: proportional to gate count and toggle) | |
| power = gate_count * 0.001 # mW estimate | |
| return asdict(SynthesisResult( | |
| status="success", | |
| area=round(area, 2), | |
| delay=round(critical_path_estimate, 2), | |
| power=round(power, 4), | |
| gate_count=gate_count, | |
| cell_breakdown=cell_breakdown, | |
| wire_count=wire_count, | |
| wire_bits=wire_bits, | |
| critical_path_estimate=round(critical_path_estimate, 2), | |
| synthesis_log=stdout[-2000:] if len(stdout) > 2000 else stdout | |
| )) | |
| finally: | |
| # Cleanup temp file | |
| if os.path.exists(temp_file): | |
| os.remove(temp_file) | |
| # ============================================================================ | |
| # Tool 2: Simulation Tool | |
| # ============================================================================ | |
| class SimulationResult: | |
| """Result from simulation_tool.""" | |
| status: str | |
| toggle_rates: Dict[str, float] | |
| simulation_cycles: int | |
| assertion_results: Dict[str, bool] | |
| coverage_estimate: float | |
| signal_activity: Dict[str, Any] | |
| simulation_log: str | |
| error: Optional[str] = None | |
| def _parse_ports(verilog_code: str, module_name: str): | |
| """(name, width or None) for the input and output ports of `module_name`.""" | |
| m = re.search(r"\bmodule\s+" + re.escape(module_name) + r"\b(.*?)\bendmodule\b", verilog_code, re.S) | |
| body = m.group(1) if m else verilog_code | |
| def grab(kind): | |
| out = [] | |
| for decl in re.finditer(kind + r"\s+(?:(?:wire|reg|logic|signed|unsigned)\s+)*(\[\s*(\d+)\s*:\s*(\d+)\s*\])?\s*([A-Za-z_][\w\s,]*?)\s*(?=[;)]|,\s*(?:input|output|inout)\b)", body): | |
| w = abs(int(decl.group(2)) - int(decl.group(3))) + 1 if decl.group(2) else (None if decl.group(1) else 1) | |
| for name in re.split(r"\s*,\s*", decl.group(4).strip()): | |
| if re.fullmatch(r"[A-Za-z_]\w*", name or "") and name not in ("wire", "reg", "logic", "signed", "unsigned"): | |
| out.append((name, w)) | |
| seen, res = set(), [] | |
| for n, w in out: | |
| if n not in seen: | |
| seen.add(n); res.append((n, w)) | |
| return res | |
| return grab(r"\binput\b"), grab(r"\boutput\b") | |
| def _vcd_toggles(vcd_path: str, scope: str = "dut"): | |
| """Count 0<->1 bit transitions per variable of `scope` in a VCD file.""" | |
| vars_, cur, ids = {}, [], {} | |
| with open(vcd_path, errors="ignore") as f: | |
| lines = f.read().split("\n") | |
| k = 0 | |
| while k < len(lines): | |
| t = lines[k].split() | |
| if t[:1] == ["$scope"]: | |
| cur.append(t[2] if len(t) > 2 else "") | |
| elif t[:1] == ["$upscope"]: | |
| if cur: cur.pop() | |
| elif t[:1] == ["$var"] and cur and cur[-1] == scope and len(t) >= 5: | |
| width, code, name = int(t[2]), t[3], t[4] | |
| ids[code] = name | |
| vars_[name] = {"width": width, "toggles": 0, "bits_toggled": set()} | |
| elif t[:1] == ["$enddefinitions"]: | |
| k += 1 | |
| break | |
| k += 1 | |
| prev = {} | |
| for line in lines[k:]: | |
| if not line or line[0] in "#$": | |
| continue | |
| if line[0] in "01xzXZ": | |
| val, code = line[0], line[1:].strip() | |
| elif line[0] in "bB": | |
| parts = line[1:].split() | |
| if len(parts) != 2: | |
| continue | |
| val, code = parts | |
| else: | |
| continue | |
| if code not in ids: | |
| continue | |
| name = ids[code]; w = vars_[name]["width"] | |
| val = val.rjust(w, val[0] if val[0] in "xzXZ" else "0")[-w:] | |
| old = prev.get(code) | |
| if old is not None: | |
| for b, (o, n) in enumerate(zip(old, val)): | |
| if o in "01" and n in "01" and o != n: | |
| vars_[name]["toggles"] += 1 | |
| vars_[name]["bits_toggled"].add(b) | |
| prev[code] = val | |
| return vars_ | |
| def simulation_tool(verilog_code: str, num_cycles: int = 100, | |
| simulation_type: str = "functional") -> Dict[str, Any]: | |
| """ | |
| Simulate the design with Icarus Verilog and measure switching activity. | |
| A generated testbench drives a detected clock (one period per cycle), holds any | |
| detected reset active for the first two cycles, and drives the remaining inputs | |
| with random values every cycle (fixed seed). The waveform of the top-level design | |
| signals is dumped to a VCD file, and the toggle rate of every signal is measured as | |
| the number of 0<->1 bit transitions divided by (bit width x cycles). | |
| `coverage_estimate` is the toggle coverage: the percentage of signal bits that | |
| toggled at least once. If the design does not compile or the run does not | |
| complete, the result has status "error" and carries no activity figures. | |
| """ | |
| module_name = extract_module_name(verilog_code) or "top" | |
| inputs, outputs = _parse_ports(verilog_code, module_name) | |
| wires = re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code) | |
| regs = re.findall(r'reg\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code) | |
| activity = {"inputs": len(inputs), "outputs": len(outputs), "wires": len(wires), "regs": len(regs)} | |
| is_clk = lambda n: re.fullmatch(r"(?i)(a?clk\w*|\w*_clk|clock\w*|\w*_clock)", n) is not None | |
| is_rst = lambda n: re.search(r"(?i)(rst|reset)", n) is not None | |
| active_low = lambda n: re.search(r"(?i)(_n|_b|n)$", n) is not None | |
| def decl(kind, n, w): | |
| return f"{kind} {'' if not w or w == 1 else f'[{w-1}:0] '}{n};" | |
| clks = [n for n, _ in inputs if is_clk(n)] | |
| rsts = [n for n, _ in inputs if is_rst(n) and n not in clks] | |
| data = [(n, w) for n, w in inputs if n not in clks and n not in rsts] | |
| temp_dut = write_temp_verilog(verilog_code, suffix="_dut.v") | |
| temp_vvp = temp_dut.replace("_dut.v", ".vvp") | |
| temp_vcd = temp_dut.replace("_dut.v", ".vcd") | |
| tb = ["`timescale 1ns/1ps", f"module tb_{module_name};"] | |
| tb += [" " + decl("reg", n, w) for n, w in inputs] | |
| tb += [" " + decl("wire", n, w) for n, w in outputs] | |
| tb.append(f" {module_name} dut(" + ", ".join(f".{n}({n})" for n, _ in inputs + outputs) + ");") | |
| tb.append(" integer cycle_count; integer seed;") | |
| tb.append(" initial begin") | |
| tb.append(f' $dumpfile("{temp_vcd}"); $dumpvars(1, dut);') | |
| tb.append(" seed = 42; cycle_count = 0;") | |
| tb += [f" {n} = 0;" for n in clks] | |
| tb += [f" {n} = {0 if active_low(n) else 1};" for n in rsts] | |
| tb += [f" {n} = 0;" for n, _ in data] | |
| tb.append(f" repeat ({num_cycles}) begin") | |
| tb += [f" {n} = $random(seed);" for n, _ in data] | |
| if rsts: | |
| tb.append(" if (cycle_count == 2) begin " + " ".join(f"{n} = {1 if active_low(n) else 0};" for n in rsts) + " end") | |
| if clks: | |
| tb += [f" #5 {clks[0]} = 1;", f" #5 {clks[0]} = 0;"] | |
| else: | |
| tb.append(" #10;") | |
| tb.append(" cycle_count = cycle_count + 1;") | |
| tb.append(" end") | |
| tb.append(' $display("SIMULATION_COMPLETE"); $display("CYCLES: %0d", cycle_count); $finish;') | |
| tb.append(" end") | |
| tb.append("endmodule") | |
| temp_tb = write_temp_verilog("\n".join(tb) + "\n", suffix="_tb.v") | |
| def fail(msg): | |
| return asdict(SimulationResult(status="error", toggle_rates={}, simulation_cycles=0, assertion_results={}, | |
| coverage_estimate=0.0, signal_activity=activity, | |
| simulation_log=msg[:1000], error=msg[:300])) | |
| try: | |
| rc, out, err = run_with_conda(f"iverilog -g2012 -I{TOOLS_ROOT}/incdir -o {temp_vvp} {temp_dut} {temp_tb}", | |
| timeout=IVERILOG_TIMEOUT) | |
| if rc != 0: | |
| return fail(f"Compilation failed: {(err or out)[:500]}") | |
| rc, out, err = run_with_conda(f"vvp -n {temp_vvp}", timeout=IVERILOG_TIMEOUT) | |
| if "SIMULATION_COMPLETE" not in out or not os.path.exists(temp_vcd): | |
| return fail(f"Simulation did not complete: {(err or out)[-500:]}") | |
| m = re.search(r"CYCLES:\s*(\d+)", out) | |
| cycles = int(m.group(1)) if m else num_cycles | |
| v = _vcd_toggles(temp_vcd) | |
| if not v or not cycles: | |
| return fail("No waveform recorded for the design signals") | |
| rates = {n: round(d["toggles"] / (d["width"] * cycles), 3) for n, d in v.items()} | |
| bits = sum(d["width"] for d in v.values()) | |
| hit = sum(len(d["bits_toggled"]) for d in v.values()) | |
| activity["signals_recorded"] = len(v) | |
| activity["signals_toggling"] = sum(1 for d in v.values() if d["toggles"]) | |
| return asdict(SimulationResult(status="success", toggle_rates=dict(sorted(rates.items())[:200]), | |
| simulation_cycles=cycles, assertion_results={}, | |
| coverage_estimate=round(100.0 * hit / bits, 1) if bits else 0.0, | |
| signal_activity=activity, simulation_log=out[-1000:])) | |
| except Exception as e: | |
| return fail(f"Simulation error: {e}") | |
| finally: | |
| for p in (temp_dut, temp_tb, temp_vvp, temp_vcd): | |
| try: | |
| os.remove(p) | |
| except OSError: | |
| pass | |
| # ============================================================================ | |
| # Tool 3: Graph Extractor | |
| # ============================================================================ | |
| class GraphResult: | |
| """Result from graph_extractor.""" | |
| status: str | |
| graph_type: str | |
| nodes: List[Dict[str, Any]] | |
| edges: List[Dict[str, Any]] | |
| node_count: int | |
| edge_count: int | |
| graph_properties: Dict[str, Any] | |
| error: Optional[str] = None | |
| def graph_extractor(verilog_code: str, graph_type: str = "CDFG") -> Dict[str, Any]: | |
| """ | |
| Extract graph representation from Verilog code using Yosys. | |
| Args: | |
| verilog_code: Verilog source code | |
| graph_type: "CDFG", "AIG", "AST", or "DFG" | |
| Returns: | |
| Dict with nodes, edges, node_count, edge_count, graph_properties | |
| """ | |
| temp_file = write_temp_verilog(verilog_code) | |
| module_name = extract_module_name(verilog_code) or "top" | |
| temp_json = temp_file.replace(".v", ".json") | |
| try: | |
| # Build Yosys script based on graph type | |
| if graph_type == "AIG": | |
| # And-Inverter Graph | |
| yosys_script = f""" | |
| read_verilog -I{TOOLS_ROOT}/incdir {temp_file} | |
| hierarchy -top {module_name} | |
| proc; opt; techmap | |
| aigmap | |
| write_json {temp_json} | |
| stat | |
| """ | |
| elif graph_type == "AST": | |
| # Abstract Syntax Tree - use basic parsing | |
| yosys_script = f""" | |
| read_verilog -I{TOOLS_ROOT}/incdir {temp_file} | |
| hierarchy -top {module_name} | |
| write_json {temp_json} | |
| stat | |
| """ | |
| elif graph_type == "DFG": | |
| # Data Flow Graph | |
| yosys_script = f""" | |
| read_verilog -I{TOOLS_ROOT}/incdir {temp_file} | |
| hierarchy -top {module_name} | |
| proc; opt | |
| write_json {temp_json} | |
| stat | |
| """ | |
| else: # CDFG - Control/Data Flow Graph | |
| yosys_script = f""" | |
| read_verilog -I{TOOLS_ROOT}/incdir {temp_file} | |
| hierarchy -top {module_name} | |
| proc; opt; memory; opt | |
| write_json {temp_json} | |
| stat | |
| """ | |
| # Run Yosys | |
| yosys_cmd = f"yosys -p '{yosys_script}' 2>&1" | |
| returncode, stdout, stderr = run_with_conda(yosys_cmd, timeout=YOSYS_TIMEOUT) | |
| if returncode != 0 or not os.path.exists(temp_json): | |
| return asdict(GraphResult( | |
| status="error", | |
| graph_type=graph_type, | |
| nodes=[], edges=[], | |
| node_count=0, edge_count=0, | |
| graph_properties={}, | |
| error=f"Yosys failed: {stderr[:500]}" | |
| )) | |
| # Parse JSON output | |
| with open(temp_json, 'r') as f: | |
| yosys_json = json.load(f) | |
| # Extract nodes and edges from Yosys JSON format | |
| nodes = [] | |
| edges = [] | |
| if 'modules' in yosys_json: | |
| for mod_name, mod_data in yosys_json['modules'].items(): | |
| # Extract cells as nodes | |
| if 'cells' in mod_data: | |
| for cell_name, cell_data in mod_data['cells'].items(): | |
| nodes.append({ | |
| 'id': cell_name, | |
| 'type': cell_data.get('type', 'unknown'), | |
| 'attributes': cell_data.get('attributes', {}), | |
| 'parameters': cell_data.get('parameters', {}) | |
| }) | |
| # Extract connections as edges | |
| if 'connections' in cell_data: | |
| for port, signals in cell_data['connections'].items(): | |
| for sig in signals if isinstance(signals, list) else [signals]: | |
| edges.append({ | |
| 'source': cell_name, | |
| 'target': str(sig), | |
| 'port': port | |
| }) | |
| # Extract ports as nodes | |
| if 'ports' in mod_data: | |
| for port_name, port_data in mod_data['ports'].items(): | |
| nodes.append({ | |
| 'id': port_name, | |
| 'type': f"port_{port_data.get('direction', 'unknown')}", | |
| 'bits': port_data.get('bits', []) | |
| }) | |
| # Calculate graph properties | |
| node_types = {} | |
| for node in nodes: | |
| t = node.get('type', 'unknown') | |
| node_types[t] = node_types.get(t, 0) + 1 | |
| return asdict(GraphResult( | |
| status="success", | |
| graph_type=graph_type, | |
| nodes=nodes[:100], # Limit for large designs | |
| edges=edges[:200], | |
| node_count=len(nodes), | |
| edge_count=len(edges), | |
| graph_properties={ | |
| 'node_types': node_types, | |
| 'avg_degree': round(len(edges) / max(len(nodes), 1), 2), | |
| 'module_name': module_name | |
| } | |
| )) | |
| finally: | |
| for f in [temp_file, temp_json]: | |
| if os.path.exists(f): | |
| os.remove(f) | |
| # ============================================================================ | |
| # Tool 4: Static Analyzer (Enhanced version) | |
| # ============================================================================ | |
| class StaticAnalysisResult: | |
| """Result from static_analyzer.""" | |
| status: str | |
| module_name: str | |
| port_count: Dict[str, int] | |
| signal_count: Dict[str, int] | |
| always_blocks: int | |
| assign_statements: int | |
| instantiations: List[str] | |
| code_complexity: Dict[str, Any] | |
| lint_warnings: List[str] | |
| error: Optional[str] = None | |
| def static_analyzer(verilog_code: str, analysis_type: str = "full") -> Dict[str, Any]: | |
| """ | |
| Perform static code analysis on Verilog code. | |
| Args: | |
| verilog_code: Verilog source code | |
| analysis_type: "full", "ports", "complexity", or "lint" | |
| Returns: | |
| Dict with module_name, port_count, signal_count, always_blocks, etc. | |
| """ | |
| module_name = extract_module_name(verilog_code) or "unknown" | |
| # Count ports | |
| inputs = re.findall(r'input\s+(?:wire\s+)?(?:reg\s+)?(?:\[\d+:\d+\])?\s*(\w+)', verilog_code) | |
| outputs = re.findall(r'output\s+(?:wire\s+)?(?:reg\s+)?(?:\[\d+:\d+\])?\s*(\w+)', verilog_code) | |
| inouts = re.findall(r'inout\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code) | |
| # Count signals | |
| wires = re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code) | |
| regs = re.findall(r'reg\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code) | |
| params = re.findall(r'parameter\s+(\w+)', verilog_code) | |
| localparam = re.findall(r'localparam\s+(\w+)', verilog_code) | |
| # Count blocks | |
| always_blocks = len(re.findall(r'always\s*@', verilog_code)) | |
| always_comb = len(re.findall(r'always_comb', verilog_code)) | |
| always_ff = len(re.findall(r'always_ff', verilog_code)) | |
| assign_stmts = len(re.findall(r'\bassign\s+', verilog_code)) | |
| # Find instantiations | |
| instantiations = re.findall(r'(\w+)\s+\w+\s*\(', verilog_code) | |
| # Filter out keywords | |
| keywords = {'module', 'function', 'task', 'if', 'else', 'case', 'for', 'while', 'begin', 'end'} | |
| instantiations = [i for i in instantiations if i not in keywords and not i.startswith('$')] | |
| # Calculate complexity metrics | |
| lines = verilog_code.split('\n') | |
| code_lines = [l for l in lines if l.strip() and not l.strip().startswith('//')] | |
| # Cyclomatic complexity estimate | |
| branches = len(re.findall(r'\b(if|else|case|for|while)\b', verilog_code)) | |
| # Lint warnings | |
| lint_warnings = [] | |
| # Check for blocking assignments in sequential blocks | |
| if re.search(r'always\s*@\s*\(\s*posedge.*=(?!=)', verilog_code): | |
| lint_warnings.append("Potential blocking assignment in sequential block") | |
| # Check for latches (incomplete if/case) | |
| if re.search(r'always\s*@\s*\*', verilog_code): | |
| if not re.search(r'else\b', verilog_code): | |
| lint_warnings.append("Combinational block may infer latch (missing else)") | |
| # Check for unused signals (simplified) | |
| all_signals = set(wires + regs) | |
| used_signals = set(re.findall(r'\b(\w+)\b', verilog_code)) | |
| return asdict(StaticAnalysisResult( | |
| status="success", | |
| module_name=module_name, | |
| port_count={ | |
| 'inputs': len(inputs), | |
| 'outputs': len(outputs), | |
| 'inouts': len(inouts), | |
| 'total': len(inputs) + len(outputs) + len(inouts) | |
| }, | |
| signal_count={ | |
| 'wires': len(wires), | |
| 'regs': len(regs), | |
| 'parameters': len(params) + len(localparam), | |
| 'total': len(wires) + len(regs) | |
| }, | |
| always_blocks=always_blocks + always_comb + always_ff, | |
| assign_statements=assign_stmts, | |
| instantiations=list(set(instantiations))[:20], | |
| code_complexity={ | |
| 'lines_of_code': len(code_lines), | |
| 'total_lines': len(lines), | |
| 'cyclomatic_complexity': branches + 1, | |
| 'nesting_depth': verilog_code.count('begin'), | |
| 'operator_count': len(re.findall(r'[+\-*/&|^~<>=]', verilog_code)) | |
| }, | |
| lint_warnings=lint_warnings[:10] | |
| )) | |
| # ============================================================================ | |
| # Tool 5: Optimization Advisor | |
| # ============================================================================ | |
| class OptimizationResult: | |
| """Result from optimization_advisor.""" | |
| status: str | |
| target_metric: str | |
| recommended_recipes: List[str] | |
| optimization_suggestions: List[Dict[str, Any]] | |
| estimated_improvement: Dict[str, float] | |
| trade_offs: List[str] | |
| error: Optional[str] = None | |
| # Synthesis recipes for different optimization targets | |
| SYNTHESIS_RECIPES = { | |
| 'area': [ | |
| "synth -top {module} -flatten", | |
| "opt -full; share -aggressive; opt", | |
| "abc -g gates -liberty {lib}", | |
| "opt_clean -purge" | |
| ], | |
| 'delay': [ | |
| "synth -top {module}", | |
| "opt -fast", | |
| "abc -fast -liberty {lib}", | |
| "opt_clean" | |
| ], | |
| 'power': [ | |
| "synth -top {module}", | |
| "opt; share; opt", | |
| "abc -g gates -liberty {lib}", | |
| "opt_clean; clockgate" | |
| ], | |
| 'balanced': [ | |
| "synth -top {module}", | |
| "opt; techmap; opt", | |
| "abc -liberty {lib}", | |
| "opt_clean" | |
| ] | |
| } | |
| def optimization_advisor(verilog_code: str, target_metric: str = "area", | |
| constraints: Dict[str, Any] = None) -> Dict[str, Any]: | |
| """ | |
| Provide optimization recommendations for Verilog code. | |
| Args: | |
| verilog_code: Verilog source code | |
| target_metric: "area", "delay", "power", or "balanced" | |
| constraints: Optional timing/area constraints | |
| Returns: | |
| Dict with recommended_recipes, optimization_suggestions, estimated_improvement | |
| """ | |
| module_name = extract_module_name(verilog_code) or "top" | |
| # Analyze code patterns | |
| has_memories = bool(re.search(r'reg\s*\[\d+:\d+\]\s*\w+\s*\[\d+:\d+\]', verilog_code)) | |
| has_fsm = bool(re.search(r'case\s*\(.*state', verilog_code, re.IGNORECASE)) | |
| has_arithmetic = bool(re.search(r'[+\-*/]', verilog_code)) | |
| has_mux = bool(re.search(r'\?.*:', verilog_code)) or bool(re.search(r'case\s*\(', verilog_code)) | |
| # Count complexity indicators | |
| always_count = len(re.findall(r'always\s*@', verilog_code)) | |
| reg_count = len(re.findall(r'\breg\b', verilog_code)) | |
| # Build recommendations | |
| suggestions = [] | |
| trade_offs = [] | |
| estimated_improvement = {} | |
| if target_metric == "area": | |
| if has_memories: | |
| suggestions.append({ | |
| 'type': 'memory_optimization', | |
| 'description': 'Consider using memory inference for large arrays', | |
| 'command': 'memory -nomap; memory_bram' | |
| }) | |
| if has_mux: | |
| suggestions.append({ | |
| 'type': 'mux_optimization', | |
| 'description': 'Share multiplexers where possible', | |
| 'command': 'muxcover; opt' | |
| }) | |
| if has_arithmetic: | |
| suggestions.append({ | |
| 'type': 'resource_sharing', | |
| 'description': 'Share arithmetic operators', | |
| 'command': 'share -aggressive' | |
| }) | |
| estimated_improvement = {'area': -15.0, 'delay': 5.0, 'power': -10.0} | |
| trade_offs = ["Area optimization may increase delay", "Aggressive sharing increases routing complexity"] | |
| elif target_metric == "delay": | |
| if has_arithmetic: | |
| suggestions.append({ | |
| 'type': 'pipeline_insertion', | |
| 'description': 'Consider pipelining arithmetic operations', | |
| 'command': 'Use register retiming' | |
| }) | |
| if has_fsm: | |
| suggestions.append({ | |
| 'type': 'fsm_encoding', | |
| 'description': 'Use one-hot encoding for faster FSM', | |
| 'command': 'fsm_opt; fsm_recode -encoding one-hot' | |
| }) | |
| suggestions.append({ | |
| 'type': 'logic_duplication', | |
| 'description': 'Duplicate logic to reduce fanout', | |
| 'command': 'splitnets -driver' | |
| }) | |
| estimated_improvement = {'area': 10.0, 'delay': -20.0, 'power': 5.0} | |
| trade_offs = ["Speed optimization increases area", "Higher power consumption"] | |
| elif target_metric == "power": | |
| suggestions.append({ | |
| 'type': 'clock_gating', | |
| 'description': 'Insert clock gating for registers', | |
| 'command': 'clockgate' | |
| }) | |
| if has_memories: | |
| suggestions.append({ | |
| 'type': 'memory_banking', | |
| 'description': 'Bank memories to reduce active area', | |
| 'command': 'memory_share' | |
| }) | |
| suggestions.append({ | |
| 'type': 'operand_isolation', | |
| 'description': 'Isolate operands when not in use', | |
| 'command': 'Use enable signals for arithmetic' | |
| }) | |
| estimated_improvement = {'area': 5.0, 'delay': 5.0, 'power': -25.0} | |
| trade_offs = ["Power optimization may add area overhead", "Clock gating adds timing complexity"] | |
| else: # balanced | |
| suggestions.append({ | |
| 'type': 'balanced_optimization', | |
| 'description': 'Use default synthesis flow', | |
| 'command': 'synth -top {module}' | |
| }) | |
| estimated_improvement = {'area': -5.0, 'delay': -5.0, 'power': -5.0} | |
| trade_offs = ["Balanced approach may not achieve best results in any single metric"] | |
| # Get recipes | |
| recipes = SYNTHESIS_RECIPES.get(target_metric, SYNTHESIS_RECIPES['balanced']) | |
| recipes = [r.format(module=module_name, lib="stdcells.lib") for r in recipes] | |
| return asdict(OptimizationResult( | |
| status="success", | |
| target_metric=target_metric, | |
| recommended_recipes=recipes, | |
| optimization_suggestions=suggestions, | |
| estimated_improvement=estimated_improvement, | |
| trade_offs=trade_offs | |
| )) | |
| # ============================================================================ | |
| # Tool 6: Cross-Stage Mapper | |
| # ============================================================================ | |
| class CrossStageResult: | |
| """Result from cross_stage_mapper.""" | |
| status: str | |
| rtl_to_netlist_mapping: Dict[str, List[str]] | |
| alignment_score: float | |
| unmapped_elements: List[str] | |
| mapping_statistics: Dict[str, Any] | |
| error: Optional[str] = None | |
| def cross_stage_mapper(rtl_code: str, netlist_code: str = None) -> Dict[str, Any]: | |
| """ | |
| Map RTL signals to netlist elements. | |
| If netlist_code is not provided, synthesizes the RTL to generate netlist. | |
| Args: | |
| rtl_code: RTL Verilog source code | |
| netlist_code: Optional synthesized netlist code | |
| Returns: | |
| Dict with rtl_to_netlist_mapping, alignment_score, unmapped_elements | |
| """ | |
| module_name = extract_module_name(rtl_code) or "top" | |
| # Extract RTL signals | |
| rtl_inputs = set(re.findall(r'input\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code)) | |
| rtl_outputs = set(re.findall(r'output\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code)) | |
| rtl_wires = set(re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code)) | |
| rtl_regs = set(re.findall(r'reg\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code)) | |
| all_rtl_signals = rtl_inputs | rtl_outputs | rtl_wires | rtl_regs | |
| # If no netlist provided, synthesize to get one | |
| if netlist_code is None: | |
| temp_file = write_temp_verilog(rtl_code) | |
| temp_netlist = temp_file.replace(".v", "_netlist.v") | |
| try: | |
| yosys_script = f""" | |
| read_verilog -I{TOOLS_ROOT}/incdir {temp_file} | |
| hierarchy -top {module_name} | |
| proc; opt; techmap | |
| abc -g gates | |
| write_verilog {temp_netlist} | |
| """ | |
| yosys_cmd = f"yosys -p '{yosys_script}' 2>&1" | |
| returncode, stdout, stderr = run_with_conda(yosys_cmd, timeout=YOSYS_TIMEOUT) | |
| if returncode == 0 and os.path.exists(temp_netlist): | |
| with open(temp_netlist, 'r') as f: | |
| netlist_code = f.read() | |
| else: | |
| netlist_code = "" | |
| finally: | |
| for f in [temp_file, temp_netlist]: | |
| if os.path.exists(f): | |
| os.remove(f) | |
| if not netlist_code: | |
| # synthesis produced no netlist: there is nothing to map against | |
| return asdict(CrossStageResult( | |
| status="error", rtl_to_netlist_mapping={}, alignment_score=0.0, unmapped_elements=[], | |
| mapping_statistics={'rtl_signals': len(all_rtl_signals)}, | |
| error="Synthesis did not produce a netlist")) | |
| # Extract netlist signals | |
| netlist_wires = set(re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', netlist_code)) if netlist_code else set() | |
| netlist_cells = re.findall(r'(\$\w+)\s+\w+\s*\(', netlist_code) if netlist_code else [] | |
| # Build mapping | |
| mapping = {} | |
| mapped_count = 0 | |
| for rtl_sig in all_rtl_signals: | |
| # Find matching netlist signals (exact or partial match) | |
| matches = [] | |
| for net_sig in netlist_wires: | |
| if rtl_sig in net_sig or net_sig.startswith(rtl_sig): | |
| matches.append(net_sig) | |
| if matches: | |
| mapping[rtl_sig] = matches[:5] # Limit matches | |
| mapped_count += 1 | |
| else: | |
| mapping[rtl_sig] = [] | |
| # Calculate alignment score | |
| total_signals = len(all_rtl_signals) | |
| alignment_score = (mapped_count / total_signals * 100) if total_signals > 0 else 0.0 | |
| # Find unmapped elements | |
| unmapped = [sig for sig, matches in mapping.items() if not matches] | |
| return asdict(CrossStageResult( | |
| status="success", | |
| rtl_to_netlist_mapping=mapping, | |
| alignment_score=round(alignment_score, 2), | |
| unmapped_elements=unmapped[:20], | |
| mapping_statistics={ | |
| 'rtl_signals': len(all_rtl_signals), | |
| 'netlist_wires': len(netlist_wires), | |
| 'netlist_cells': len(set(netlist_cells)), | |
| 'mapped_signals': mapped_count, | |
| 'unmapped_signals': len(unmapped) | |
| } | |
| )) | |
| # ============================================================================ | |
| # Tool Registry and Dispatcher | |
| # ============================================================================ | |
| TOOL_REGISTRY = { | |
| 'synthesis_tool': synthesis_tool, | |
| 'simulation_tool': simulation_tool, | |
| 'graph_extractor': graph_extractor, | |
| 'static_analyzer': static_analyzer, | |
| 'optimization_advisor': optimization_advisor, | |
| 'cross_stage_mapper': cross_stage_mapper | |
| } | |
| def execute_tool(tool_name: str, verilog_code: str, **kwargs) -> Dict[str, Any]: | |
| """ | |
| Execute a tool by name with the given parameters. | |
| Args: | |
| tool_name: Name of the tool to execute | |
| verilog_code: Verilog source code | |
| **kwargs: Additional tool-specific parameters | |
| Returns: | |
| Tool result as a dictionary | |
| """ | |
| if tool_name not in TOOL_REGISTRY: | |
| return {'status': 'error', 'error': f'Unknown tool: {tool_name}'} | |
| tool_func = TOOL_REGISTRY[tool_name] | |
| try: | |
| if tool_name == 'cross_stage_mapper': | |
| return tool_func(verilog_code, kwargs.get('netlist_code')) | |
| else: | |
| return tool_func(verilog_code, **kwargs) | |
| except Exception as e: | |
| return {'status': 'error', 'error': str(e)} | |
| # ============================================================================ | |
| # Test Function | |
| # ============================================================================ | |
| def test_all_tools(): | |
| """Test all tools with a simple Verilog module.""" | |
| test_code = """ | |
| module counter( | |
| input clk, | |
| input rst, | |
| input enable, | |
| output reg [7:0] count | |
| ); | |
| always @(posedge clk or posedge rst) begin | |
| if (rst) | |
| count <= 8'b0; | |
| else if (enable) | |
| count <= count + 1; | |
| end | |
| endmodule | |
| """ | |
| print("=" * 60) | |
| print("Testing EDA Tool Suite") | |
| print("=" * 60) | |
| for tool_name in TOOL_REGISTRY: | |
| print(f"\n--- Testing {tool_name} ---") | |
| try: | |
| result = execute_tool(tool_name, test_code) | |
| print(f"Status: {result.get('status', 'unknown')}") | |
| if result.get('status') == 'error': | |
| print(f"Error: {result.get('error', 'unknown')}") | |
| else: | |
| # Print key metrics | |
| for key in ['gate_count', 'node_count', 'alignment_score', 'module_name']: | |
| if key in result: | |
| print(f" {key}: {result[key]}") | |
| except Exception as e: | |
| print(f"Exception: {e}") | |
| print("\n" + "=" * 60) | |
| print("Tool Suite Test Complete") | |
| print("=" * 60) | |
| if __name__ == "__main__": | |
| test_all_tools() |