Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ the `--benchmark-dir` flag. Results land in `bench-results.json` in
| `--stdout` | off | Also print results to stdout |
| `--pipeline P` | (all) | `evmasm`/`ir`/`ir-ssacfg`/`ir-ethdebug` |
| `--no-optimize` | off | Disable the optimizer |
| `--yul-optimizations STEPS` | solc's default | Yul optimizer step sequence for every pipeline (`STEPS` or `STEPS:CLEANUP_STEPS`). Recorded in the result file; skips forge gas |
| `--evmone PATH` | (none) | Replay [mainnet gas fixtures](#mainnet-gas-fixtures) against the compiled bytecode |

```bash
Expand All @@ -112,6 +113,15 @@ solc-bench run --solc ./solc contract.sol --pipeline ir # single file
solc-bench run --solc ./solc --benchmark-dir ./benchmark_data --evmone ./evmone # + gas-fixture replay
```

To measure a Yul optimizer step sequence, run the same binary twice and compare the result files:

```bash
solc-bench run --solc ./solc --benchmark-dir ./benchmark_data --pipeline ir -o default.json
solc-bench run --solc ./solc --benchmark-dir ./benchmark_data --pipeline ir -o sequence.json \
--yul-optimizations 'dhfoDgvulfnTUtnIf [xa[r]EscLMVcul] jmul:fDnTOcmu'
solc-bench compare default.json sequence.json
```

### `solc-bench compare`

Compares two result files, or two pipelines in one file (`--pipelines TARGET:REF`).
Expand Down
22 changes: 18 additions & 4 deletions src/solc_bench/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ def __init__(
keep_inputs=False,
output_file=None,
evmone=None,
yul_optimizations=None,
):
self.solc_version = get_solc_version(solc)
self.benchmark = Benchmark(solc)
Expand All @@ -205,6 +206,8 @@ def __init__(
self.keep_inputs = keep_inputs
# Path to evmone, or None to skip gas-fixture benchmarking.
self.evmone = evmone
# Yul optimizer step sequence for every pipeline, or None for solc's default.
self.yul_optimizations = yul_optimizations
self.results = {}

@property
Expand Down Expand Up @@ -246,6 +249,9 @@ def _run_gas(self, result, project_dir, name, pipeline, solc_settings):
if pipeline == "ir-ssacfg":
# TODO: forge doesn't support --viaSSACFG yet, skip gas for ir-ssacfg
return
if self.yul_optimizations is not None:
# forge compiles the project with its own settings, without the given sequence.
return
via_ir = solc_settings.get("viaIR", False)
log_path = self.output_dir / f"{name}-{pipeline}.gas.log"
log_path.parent.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -353,7 +359,9 @@ def run_file(self, input_file, pipelines, no_optimize):
pipelines is a list of pipeline names, or None for all pipelines.
"""
name = Path(input_file).stem
pipeline_runs = self._pipeline_runs(pipelines or DEFAULT_PIPELINES, no_optimize)
pipeline_runs = self._pipeline_runs(
pipelines or DEFAULT_PIPELINES, no_optimize, self.yul_optimizations
)

for label, solc_settings, ethdebug in pipeline_runs:
if input_file.endswith(".sol"):
Expand Down Expand Up @@ -425,6 +433,7 @@ def run_suite(
for label, solc_settings, ethdebug in self._pipeline_runs(
bench_pipelines,
no_optimize,
self.yul_optimizations,
):
pipeline_gas_fixtures = None if ethdebug else gas_fixtures
if pipeline_gas_fixtures is not None:
Expand All @@ -451,7 +460,7 @@ def run_suite(
)

@staticmethod
def _pipeline_runs(pipelines, no_optimize):
def _pipeline_runs(pipelines, no_optimize, yul_optimizations=None):
runs = []
for pipeline in pipelines:
if pipeline == "ir-ethdebug":
Expand All @@ -460,15 +469,19 @@ def _pipeline_runs(pipelines, no_optimize):
runs.append(
(
pipeline,
resolve_solc_settings("ir", no_optimize, ethdebug=True),
resolve_solc_settings(
"ir", no_optimize, ethdebug=True, yul_optimizations=yul_optimizations
),
True,
)
)
else:
runs.append(
(
pipeline,
resolve_solc_settings(pipeline, no_optimize),
resolve_solc_settings(
pipeline, no_optimize, yul_optimizations=yul_optimizations
),
False,
)
)
Expand All @@ -485,6 +498,7 @@ def write_results(self, stdout=False):
solc_version=self.solc_version,
timestamp=datetime.now(timezone.utc).isoformat(timespec="seconds"),
iterations=self.iterations,
yul_optimizations=self.yul_optimizations,
hardware=host.hardware(),
environment=host.environment(),
results=self.results,
Expand Down
13 changes: 13 additions & 0 deletions src/solc_bench/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,12 @@ def cmd_run(args):
keep_inputs=args.keep_inputs,
output_file=args.output_file,
evmone=args.evmone,
yul_optimizations=args.yul_optimizations,
)
print(f"solc: {suite.solc_version}", file=sys.stderr)
print(f"iterations: {args.iterations}", file=sys.stderr)
if args.yul_optimizations is not None:
print(f"Yul optimizations: {args.yul_optimizations}", file=sys.stderr)
perf_str = (
"available (using hardware counters)"
if suite.use_perf
Expand Down Expand Up @@ -417,6 +420,16 @@ def build_parser():
default=False,
help="Disable optimizer (default: optimizer enabled)",
)
run_parser.add_argument(
"--yul-optimizations",
default=None,
metavar="STEPS",
help=(
"Yul optimizer step sequence for every pipeline, as for solc's "
"--yul-optimizations: 'STEPS' or 'STEPS:CLEANUP_STEPS' "
"(default: solc's default sequence). Skips forge gas"
),
)
run_parser.add_argument(
"--keep-inputs",
action="store_true",
Expand Down
1 change: 1 addition & 0 deletions src/solc_bench/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ def to_json(self) -> dict[str, Any]:
"solc_version": self.run.solc_version,
"timestamp": self.run.timestamp,
"iterations": self.run.iterations,
"yul_optimizations": self.run.yul_optimizations,
"ref_pipeline": self.ref_pipeline,
"target_pipeline": self.target_pipeline,
"benchmarks": {name: c.to_json("ref") for name, c in self.benchmarks.items()},
Expand Down
5 changes: 5 additions & 0 deletions src/solc_bench/reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ def cross_version_table(result: CrossVersionComparison):
target = result.target
print(f"Baseline: {baseline.solc_version}{_iterations_suffix(baseline)}")
print(f"Target: {target.solc_version}{_iterations_suffix(target)}")
for role, run_info in (("Baseline", baseline), ("Target", target)):
if run_info.yul_optimizations is not None:
print(f"{role} Yul optimizations: {run_info.yul_optimizations}")
print(
"Values are mean \u00b1 sample stddev. \u0394% = "
"(target mean - baseline mean) / baseline mean. Negative = "
Expand Down Expand Up @@ -295,6 +298,8 @@ def cross_pipeline_table(result: CrossPipelineComparison):
print(f"timestamp: {result.run.timestamp}")
if result.run.iterations is not None:
print(f"iterations: {result.run.iterations}")
if result.run.yul_optimizations is not None:
print(f"Yul optimizations: {result.run.yul_optimizations}")
print(
f"Pipeline comparison: {result.target_pipeline} vs "
f"{result.ref_pipeline}"
Expand Down
2 changes: 2 additions & 0 deletions src/solc_bench/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ class RunInfo(BaseModel):
solc_version: str = "unknown"
timestamp: str = ""
iterations: int | None = None
# Yul optimizer step sequence given with --yul-optimizations; None: solc's default.
yul_optimizations: str | None = None
hardware: dict[str, Any] = {}
environment: dict[str, Any] = {}

Expand Down
10 changes: 8 additions & 2 deletions src/solc_bench/solidity.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
from solc_bench.config import PIPELINE_CONFIGS


def resolve_solc_settings(pipeline, no_optimize, ethdebug=False):
"""Build solc_settings for a pipeline, applying --no-optimize if set."""
def resolve_solc_settings(pipeline, no_optimize, ethdebug=False, yul_optimizations=None):
"""Build solc_settings for a pipeline, applying --no-optimize or --yul-optimizations if set."""
solc_settings = copy.deepcopy(PIPELINE_CONFIGS[pipeline]["solc_settings"])
if yul_optimizations is not None and no_optimize:
raise ValueError("--yul-optimizations cannot be combined with --no-optimize")
if ethdebug:
if pipeline != "ir":
raise ValueError("ETHDebug output is only supported with the IR pipeline")
Expand All @@ -22,6 +24,10 @@ def resolve_solc_settings(pipeline, no_optimize, ethdebug=False):
solc_settings["experimental"] = True
if no_optimize:
solc_settings["optimizer"] = {"enabled": False}
if yul_optimizations is not None:
solc_settings["optimizer"]["details"] = {
"yulDetails": {"optimizerSteps": yul_optimizations}
}
solc_settings.setdefault("metadata", {}).update({
"bytecodeHash": "none",
"appendCBOR": False,
Expand Down
36 changes: 35 additions & 1 deletion tests/test_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,38 @@ def test_run_ethdebug_requires_no_optimize(cli, solc, contract, tmp_path):
assert "--no-optimize" in proc.stderr


def test_run_yul_optimizations(cli, solc, contract, tmp_path):
steps = "dhfoDgvulfnTUtnIf [xa[r]EscLMVcul] jmul:fDnTOcmu"
out = tmp_path / "sequence.json"
cli(
"run", "--solc", solc, "--iterations", "1", "--pipeline", "ir",
"--yul-optimizations", steps, "--keep-inputs",
"--output-dir", tmp_path, "-o", out, contract,
)
data = load_json(out)
assert data["yul_optimizations"] == steps
assert_metric(data["results"]["Counter"]["ir"], "creation_size")
optimizer = load_json(tmp_path / "inputs" / "Counter.ir.json")["settings"]["optimizer"]
assert optimizer["enabled"] is True
assert optimizer["details"]["yulDetails"]["optimizerSteps"] == steps


def test_run_without_yul_optimizations_records_none(cli, solc, contract, tmp_path):
out = tmp_path / "default.json"
cli("run", "--solc", solc, "--iterations", "1", "--pipeline", "ir", "-o", out, contract)
assert "yul_optimizations" not in load_json(out)


def test_run_yul_optimizations_rejects_no_optimize(cli, solc, contract, tmp_path):
proc = cli(
"run", "--solc", solc, "--pipeline", "ir", "--no-optimize",
"--yul-optimizations", "dhfoDgvulfnTUtnIf", "-o", tmp_path / "x.json", contract,
check=False,
)
assert proc.returncode == 1
assert "--yul-optimizations cannot be combined with --no-optimize" in proc.stderr


def test_run_refuses_to_overwrite_results(cli, solc, contract, tmp_path):
out = tmp_path / "existing.json"
out.write_text("{}", encoding="utf-8")
Expand Down Expand Up @@ -339,7 +371,9 @@ def test_compare_cross_version(cli, two_runs, tmp_path):

result = load_json(cmp_json)
assert result["mode"] == "cross-version"
run_info = {"solc_version", "timestamp", "iterations", "hardware", "environment"}
run_info = {
"solc_version", "timestamp", "iterations", "yul_optimizations", "hardware", "environment",
}
assert set(result["baseline"]) == set(result["target"]) == run_info
assert set(result["benchmarks"]["Counter"]) == {"evmasm", "ir"}
comparison = result["benchmarks"]["Counter"]["evmasm"]
Expand Down