From a50affba1afa11cbd0b4a656dc5a753fc5be0137 Mon Sep 17 00:00:00 2001 From: Matheus Aguiar Date: Thu, 18 Dec 2025 12:36:09 -0300 Subject: [PATCH 01/73] Set version to 0.8.34 --- CMakeLists.txt | 2 +- Changelog.md | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5792563eb3c0..82afc5b67d3a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,7 @@ include(EthPolicy) eth_policy() # project name and version should be set after cmake_policy CMP0048 -set(PROJECT_VERSION "0.8.33") +set(PROJECT_VERSION "0.8.34") # OSX target needed in order to support std::visit set(CMAKE_OSX_DEPLOYMENT_TARGET "10.14") project(solidity VERSION ${PROJECT_VERSION} LANGUAGES C CXX) diff --git a/Changelog.md b/Changelog.md index cb78695bc5e3..655e66e5418a 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,12 @@ +### 0.8.34 (unreleased) + +Language Features: + +Compiler Features: + +Bugfixes: + + ### 0.8.33 (2025-12-18) Bugfixes: From 779f590beb82d11e39dcec821507fb4d4b660c60 Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Thu, 18 Dec 2025 00:19:12 -0300 Subject: [PATCH 02/73] Add Constantinople EVM version requirement to long byte array cleanup test due to the use of shl --- .../array/long_byte_array_cleanup_after_overwrite_with_long.sol | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/libsolidity/semanticTests/array/long_byte_array_cleanup_after_overwrite_with_long.sol b/test/libsolidity/semanticTests/array/long_byte_array_cleanup_after_overwrite_with_long.sol index edb00809bcd3..c796881c4c25 100644 --- a/test/libsolidity/semanticTests/array/long_byte_array_cleanup_after_overwrite_with_long.sol +++ b/test/libsolidity/semanticTests/array/long_byte_array_cleanup_after_overwrite_with_long.sol @@ -82,6 +82,8 @@ contract C { return result; } } +// ==== +// EVMVersion: >=constantinople // ---- // arrayLength() ->0 // canaryValue() -> 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff From 7e371ddc0561033ccca7ffa1cee8f29ffee12ab5 Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Sun, 21 Dec 2025 17:06:57 -0300 Subject: [PATCH 03/73] Enables pipefail globally so parsing errors fail CI instead of being silently ignored --- scripts/externalTests/common.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/externalTests/common.sh b/scripts/externalTests/common.sh index 0465a4fec5f1..c6f5ef6d39f5 100644 --- a/scripts/externalTests/common.sh +++ b/scripts/externalTests/common.sh @@ -18,7 +18,7 @@ # # (c) 2019 solidity contributors. #------------------------------------------------------------------------------ -set -e +set -eo pipefail # Requires $REPO_ROOT to be defined and "${REPO_ROOT}/scripts/common.sh" to be included before. From e882f5343565183a3b290e60df2f9b7ce907d6b4 Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Sun, 21 Dec 2025 17:07:15 -0300 Subject: [PATCH 04/73] Fix external tests for hardhat-gas-reporter v2 compatibility --- scripts/externalTests/common.sh | 4 ++-- scripts/externalTests/parse_eth_gas_report.py | 17 +++++++++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/scripts/externalTests/common.sh b/scripts/externalTests/common.sh index c6f5ef6d39f5..7e480343acc3 100644 --- a/scripts/externalTests/common.sh +++ b/scripts/externalTests/common.sh @@ -434,9 +434,9 @@ function eth_gas_reporter_settings echo " enabled: true," echo " gasPrice: 1," # Gas price does not matter to us at all. Set to whatever to avoid API call. echo " noColors: true," - echo " showTimeSpent: false," # We're not interested in test timing - echo " onlyCalledMethods: true," # Exclude entries with no gas for shorter report + echo " showUncalledMethods: false," # Exclude entries with no gas for shorter report echo " showMethodSig: true," # Should make diffs more stable if there are overloaded functions + echo " reportFormat: 'legacy'," # Use v1.x format for compatibility with parse_eth_gas_report.py echo " outputFile: \"$(gas_report_path "$preset")\"" echo "}" } diff --git a/scripts/externalTests/parse_eth_gas_report.py b/scripts/externalTests/parse_eth_gas_report.py index ea8cbba66a6e..d7dbe45fa8c8 100755 --- a/scripts/externalTests/parse_eth_gas_report.py +++ b/scripts/externalTests/parse_eth_gas_report.py @@ -10,8 +10,8 @@ REPORT_HEADER_REGEX = re.compile(r''' ^[|\s]+ Solc[ ]version:\s*(?P[\w\d.]+) [|\s]+ Optimizer[ ]enabled:\s*(?P[\w]+) - [|\s]+ Runs:\s*(?P[\d]+) - [|\s]+ Block[ ]limit:\s*(?P[\d]+)\s*gas + [|\s]+ Runs:\s*(?P[\d,]+) + [|\s]+ Block[ ]limit:\s*(?P[\d,]+)\s*gas [|\s]+$ ''', re.VERBOSE) METHOD_HEADER_REGEX = re.compile(r'^[|\s]+Methods[|\s]+$') @@ -122,10 +122,11 @@ def parse_bool(input_string: str) -> bool: def parse_optional_int(input_string: str, default: Optional[int] = None) -> Optional[int]: - if input_string.strip() == '-': + stripped = input_string.strip().replace(',', '') + if stripped == '-': return default - return int(input_string) + return int(stripped) def parse_report_header(line: str) -> Optional[dict]: @@ -136,8 +137,8 @@ def parse_report_header(line: str) -> Optional[dict]: return { 'solc_version': match.group('solc_version'), 'optimize': parse_bool(match.group('optimize')), - 'runs': int(match.group('runs')), - 'block_limit': int(match.group('block_limit')), + 'runs': int(match.group('runs').replace(',', '')), + 'block_limit': int(match.group('block_limit').replace(',', '')), } @@ -147,7 +148,7 @@ def parse_method_row(line: str, line_number: int) -> Optional[Tuple[str, str, Me raise ReportParsingError("Expected a table row with method details.", line, line_number) avg_gas = parse_optional_int(match['avg']) - call_count = int(match['call_count']) + call_count = int(match['call_count'].strip().replace(',', '')) if avg_gas is None and call_count == 0: # No calls, no gas values. Uninteresting. Skip the row. @@ -174,7 +175,7 @@ def parse_deployment_row(line: str, line_number: int) -> Tuple[str, int, int, in match['contract'].strip(), parse_optional_int(match['min'].strip()), parse_optional_int(match['max'].strip()), - int(match['avg'].strip()), + int(match['avg'].strip().replace(',', '')), ) From 1cd9bc2ff5f1d2a12c01980d5a9cb9bf322f6370 Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Mon, 22 Dec 2025 10:43:52 -0300 Subject: [PATCH 05/73] Bump hardhat-gas-reporter to v2 in gp2 external test --- test/externalTests/gp2.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/externalTests/gp2.sh b/test/externalTests/gp2.sh index cc8b56b665ac..78f21e8e28d2 100755 --- a/test/externalTests/gp2.sh +++ b/test/externalTests/gp2.sh @@ -68,7 +68,8 @@ function gp2_test yarn # Hardhat 3.0+ breaks the test suite # v2.27.1 is the last v2 Hardhat (introduces Osaka support) - yarn add hardhat@2.27.1 + # hardhat-gas-reporter v2 is required for compatibility with our injected gas reporter settings + yarn add hardhat@2.27.1 hardhat-gas-reporter@^2 # Ignore bench directory which fails to compile with current hardhat and ethers versions. # bench/trace/gas.ts:123:19 - error TS2339: Property 'equals' does not exist on type 'Uint8Array'. From d2711509d64320129b7b8fd0535fde4f28cf0e85 Mon Sep 17 00:00:00 2001 From: Manuel Wedler Date: Wed, 17 Dec 2025 09:48:09 +0100 Subject: [PATCH 06/73] ci: Replace `t_ubu_soltest_all` with `t_ubu_soltest` --- .circleci/config.yml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 3cab7fbadb58..12fab84cd044 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1292,6 +1292,18 @@ jobs: destination: docs-html - matrix_notify_failure_unless_pr + t_ubu_soltest: &t_ubu_soltest + <<: *base_ubuntu2404_large + parallelism: 20 + environment: + <<: *base_ubuntu2404_large_env + EVM: << pipeline.parameters.evm-version >> + EOF_VERSION: 0 + OPTIMIZE: 0 + SOLTEST_FLAGS: --no-smt + steps: + - soltest + t_ubu_soltest_all: &t_ubu_soltest_all <<: *base_ubuntu2404_large parallelism: 50 @@ -2038,7 +2050,7 @@ workflows: - t_ubu_cli: *requires_b_ubu - t_ubu_arm_cli: *requires_b_ubu_static_arm - t_ubu_locale: *requires_b_ubu - - t_ubu_soltest_all: *requires_b_ubu + - t_ubu_soltest: *requires_b_ubu - t_ubu_arm_soltest: *requires_b_ubu_static_arm - b_ubu_clang: *requires_nothing - t_ubu_clang_soltest: *requires_b_ubu_clang From 78dd4d15d0ebbc53246e4460d305cceaa5e74727 Mon Sep 17 00:00:00 2001 From: Manuel Wedler Date: Mon, 22 Dec 2025 09:21:13 +0100 Subject: [PATCH 07/73] ci: Remove `t_ubu_soltest_all` job --- .circleci/config.yml | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 12fab84cd044..557b08f8f30c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1304,12 +1304,6 @@ jobs: steps: - soltest - t_ubu_soltest_all: &t_ubu_soltest_all - <<: *base_ubuntu2404_large - parallelism: 50 - steps: - - soltest_all - t_ubu_arm_soltest: &t_ubu_arm_soltest <<: *base_ubuntu2404_arm_medium parallelism: 20 @@ -1384,9 +1378,10 @@ jobs: - soltest t_ubu_force_release_soltest_all: &t_ubu_force_release_soltest_all - # NOTE: This definition is identical to t_ubu_soltest_all but in the workflow we make it depend on - # a different job (b_ubu_force_release) so the workspace it attaches contains a different executable. - <<: *t_ubu_soltest_all + <<: *base_ubuntu2404_large + parallelism: 50 + steps: + - soltest_all t_ubu_cli: &t_ubu_cli <<: *base_ubuntu2404_small From 41b20a7e64d56ccb8c0ad54062967d99bee613e6 Mon Sep 17 00:00:00 2001 From: Manuel Wedler Date: Mon, 22 Dec 2025 09:24:32 +0100 Subject: [PATCH 08/73] ci: Remove `--no-smt` flag from `t_ubu_soltest` job MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Kamil Úliwak --- .circleci/config.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 557b08f8f30c..2276350e0469 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1300,7 +1300,6 @@ jobs: EVM: << pipeline.parameters.evm-version >> EOF_VERSION: 0 OPTIMIZE: 0 - SOLTEST_FLAGS: --no-smt steps: - soltest From 2b7dedf518d5221d566ca73d3322646267a2546c Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Tue, 6 Jan 2026 09:08:48 +0100 Subject: [PATCH 09/73] Add ccache to buildpack-deps images --- .circleci/osx_install_dependencies.sh | 1 + scripts/ci/docker_upgrade.sh | 1 + scripts/docker/buildpack-deps/Dockerfile.emscripten | 3 ++- scripts/docker/buildpack-deps/Dockerfile.ubuntu.clang.ossfuzz | 3 ++- scripts/docker/buildpack-deps/Dockerfile.ubuntu2404 | 3 ++- scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.arm | 3 ++- scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.clang | 3 ++- 7 files changed, 12 insertions(+), 5 deletions(-) diff --git a/.circleci/osx_install_dependencies.sh b/.circleci/osx_install_dependencies.sh index dd5a8397b168..0666211b76b3 100755 --- a/.circleci/osx_install_dependencies.sh +++ b/.circleci/osx_install_dependencies.sh @@ -51,6 +51,7 @@ then brew update brew upgrade brew install cmake + brew install ccache brew install wget brew install coreutils brew install diffutils diff --git a/scripts/ci/docker_upgrade.sh b/scripts/ci/docker_upgrade.sh index c2077239a5b6..533982a3759a 100755 --- a/scripts/ci/docker_upgrade.sh +++ b/scripts/ci/docker_upgrade.sh @@ -55,6 +55,7 @@ docker run \ --rm \ --volume "${PWD}:/project" \ -u "$(id -u "${USER}"):$(id -g "${USER}")" \ + -e CCACHE_DIR=/tmp/ccache \ "${IMAGE_NAME}" \ bash -c "/project/scripts/ci/${IMAGE_NAME}_test_${IMAGE_VARIANT}.sh" diff --git a/scripts/docker/buildpack-deps/Dockerfile.emscripten b/scripts/docker/buildpack-deps/Dockerfile.emscripten index 007729d4113a..67c9ec61a162 100644 --- a/scripts/docker/buildpack-deps/Dockerfile.emscripten +++ b/scripts/docker/buildpack-deps/Dockerfile.emscripten @@ -33,7 +33,7 @@ # Using $(em-config CACHE)/sysroot/usr seems to work, though, and still has cmake find the # dependencies automatically. FROM emscripten/emsdk:3.1.19 AS base -LABEL version="21" +LABEL version="22" ADD emscripten.jam /usr/src RUN <<-EOF @@ -41,6 +41,7 @@ RUN <<-EOF apt-get update apt-get install -qqy --no-install-recommends \ lsof \ + ccache \ lz4 \ python3 \ python3-pip \ diff --git a/scripts/docker/buildpack-deps/Dockerfile.ubuntu.clang.ossfuzz b/scripts/docker/buildpack-deps/Dockerfile.ubuntu.clang.ossfuzz index 5a96e6889dd0..08c091cd7726 100644 --- a/scripts/docker/buildpack-deps/Dockerfile.ubuntu.clang.ossfuzz +++ b/scripts/docker/buildpack-deps/Dockerfile.ubuntu.clang.ossfuzz @@ -22,7 +22,7 @@ # (c) 2016-2021 solidity contributors. #------------------------------------------------------------------------------ FROM gcr.io/oss-fuzz-base/base-builder AS base -LABEL version="12" +LABEL version="13" ARG DEBIAN_FRONTEND=noninteractive @@ -31,6 +31,7 @@ RUN apt-get update; \ automake \ bison \ build-essential \ + ccache \ curl \ git \ jq \ diff --git a/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404 b/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404 index 9cf381f760ef..8f5c1aec8426 100644 --- a/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404 +++ b/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404 @@ -22,7 +22,7 @@ # (c) 2016-2024 solidity contributors. #------------------------------------------------------------------------------ FROM buildpack-deps:noble AS base -LABEL version="6" +LABEL version="7" ARG DEBIAN_FRONTEND=noninteractive @@ -39,6 +39,7 @@ RUN set -ex; \ apt-get install -qqy --no-install-recommends \ build-essential \ cmake \ + ccache \ jq \ libboost-filesystem-dev \ libboost-program-options-dev \ diff --git a/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.arm b/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.arm index 663928220a0e..cc58ed67963e 100644 --- a/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.arm +++ b/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.arm @@ -22,7 +22,7 @@ # (c) 2016-2025 solidity contributors. #------------------------------------------------------------------------------ FROM --platform=linux/arm64 buildpack-deps:noble AS base -LABEL version="2" +LABEL version="3" ARG DEBIAN_FRONTEND=noninteractive @@ -40,6 +40,7 @@ RUN <<-EOF apt-get install --quiet=2 --no-install-recommends \ build-essential \ cmake \ + ccache \ jq \ libboost-filesystem-dev \ libboost-program-options-dev \ diff --git a/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.clang b/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.clang index aec6fe6e26dc..9a9928514088 100644 --- a/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.clang +++ b/scripts/docker/buildpack-deps/Dockerfile.ubuntu2404.clang @@ -22,7 +22,7 @@ # (c) 2016-2024 solidity contributors. #------------------------------------------------------------------------------ FROM buildpack-deps:noble AS base -LABEL version="7" +LABEL version="8" ARG DEBIAN_FRONTEND=noninteractive @@ -40,6 +40,7 @@ RUN set -ex; \ build-essential \ clang \ cmake \ + ccache \ jq \ libboost-filesystem-dev \ libboost-program-options-dev \ From 009ea626be2df0724e5df876f2cc831e40c72651 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Tue, 6 Jan 2026 13:29:43 +0100 Subject: [PATCH 10/73] CI: Batched antlr check --- scripts/AntlrBatchTestRig.java | 104 +++++++++++++++++++++++++++++ scripts/test_antlr_grammar.sh | 118 ++++++++++++++------------------- 2 files changed, 155 insertions(+), 67 deletions(-) create mode 100644 scripts/AntlrBatchTestRig.java diff --git a/scripts/AntlrBatchTestRig.java b/scripts/AntlrBatchTestRig.java new file mode 100644 index 000000000000..91a924c33563 --- /dev/null +++ b/scripts/AntlrBatchTestRig.java @@ -0,0 +1,104 @@ +import org.antlr.v4.runtime.*; +import java.io.*; +import java.nio.file.*; + +public class AntlrBatchTestRig { + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.err.println("Usage: AntlrBatchTestRig [file2] ..."); + System.exit(1); + } + + int exitCode = 0; + for (String filePath: args) { + try { + if (!testFile(filePath)) + exitCode = 1; + } catch (Exception e) { + System.err.println("ERROR:" + filePath + ":" + e.getMessage()); + exitCode = 1; + } + } + System.exit(exitCode); + } + + private static boolean testFile(String filePath) throws Exception { + // Detect mode based on file extension + String mode = filePath.endsWith(".yul") ? "yul" : "sol"; + String content = new String(Files.readAllBytes(Paths.get(filePath))); + + // Check if file expects parser error + boolean expectsError = content.contains("// ParserError"); + + CharStream input; + if (mode.equals("sol")) { + // Remove ExternalSource lines for Solidity files + content = content.replaceAll("(?m)^==== ExternalSource:.*$", ""); + input = CharStreams.fromString(content); + } else { + // Wrap Yul in assembly statement + input = CharStreams.fromString("assembly " + content); + } + + SolidityLexer lexer = new SolidityLexer(input); + CommonTokenStream tokens = new CommonTokenStream(lexer); + SolidityParser parser = new SolidityParser(tokens); + + // Remove default error listeners and add custom one + parser.removeErrorListeners(); + lexer.removeErrorListeners(); + + ErrorCollector errorCollector = new ErrorCollector(); + parser.addErrorListener(errorCollector); + lexer.addErrorListener(errorCollector); + + // Parse based on mode + if (mode.equals("sol")) { + parser.sourceUnit(); + } else { + parser.assemblyStatement(); + } + + boolean hasErrors = errorCollector.hasErrors(); + + // Output result + if (expectsError) { + if (hasErrors) { + System.out.println("PASS:" + filePath + ":FAILED_AS_EXPECTED"); + } else { + System.out.println("FAIL:" + filePath + ":SUCCEEDED_DESPITE_PARSER_ERROR"); + return false; + } + } else { + if (!hasErrors) { + System.out.println("PASS:" + filePath + ":OK"); + } else { + System.out.println("FAIL:" + filePath + ":" + errorCollector.getErrors()); + return false; + } + } + return true; + } + + static class ErrorCollector extends BaseErrorListener { + private StringBuilder errors = new StringBuilder(); + private boolean hasErrors = false; + + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, + int line, int charPositionInLine, + String msg, RecognitionException e) { + hasErrors = true; + errors.append("line ").append(line).append(":").append(charPositionInLine) + .append(" ").append(msg).append("\n"); + } + + public boolean hasErrors() { + return hasErrors; + } + + public String getErrors() { + return errors.toString(); + } + } +} diff --git a/scripts/test_antlr_grammar.sh b/scripts/test_antlr_grammar.sh index 02e9a634f9fd..c8e008c06d4b 100755 --- a/scripts/test_antlr_grammar.sh +++ b/scripts/test_antlr_grammar.sh @@ -10,6 +10,7 @@ ROOT_DIR=$(${READLINK} -f "$(dirname "$0")"/..) WORKDIR="${ROOT_DIR}/build/antlr" ANTLR_JAR="${ROOT_DIR}/build/deps/antlr4.jar" ANTLR_JAR_URI="https://www.antlr.org/download/antlr-4.8-complete.jar" +BATCH_SIZE=100 # Process 100 files per JVM invocation SGR_RESET="\033[0m" SGR_BOLD="\033[1m" @@ -17,9 +18,6 @@ SGR_GREEN="\033[32m" SGR_RED="\033[31m" SGR_BLUE="\033[34m" -vt_cursor_up() { echo -ne "\033[A"; } -vt_cursor_begin_of_line() { echo -ne "\r"; } - function download_antlr4 { if [[ ! -e "$ANTLR_JAR" ]] @@ -47,61 +45,10 @@ java -jar "${ANTLR_JAR}" SolidityParser.g4 SolidityLexer.g4 -o "${WORKDIR}/src/" # Compile lexer/parser sources javac -classpath "${ANTLR_JAR}" "${WORKDIR}/src/"*.java -d "${WORKDIR}/target/" -) -# Run tests -failed_count=0 -function test_file -{ - local SOL_FILE - SOL_FILE="$(${READLINK} -m "${1}")" - local cur=${2} - local max=${3} - local solOrYul=${4} - - echo -e "${SGR_BLUE}[${cur}/${max}] Testing ${SOL_FILE}${SGR_RESET} ..." - local output - if [[ "${solOrYul}" == "sol" ]]; then - output=$( - grep -v "^==== ExternalSource:" "${SOL_FILE}" | java \ - -classpath "${ANTLR_JAR}:${WORKDIR}/target/" \ - "org.antlr.v4.gui.TestRig" \ - Solidity \ - sourceUnit 2>&1 - ) - else - output=$( - echo "assembly $(cat "${SOL_FILE}")" | java \ - -classpath "${ANTLR_JAR}:${WORKDIR}/target/" \ - "org.antlr.v4.gui.TestRig" \ - Solidity \ - assemblyStatement 2>&1 - ) - fi - vt_cursor_up - vt_cursor_begin_of_line - if grep -qE "^\/\/ ParserError" "${SOL_FILE}"; then - if [[ "${output}" != "" ]] - then - echo -e "${SGR_BLUE}[${cur}/${max}] Testing ${SOL_FILE}${SGR_RESET} ${SGR_BOLD}${SGR_GREEN}FAILED AS EXPECTED${SGR_RESET}" - else - echo -e "${SGR_BLUE}[${cur}/${max}] Testing ${SOL_FILE}${SGR_RESET} ${SGR_BOLD}${SGR_RED}SUCCEEDED DESPITE PARSER ERROR${SGR_RESET}" - echo "${output}" - failed_count=$((failed_count + 1)) - exit 1 - fi - else - if [[ "${output}" == "" ]] - then - echo -e "${SGR_BLUE}[${cur}/${max}] Testing ${SOL_FILE}${SGR_RESET} ${SGR_BOLD}${SGR_GREEN}OK${SGR_RESET}" - else - echo -e "${SGR_BLUE}[${cur}/${max}] Testing ${SOL_FILE}${SGR_RESET} ${SGR_BOLD}${SGR_RED}FAILED${SGR_RESET}" - echo "${output}" - failed_count=$((failed_count + 1)) - exit 1 - fi - fi -} +# Compile AntlrBatchTestRig +javac -classpath "${ANTLR_JAR}:${WORKDIR}/target/" "${ROOT_DIR}/scripts/AntlrBatchTestRig.java" -d "${WORKDIR}/target/" +) # we only want to use files that do not contain excluded parser errors, analysis errors or multi-source files. SOL_FILES=() @@ -154,17 +101,54 @@ done < <( "${ROOT_DIR}/test/libyul/yulOptimizerTests" ) -num_tests=$((${#SOL_FILES[*]} + ${#YUL_FILES[*]})) +# Combine all files into one array +ALL_FILES=("${SOL_FILES[@]}" "${YUL_FILES[@]}") +num_tests=${#ALL_FILES[@]} +failed_count=0 test_count=0 -for SOL_FILE in "${SOL_FILES[@]}" -do - test_count=$((test_count + 1)) - test_file "${SOL_FILE}" ${test_count} $num_tests "sol" -done -for YUL_FILE in "${YUL_FILES[@]}" -do - test_count=$((test_count + 1)) - test_file "${YUL_FILE}" ${test_count} $num_tests "yul" + +echo "Testing $num_tests files..." + +# Process all files in batches +for ((i=0; i<${#ALL_FILES[@]}; i+=BATCH_SIZE)); do + batch=("${ALL_FILES[@]:i:BATCH_SIZE}") + batch_size=${#batch[@]} + + echo "Processing batch $((i/BATCH_SIZE + 1)) (${batch_size} files)..." + + # Run batch + output=$(java -classpath "${ANTLR_JAR}:${WORKDIR}/target/" AntlrBatchTestRig "${batch[@]}" 2>&1) || true + + # Parse output + while IFS= read -r line; do + if [[ -z "$line" ]]; then + continue + fi + + test_count=$((test_count + 1)) + + if [[ "$line" =~ ^PASS:(.+):(.*) ]]; then + file="${BASH_REMATCH[1]}" + status="${BASH_REMATCH[2]}" + if [[ "$status" == "FAILED_AS_EXPECTED" ]]; then + echo -e "${SGR_BLUE}[${test_count}/${num_tests}] ${file}${SGR_RESET} ${SGR_BOLD}${SGR_GREEN}FAILED AS EXPECTED${SGR_RESET}" + else + echo -e "${SGR_BLUE}[${test_count}/${num_tests}] ${file}${SGR_RESET} ${SGR_BOLD}${SGR_GREEN}OK${SGR_RESET}" + fi + elif [[ "$line" =~ ^FAIL:(.+):(.*) ]]; then + file="${BASH_REMATCH[1]}" + error="${BASH_REMATCH[2]}" + echo -e "${SGR_BLUE}[${test_count}/${num_tests}] ${file}${SGR_RESET} ${SGR_BOLD}${SGR_RED}FAILED${SGR_RESET}" + echo "$error" + failed_count=$((failed_count + 1)) + elif [[ "$line" =~ ^ERROR:(.+):(.*) ]]; then + file="${BASH_REMATCH[1]}" + error="${BASH_REMATCH[2]}" + echo -e "${SGR_BLUE}[${test_count}/${num_tests}] ${file}${SGR_RESET} ${SGR_BOLD}${SGR_RED}ERROR${SGR_RESET}" + echo "$error" + failed_count=$((failed_count + 1)) + fi + done <<< "$output" done echo "Summary: ${failed_count} of $num_tests sources failed." From 98af07f1e46cff0eeadd134caf4f13f2bd31aed7 Mon Sep 17 00:00:00 2001 From: Franco Victorio Date: Fri, 5 Sep 2025 19:03:33 +0200 Subject: [PATCH 11/73] Add Slippy to the list of Solidity tools --- docs/resources.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/resources.rst b/docs/resources.rst index 3ba0620f95f3..52df87fdd55c 100644 --- a/docs/resources.rst +++ b/docs/resources.rst @@ -133,6 +133,9 @@ Solidity Tools * `Scaffold-ETH 2 `_ Forkable Ethereum development stack focused on fast product iterations. +* `Slippy `_ + A simple and powerful linter for Solidity. + * `sol2uml `_ Unified Modeling Language (UML) class diagram generator for Solidity contracts. From fb900032cc341b3bd0aaad032232ea598741b778 Mon Sep 17 00:00:00 2001 From: Franco Victorio Date: Fri, 19 Dec 2025 10:53:12 +0000 Subject: [PATCH 12/73] Add 'slippy' to codespell's whitelist --- scripts/codespell_whitelist.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/codespell_whitelist.txt b/scripts/codespell_whitelist.txt index 7bcbf6ad14fb..e3a45b947222 100644 --- a/scripts/codespell_whitelist.txt +++ b/scripts/codespell_whitelist.txt @@ -2,3 +2,4 @@ nd compilability keypair wast +slippy From 1d6e22d2f03873a8333ebfc26d395f22b917170b Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Wed, 7 Jan 2026 10:55:07 +0100 Subject: [PATCH 13/73] Speed up CI builds with ccache (seeded from develop) --- .circleci/config.yml | 210 +++++++++++++++++++++++--- .circleci/osx_install_dependencies.sh | 1 + scripts/ci/build.sh | 16 +- scripts/ci/build_emscripten.sh | 12 ++ scripts/ci/build_ossfuzz.sh | 17 ++- scripts/ci/build_win.sh | 26 +++- scripts/install_deps.ps1 | 11 ++ 7 files changed, 265 insertions(+), 28 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2276350e0469..1c141d6474e8 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -13,25 +13,25 @@ parameters: default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:1f387a77be889f65a2a25986a5c5eccc88cec23fabe6aeaf351790751145c81e" ubuntu-2404-docker-image: type: string - # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu2404-6 - default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:c0412c53e59ce0c96bde4c08e7332ea12e4cadba9bbac829621947897fa21272" + # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu2404-7 + default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:e52bd8fbb38908f203c6866e39562548faf26e5b7a5174f9860b44aae2b8f0cd" ubuntu-2404-arm-docker-image: type: string - # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu2404.arm-2 - default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:27b03c1c4688e5d69b10e0539460346a3dee3b10b0e04fb406b9707c6f0dd95e" + # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu2404.arm-3 + default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:1e6dbf9a9173f2645449281a1e11918a95ca6dc04e59aa9d70824cffc44697ed" ubuntu-2404-clang-docker-image: type: string - # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu2404.clang-7 - default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:7466ed23590cf14e60da884894723bcdab064742f017dcfcce015999b4f9143b" + # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu2404.clang-8 + default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:e283c8ec6a59c76565c89b856d8019af2fa5beb96f27d3064fc4dda42bf3524d" ubuntu-clang-ossfuzz-docker-image: type: string - # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu.clang.ossfuzz-12 - default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:c7088af5082bf764244a6251ecf3dd29d280d2cd2cd071f011f7f32e0326f426" + # ghcr.io/argotorg/solidity-buildpack-deps:ubuntu.clang.ossfuzz-13 + default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:2acb5d6f254ece25a96096f26960b5fe114eb86ceca92312cd20d59c096bf6e4" emscripten-docker-image: type: string # NOTE: Please remember to update the `scripts/build_emscripten.sh` whenever the hash of this image changes. - # ghcr.io/argotorg/solidity-buildpack-deps:emscripten-21 - default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:fc53d68a4680ffa7d5f70164e13a903478964f15bcc07434d74833a05f4fbc19" + # ghcr.io/argotorg/solidity-buildpack-deps:emscripten-22 + default: "ghcr.io/argotorg/solidity-buildpack-deps@sha256:b9c953144d82cca5553f65626bc43b8af456dbc8966f8732ff9522f33ca8d722" evm-version: type: string default: osaka @@ -208,15 +208,98 @@ commands: run_build: steps: - - run: - name: Build - command: scripts/ci/build.sh + # TODO: remove the line below + # Before merging this PR we need to use an alternative develop branch to test the functionality, `ci-ccache` + + # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. + # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + - not: + or: + - equal: ["ci-ccache", << pipeline.git.branch >>] + - equal: ["breaking", << pipeline.git.branch >>] + steps: + - restore_cache: + keys: + # Reuse cache produced on ci-ccache (prefix match; restores the most recent). + - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: Build (ccache) + command: CCACHE_ENABLED=1 scripts/ci/build.sh + - when: + condition: + or: + - not: + equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: Build (no ccache) + command: scripts/ci/build.sh + + # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. + - when: + condition: + equal: ["ci-ccache", << pipeline.git.branch >>] + steps: + - save_cache: + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + paths: + - ~/.ccache run_build_ossfuzz: steps: - - run: - name: Build_ossfuzz - command: scripts/ci/build_ossfuzz.sh + # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. + # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + - not: + or: + - equal: ["ci-ccache", << pipeline.git.branch >>] + - equal: ["breaking", << pipeline.git.branch >>] + steps: + - restore_cache: + keys: + # Reuse cache produced on ci-ccache (prefix match; restores the most recent). + - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: Build_ossfuzz (ccache) + command: CCACHE_ENABLED=1 scripts/ci/build_ossfuzz.sh + - when: + condition: + or: + - not: + equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: Build_ossfuzz (no ccache) + command: scripts/ci/build_ossfuzz.sh + + # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. + - when: + condition: + equal: ["ci-ccache", << pipeline.git.branch >>] + steps: + - save_cache: + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + paths: + - ~/.ccache run_proofs: steps: @@ -1197,7 +1280,7 @@ jobs: - run: name: Install build dependencies command: | - pacman --noconfirm -Syu --noprogressbar --needed base-devel boost cmake git openssh tar + pacman --noconfirm -Syu --noprogressbar --needed base-devel boost cmake ccache git openssh tar - checkout - run_build - store_artifacts_solc @@ -1257,10 +1340,50 @@ jobs: MAKEFLAGS: -j 10 steps: - checkout - - run: - name: Build - command: | - scripts/ci/build_emscripten.sh + # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. + # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + - not: + or: + - equal: ["ci-ccache", << pipeline.git.branch >>] + - equal: ["breaking", << pipeline.git.branch >>] + steps: + - restore_cache: + keys: + # Reuse cache produced on ci-ccache (prefix match; restores the most recent). + - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: Build (ccache) + command: CCACHE_ENABLED=1 scripts/ci/build_emscripten.sh + - when: + condition: + or: + - not: + equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: Build (no ccache) + command: | + scripts/ci/build_emscripten.sh + + # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. + - when: + condition: + equal: ["ci-ccache", << pipeline.git.branch >>] + steps: + - save_cache: + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + paths: + - ~/.ccache - store_artifacts: path: upload/soljson.js destination: soljson.js @@ -1737,9 +1860,48 @@ jobs: key: dependencies-win-{{ arch }}-{{ checksum "scripts/install_deps.ps1" }} paths: - .\deps - - run: - name: "Building solidity" - command: scripts/ci/build_win.sh + # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. + # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + - not: + or: + - equal: ["ci-ccache", << pipeline.git.branch >>] + - equal: ["breaking", << pipeline.git.branch >>] + steps: + - restore_cache: + keys: + # Reuse cache produced on ci-ccache (prefix match; restores the most recent). + - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: "Building solidity (ccache)" + command: CCACHE_ENABLED=1 scripts/ci/build_win.sh + - when: + condition: + or: + - not: + equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: "Building solidity (no ccache)" + command: scripts/ci/build_win.sh + # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. + - when: + condition: + equal: ["ci-ccache", << pipeline.git.branch >>] + steps: + - save_cache: + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + paths: + - ~/.ccache - run: name: "Run solc.exe to make sure build was successful." command: .\build\solc\Release\solc.exe --version diff --git a/.circleci/osx_install_dependencies.sh b/.circleci/osx_install_dependencies.sh index dd5a8397b168..0666211b76b3 100755 --- a/.circleci/osx_install_dependencies.sh +++ b/.circleci/osx_install_dependencies.sh @@ -51,6 +51,7 @@ then brew update brew upgrade brew install cmake + brew install ccache brew install wget brew install coreutils brew install diffutils diff --git a/scripts/ci/build.sh b/scripts/ci/build.sh index b7f7e92f5708..769455903f99 100755 --- a/scripts/ci/build.sh +++ b/scripts/ci/build.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -ex -ROOTDIR="$(dirname "$0")/../.." +ROOTDIR="$(realpath "$(dirname "$0")/../..")" # shellcheck source=scripts/common.sh source "${ROOTDIR}/scripts/common.sh" @@ -16,7 +16,21 @@ cd build [[ -n $COVERAGE && -z $CIRCLE_TAG ]] && CMAKE_OPTIONS="$CMAKE_OPTIONS -DCOVERAGE=ON" +if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + export CCACHE_BASEDIR="$ROOTDIR" + export CCACHE_NOHASHDIR=1 + CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" +fi + # shellcheck disable=SC2086 cmake .. -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Release}" $CMAKE_OPTIONS +if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + ccache -z +fi + cmake --build . + +if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + ccache -s +fi diff --git a/scripts/ci/build_emscripten.sh b/scripts/ci/build_emscripten.sh index 50c851af8448..bf19bad3600d 100755 --- a/scripts/ci/build_emscripten.sh +++ b/scripts/ci/build_emscripten.sh @@ -54,6 +54,15 @@ function build() { # TODO: This can be removed if and when all usages of `move()` in our codebase use the `std::` qualifier. CMAKE_CXX_FLAGS="-Wno-unqualified-std-cast-call" + if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + export CCACHE_DIR="$HOME/.ccache" + CCACHE_BASEDIR="$(pwd)" + export CCACHE_BASEDIR + export CCACHE_NOHASHDIR=1 + mkdir -p "$CCACHE_DIR" + ccache -z + fi + mkdir -p "$build_dir" cd "$build_dir" emcmake cmake \ @@ -64,6 +73,9 @@ function build() { -DTESTS=0 \ .. make soljson + if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + ccache -s + fi cd .. mkdir -p upload diff --git a/scripts/ci/build_ossfuzz.sh b/scripts/ci/build_ossfuzz.sh index 64d992994ed6..729b54d1d74c 100755 --- a/scripts/ci/build_ossfuzz.sh +++ b/scripts/ci/build_ossfuzz.sh @@ -18,9 +18,22 @@ function generate_protobuf_bindings function build_fuzzers { cd "${BUILDDIR}" - cmake .. -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Release}" -DCCACHE=OFF \ - -DCMAKE_TOOLCHAIN_FILE="${ROOTDIR}"/cmake/toolchains/libfuzzer.cmake + if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + export CCACHE_BASEDIR="$ROOTDIR" + export CCACHE_NOHASHDIR=1 + CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" + fi + # shellcheck disable=SC2086 + cmake .. -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Release}" \ + -DCMAKE_TOOLCHAIN_FILE="${ROOTDIR}"/cmake/toolchains/libfuzzer.cmake \ + $CMAKE_OPTIONS + if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + ccache -z + fi make ossfuzz ossfuzz_proto ossfuzz_abiv2 -j 4 + if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + ccache -s + fi } generate_protobuf_bindings diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index 64d63c58f4ef..8233f3aa6160 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -10,18 +10,39 @@ CIRCLE_TAG="${CIRCLE_TAG:-}" cd "$ROOTDIR" "${ROOTDIR}/scripts/prerelease_suffix.sh" "$prerelease_source" "$CIRCLE_TAG" > prerelease.txt +if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + export CCACHE_BASEDIR="$ROOTDIR" + export CCACHE_NOHASHDIR=1 + export CCACHE_COMPILERTYPE=msvc + # Hard-coded MSVC cl.exe path + CCACHE_COMPILER="C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe" + export CCACHE_COMPILER + PATH="$ROOTDIR/deps/ccache:$(dirname "$CCACHE_COMPILER"):$PATH" + export PATH + # Use a Windows-style path for Visual Studio globals. + WIN_PWD="$(pwd -W)" + # Visual Studio generator doesn't use compiler launchers; use ccache masquerade. + # See https://github.com/ccache/ccache/wiki/MS-Visual-Studio + CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_VS_GLOBALS=CLToolPath=${WIN_PWD}/deps/ccache;UseMultiToolTask=true" +fi + mkdir -p build/ cd build/ # NOTE: Using an array to force Bash to do wildcard expansion boost_dir=("${ROOTDIR}/deps/boost/lib/cmake/Boost-"*) -"${ROOTDIR}/deps/cmake/bin/cmake" \ + # shellcheck disable=SC2086 + "${ROOTDIR}/deps/cmake/bin/cmake" \ -G "Visual Studio 16 2019" \ -DBoost_DIR="${boost_dir[*]}" \ -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded \ -DCMAKE_INSTALL_PREFIX="${ROOTDIR}/uploads/" \ + ${CMAKE_OPTIONS:-} \ .. +if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + ccache -z +fi MSBuild.exe solidity.sln \ -property:Configuration=Release \ -maxCpuCount:10 \ @@ -31,3 +52,6 @@ MSBuild.exe solidity.sln \ -j 10 \ --target install \ --config Release +if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + ccache -s +fi diff --git a/scripts/install_deps.ps1 b/scripts/install_deps.ps1 index ad4f5bdadccc..bf86735811e9 100644 --- a/scripts/install_deps.ps1 +++ b/scripts/install_deps.ps1 @@ -14,6 +14,17 @@ if ( -not (Test-Path "$PSScriptRoot\..\deps\boost") ) { mv cmake-3.27.4-windows-x86_64 "$PSScriptRoot\..\deps\cmake" Remove-Item cmake.zip + Invoke-WebRequest -URI "https://github.com/ccache/ccache/releases/download/v4.12.2/ccache-4.12.2-windows-x86_64.zip" -OutFile ccache.zip + if ((Get-FileHash ccache.zip).Hash -ne "82c1b130b25cc162531dc7a062dc5ea99349cd536bc9eba8a66d976802d66516") { + throw 'Downloaded ccache package has wrong checksum.' + } + tar -xf ccache.zip + mv ccache-4.12.2-windows-x86_64 "$PSScriptRoot\..\deps\ccache" + # ccache MSVC guide: https://github.com/ccache/ccache/wiki/MS-Visual-Studio + # Replace ccache.exe as cl.exe so MSBuild still sees "cl.exe" while ccache wraps the real compiler. + Copy-Item -Force "$PSScriptRoot\..\deps\ccache\ccache.exe" "$PSScriptRoot\..\deps\ccache\cl.exe" + Remove-Item ccache.zip + # FIXME: The default user agent results in Artifactory treating Invoke-WebRequest as a browser # and serving it a page that requires JavaScript. Invoke-WebRequest -URI "https://archives.boost.io/release/1.83.0/source/boost_1_83_0.zip" -OutFile boost.zip -UserAgent "" From d68a7cdf89808f68c0566b021fc12c4ab5816f80 Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Wed, 7 Jan 2026 11:39:08 +0100 Subject: [PATCH 14/73] Set CCACHE_DIR and create directory if CCACHE_ENABLED --- scripts/ci/build.sh | 2 ++ scripts/ci/build_ossfuzz.sh | 2 ++ scripts/ci/build_win.sh | 2 ++ 3 files changed, 6 insertions(+) diff --git a/scripts/ci/build.sh b/scripts/ci/build.sh index 769455903f99..385d2d898915 100755 --- a/scripts/ci/build.sh +++ b/scripts/ci/build.sh @@ -17,9 +17,11 @@ cd build [[ -n $COVERAGE && -z $CIRCLE_TAG ]] && CMAKE_OPTIONS="$CMAKE_OPTIONS -DCOVERAGE=ON" if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + export CCACHE_DIR="$HOME/.ccache" export CCACHE_BASEDIR="$ROOTDIR" export CCACHE_NOHASHDIR=1 CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" + mkdir -p "$CCACHE_DIR" fi # shellcheck disable=SC2086 diff --git a/scripts/ci/build_ossfuzz.sh b/scripts/ci/build_ossfuzz.sh index 729b54d1d74c..883c939b89ea 100755 --- a/scripts/ci/build_ossfuzz.sh +++ b/scripts/ci/build_ossfuzz.sh @@ -19,9 +19,11 @@ function build_fuzzers { cd "${BUILDDIR}" if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + export CCACHE_DIR="$HOME/.ccache" export CCACHE_BASEDIR="$ROOTDIR" export CCACHE_NOHASHDIR=1 CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" + mkdir -p "$CCACHE_DIR" fi # shellcheck disable=SC2086 cmake .. -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Release}" \ diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index 8233f3aa6160..ea820705d256 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -11,6 +11,7 @@ cd "$ROOTDIR" "${ROOTDIR}/scripts/prerelease_suffix.sh" "$prerelease_source" "$CIRCLE_TAG" > prerelease.txt if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then + export CCACHE_DIR="$HOME/.ccache" export CCACHE_BASEDIR="$ROOTDIR" export CCACHE_NOHASHDIR=1 export CCACHE_COMPILERTYPE=msvc @@ -24,6 +25,7 @@ if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then # Visual Studio generator doesn't use compiler launchers; use ccache masquerade. # See https://github.com/ccache/ccache/wiki/MS-Visual-Studio CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_VS_GLOBALS=CLToolPath=${WIN_PWD}/deps/ccache;UseMultiToolTask=true" + mkdir -p "$CCACHE_DIR" fi mkdir -p build/ From 2243156ebd88193bff483fa6b5495d474948a46f Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Thu, 8 Jan 2026 14:22:56 +0100 Subject: [PATCH 15/73] enforce CCACHE_KEY and fix Windows ccache CMake globals --- .circleci/config.yml | 55 ++++++++++++++++++++++++++++++++--------- scripts/ci/build_win.sh | 5 +++- 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 1c141d6474e8..8d9081bebaf9 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -75,6 +75,17 @@ commands: event: release condition: on_success + ensure_ccache_key: + description: "Fail fast when CCACHE_KEY is missing." + steps: + - run: + name: Check CCACHE_KEY + command: | + if [ -z "${CCACHE_KEY:-}" ]; then + echo "CCACHE_KEY is not set. Please set it in CircleCI environment settings." + exit 1 + fi + prepare_bytecode_report: description: "Generate bytecode report and upload it as an artifact." parameters: @@ -208,6 +219,11 @@ commands: run_build: steps: + - when: + condition: + equal: ["", << pipeline.git.tag >>] + steps: + - ensure_ccache_key # TODO: remove the line below # Before merging this PR we need to use an alternative develop branch to test the functionality, `ci-ccache` @@ -226,7 +242,7 @@ commands: keys: # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- - # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: and: @@ -234,7 +250,7 @@ commands: steps: - run: name: Build (ccache) - command: CCACHE_ENABLED=1 scripts/ci/build.sh + command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build.sh - when: condition: or: @@ -251,12 +267,17 @@ commands: equal: ["ci-ccache", << pipeline.git.branch >>] steps: - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache paths: - ~/.ccache run_build_ossfuzz: steps: + - when: + condition: + equal: ["", << pipeline.git.tag >>] + steps: + - ensure_ccache_key # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. - when: @@ -272,7 +293,7 @@ commands: keys: # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- - # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: and: @@ -280,7 +301,7 @@ commands: steps: - run: name: Build_ossfuzz (ccache) - command: CCACHE_ENABLED=1 scripts/ci/build_ossfuzz.sh + command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build_ossfuzz.sh - when: condition: or: @@ -297,7 +318,7 @@ commands: equal: ["ci-ccache", << pipeline.git.branch >>] steps: - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache paths: - ~/.ccache @@ -1340,6 +1361,11 @@ jobs: MAKEFLAGS: -j 10 steps: - checkout + - when: + condition: + equal: ["", << pipeline.git.tag >>] + steps: + - ensure_ccache_key # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. - when: @@ -1355,7 +1381,7 @@ jobs: keys: # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- - # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: and: @@ -1363,7 +1389,7 @@ jobs: steps: - run: name: Build (ccache) - command: CCACHE_ENABLED=1 scripts/ci/build_emscripten.sh + command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build_emscripten.sh - when: condition: or: @@ -1381,7 +1407,7 @@ jobs: equal: ["ci-ccache", << pipeline.git.branch >>] steps: - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache paths: - ~/.ccache - store_artifacts: @@ -1860,6 +1886,11 @@ jobs: key: dependencies-win-{{ arch }}-{{ checksum "scripts/install_deps.ps1" }} paths: - .\deps + - when: + condition: + equal: ["", << pipeline.git.tag >>] + steps: + - ensure_ccache_key # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. - when: @@ -1875,7 +1906,7 @@ jobs: keys: # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- - # WARNING! If you edit anything between here and save_cache, remember to bump version or invalidate the cache manually. + # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: and: @@ -1883,7 +1914,7 @@ jobs: steps: - run: name: "Building solidity (ccache)" - command: CCACHE_ENABLED=1 scripts/ci/build_win.sh + command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build_win.sh - when: condition: or: @@ -1899,7 +1930,7 @@ jobs: equal: ["ci-ccache", << pipeline.git.branch >>] steps: - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache paths: - ~/.ccache - run: diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index ea820705d256..ee64243f47a1 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -6,6 +6,7 @@ prerelease_source="${1:-ci}" ROOTDIR="$(realpath "$(dirname "$0")/../../")" FORCE_RELEASE="${FORCE_RELEASE:-}" CIRCLE_TAG="${CIRCLE_TAG:-}" +CMAKE_VS_GLOBALS_ARG=() cd "$ROOTDIR" "${ROOTDIR}/scripts/prerelease_suffix.sh" "$prerelease_source" "$CIRCLE_TAG" > prerelease.txt @@ -24,7 +25,8 @@ if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then WIN_PWD="$(pwd -W)" # Visual Studio generator doesn't use compiler launchers; use ccache masquerade. # See https://github.com/ccache/ccache/wiki/MS-Visual-Studio - CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_VS_GLOBALS=CLToolPath=${WIN_PWD}/deps/ccache;UseMultiToolTask=true" + CMAKE_VS_GLOBALS="CLToolPath=${WIN_PWD}/deps/ccache;UseMultiToolTask=true" + CMAKE_VS_GLOBALS_ARG=(-DCMAKE_VS_GLOBALS="$CMAKE_VS_GLOBALS") mkdir -p "$CCACHE_DIR" fi @@ -40,6 +42,7 @@ boost_dir=("${ROOTDIR}/deps/boost/lib/cmake/Boost-"*) -DBoost_DIR="${boost_dir[*]}" \ -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded \ -DCMAKE_INSTALL_PREFIX="${ROOTDIR}/uploads/" \ + "${CMAKE_VS_GLOBALS_ARG[@]}" \ ${CMAKE_OPTIONS:-} \ .. if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then From e1e2ebe86da6502823b3eb9576ceeaf72c4ef137 Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Thu, 8 Jan 2026 15:07:35 +0100 Subject: [PATCH 16/73] Programmatically find the path of cl.exe --- scripts/ci/build_win.sh | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index ee64243f47a1..5a3baf32770e 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -16,8 +16,12 @@ if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then export CCACHE_BASEDIR="$ROOTDIR" export CCACHE_NOHASHDIR=1 export CCACHE_COMPILERTYPE=msvc - # Hard-coded MSVC cl.exe path - CCACHE_COMPILER="C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe" + VSWHERE="C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe" + CCACHE_COMPILER="$("$VSWHERE" -latest -products "*" \ + -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 \ + -version "[16.0,17.0)" \ + -find "VC/Tools/MSVC/*/bin/Hostx64/x64/cl.exe" | sort -V | tail -n 1 | tr -d '\r')" + CCACHE_COMPILER="${CCACHE_COMPILER//\\//}" export CCACHE_COMPILER PATH="$ROOTDIR/deps/ccache:$(dirname "$CCACHE_COMPILER"):$PATH" export PATH From c2bf44142ab3057e1a731843ae0aef149e1f9c59 Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Thu, 8 Jan 2026 15:17:56 +0100 Subject: [PATCH 17/73] Remove the version filter in the command to find cl.exe --- scripts/ci/build_win.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index 5a3baf32770e..01c062ec5e8e 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -19,7 +19,6 @@ if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then VSWHERE="C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe" CCACHE_COMPILER="$("$VSWHERE" -latest -products "*" \ -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 \ - -version "[16.0,17.0)" \ -find "VC/Tools/MSVC/*/bin/Hostx64/x64/cl.exe" | sort -V | tail -n 1 | tr -d '\r')" CCACHE_COMPILER="${CCACHE_COMPILER//\\//}" export CCACHE_COMPILER From 9b8d22abb56ad379dfedea64f751cde3185f11aa Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Thu, 8 Jan 2026 15:24:56 +0100 Subject: [PATCH 18/73] Fix vswhere command --- scripts/ci/build_win.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index 01c062ec5e8e..b88051985190 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -19,7 +19,7 @@ if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then VSWHERE="C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe" CCACHE_COMPILER="$("$VSWHERE" -latest -products "*" \ -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 \ - -find "VC/Tools/MSVC/*/bin/Hostx64/x64/cl.exe" | sort -V | tail -n 1 | tr -d '\r')" + -find "VC/Tools/MSVC/*/bin/Hostx64/x64/cl.exe" | head -n 1 | tr -d '\r')" CCACHE_COMPILER="${CCACHE_COMPILER//\\//}" export CCACHE_COMPILER PATH="$ROOTDIR/deps/ccache:$(dirname "$CCACHE_COMPILER"):$PATH" From 4bb922571121a97421d5470cfa2d6286ea311f6e Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Thu, 8 Jan 2026 15:39:31 +0100 Subject: [PATCH 19/73] Fix CCACHE_COMPILER extraction --- scripts/ci/build_win.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index b88051985190..07604c8eb854 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -16,10 +16,12 @@ if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then export CCACHE_BASEDIR="$ROOTDIR" export CCACHE_NOHASHDIR=1 export CCACHE_COMPILERTYPE=msvc - VSWHERE="C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe" - CCACHE_COMPILER="$("$VSWHERE" -latest -products "*" \ + VSWHERE="${VSWHERE:-C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe}" + VS_INSTALL="$("$VSWHERE" -latest -products "*" \ -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 \ - -find "VC/Tools/MSVC/*/bin/Hostx64/x64/cl.exe" | head -n 1 | tr -d '\r')" + -property installationPath | tr -d '\r')" + VCTOOLS_VERSION="$(tr -d '\r' < "$VS_INSTALL/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt")" + CCACHE_COMPILER="$VS_INSTALL/VC/Tools/MSVC/$VCTOOLS_VERSION/bin/Hostx64/x64/cl.exe" CCACHE_COMPILER="${CCACHE_COMPILER//\\//}" export CCACHE_COMPILER PATH="$ROOTDIR/deps/ccache:$(dirname "$CCACHE_COMPILER"):$PATH" From b6d0d788d49cf28ca14162893d03adac3fcb5f9b Mon Sep 17 00:00:00 2001 From: 0xcharry Date: Sun, 11 Jan 2026 16:55:23 +0100 Subject: [PATCH 20/73] Update JSON.cpp --- libsolutil/JSON.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/libsolutil/JSON.cpp b/libsolutil/JSON.cpp index 548fdfe0b87c..8633a44c4db4 100644 --- a/libsolutil/JSON.cpp +++ b/libsolutil/JSON.cpp @@ -149,7 +149,6 @@ bool jsonParseStrict(std::string const& _input, Json& _json, std::string* _errs /* allow exceptions */ true, /* ignore_comments */true ); - _errs = {}; return true; } catch (Json::parse_error const& e) From 95caef252520fa52bfce38e69052da0945132588 Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Mon, 12 Jan 2026 09:24:16 +0100 Subject: [PATCH 21/73] Refactor config.yml to re-use ccache restore and save commands --- .circleci/config.yml | 135 +++++++++++++++---------------------------- 1 file changed, 45 insertions(+), 90 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 8d9081bebaf9..de63a363faa9 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -86,6 +86,44 @@ commands: exit 1 fi + restore_ccache_if_allowed: + description: "Restore ccache unless on a tag or a skipped branch." + parameters: + # TODO: remove the line below + # Before merging this PR we need to use an alternative develop branch to test the functionality, `ci-ccache` + skip_branches_regex: + description: "Regex of branches that should skip restoring the cache." + type: string + default: "^(ci-ccache|breaking)$" + steps: + # Tags always skip ccache. Selected branches intentionally start from scratch. + - when: + condition: + and: + - equal: ["", << pipeline.git.tag >>] + - not: + matches: + pattern: "<< parameters.skip_branches_regex >>" + value: << pipeline.git.branch >> + steps: + - restore_cache: + keys: + # Reuse cache produced on ci-ccache (prefix match; restores the most recent). + - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + + save_ccache_if_develop: + description: "Save a fresh ccache only on the ci-ccache branch." + steps: + # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. + - when: + condition: + equal: ["ci-ccache", << pipeline.git.branch >>] + steps: + - save_cache: + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache + paths: + - ~/.ccache + prepare_bytecode_report: description: "Generate bytecode report and upload it as an artifact." parameters: @@ -224,24 +262,7 @@ commands: equal: ["", << pipeline.git.tag >>] steps: - ensure_ccache_key - # TODO: remove the line below - # Before merging this PR we need to use an alternative develop branch to test the functionality, `ci-ccache` - - # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. - # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - - not: - or: - - equal: ["ci-ccache", << pipeline.git.branch >>] - - equal: ["breaking", << pipeline.git.branch >>] - steps: - - restore_cache: - keys: - # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: @@ -261,15 +282,7 @@ commands: name: Build (no ccache) command: scripts/ci/build.sh - # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. - - when: - condition: - equal: ["ci-ccache", << pipeline.git.branch >>] - steps: - - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache - paths: - - ~/.ccache + - save_ccache_if_develop run_build_ossfuzz: steps: @@ -278,21 +291,7 @@ commands: equal: ["", << pipeline.git.tag >>] steps: - ensure_ccache_key - # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. - # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - - not: - or: - - equal: ["ci-ccache", << pipeline.git.branch >>] - - equal: ["breaking", << pipeline.git.branch >>] - steps: - - restore_cache: - keys: - # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: @@ -312,15 +311,7 @@ commands: name: Build_ossfuzz (no ccache) command: scripts/ci/build_ossfuzz.sh - # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. - - when: - condition: - equal: ["ci-ccache", << pipeline.git.branch >>] - steps: - - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache - paths: - - ~/.ccache + - save_ccache_if_develop run_proofs: steps: @@ -1366,21 +1357,7 @@ jobs: equal: ["", << pipeline.git.tag >>] steps: - ensure_ccache_key - # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. - # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - - not: - or: - - equal: ["ci-ccache", << pipeline.git.branch >>] - - equal: ["breaking", << pipeline.git.branch >>] - steps: - - restore_cache: - keys: - # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: @@ -1401,15 +1378,7 @@ jobs: command: | scripts/ci/build_emscripten.sh - # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. - - when: - condition: - equal: ["ci-ccache", << pipeline.git.branch >>] - steps: - - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache - paths: - - ~/.ccache + - save_ccache_if_develop - store_artifacts: path: upload/soljson.js destination: soljson.js @@ -1891,21 +1860,7 @@ jobs: equal: ["", << pipeline.git.tag >>] steps: - ensure_ccache_key - # On `ci-ccache` and `breaking` we intentionally do NOT restore any ccache, so every run starts from scratch. - # Tags always skip ccache. Other branches restore the most recent cache produced on `ci-ccache`. - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - - not: - or: - - equal: ["ci-ccache", << pipeline.git.branch >>] - - equal: ["breaking", << pipeline.git.branch >>] - steps: - - restore_cache: - keys: - # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - when: condition: From bd615db148d3e3a2b76a52af0202043e1c06346d Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Mon, 12 Jan 2026 11:27:04 +0100 Subject: [PATCH 22/73] Add revision to the cache key to avoid skipping cache generation for duplicate key --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index de63a363faa9..1b6a309fc1da 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -120,7 +120,7 @@ commands: equal: ["ci-ccache", << pipeline.git.branch >>] steps: - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} paths: - ~/.ccache From be1df0710601fda269610953b75c7bf92684f965 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Wed, 14 Jan 2026 00:54:35 +0100 Subject: [PATCH 23/73] CLI Parser: Use defaulted comparison operators for options --- solc/CommandLineParser.cpp | 57 -------------------------------------- solc/CommandLineParser.h | 57 ++++++++++++++++++++++++++++---------- 2 files changed, 42 insertions(+), 72 deletions(-) diff --git a/solc/CommandLineParser.cpp b/solc/CommandLineParser.cpp index 50ce02bd14c8..534eb57d1095 100644 --- a/solc/CommandLineParser.cpp +++ b/solc/CommandLineParser.cpp @@ -157,14 +157,6 @@ void CommandLineParser::checkMutuallyExclusive(std::vector const& _ } } -bool CompilerOutputs::operator==(CompilerOutputs const& _other) const noexcept -{ - for (bool CompilerOutputs::* member: componentMap() | ranges::views::values) - if (this->*member != _other.*member) - return false; - return true; -} - std::ostream& operator<<(std::ostream& _out, CompilerOutputs const& _selection) { std::vector serializedSelection; @@ -187,15 +179,6 @@ std::string const& CompilerOutputs::componentName(bool CompilerOutputs::* _compo solAssert(false, ""); } -bool CombinedJsonRequests::operator==(CombinedJsonRequests const& _other) const noexcept -{ - for (bool CombinedJsonRequests::* member: componentMap() | ranges::views::values) - if (this->*member != _other.*member) - return false; - return true; -} - - std::ostream& operator<<(std::ostream& _out, CombinedJsonRequests const& _requests) { std::vector serializedRequests; @@ -217,46 +200,6 @@ std::string const& CombinedJsonRequests::componentName(bool CombinedJsonRequests solAssert(false, ""); } -bool CommandLineOptions::operator==(CommandLineOptions const& _other) const noexcept -{ - return - input.paths == _other.input.paths && - input.remappings == _other.input.remappings && - input.addStdin == _other.input.addStdin && - input.basePath == _other.input.basePath && - input.includePaths == _other.input.includePaths && - input.allowedDirectories == _other.input.allowedDirectories && - input.ignoreMissingFiles == _other.input.ignoreMissingFiles && - input.noImportCallback == _other.input.noImportCallback && - output.dir == _other.output.dir && - output.overwriteFiles == _other.output.overwriteFiles && - output.evmVersion == _other.output.evmVersion && - output.viaIR == _other.output.viaIR && - output.revertStrings == _other.output.revertStrings && - output.debugInfoSelection == _other.output.debugInfoSelection && - output.stopAfter == _other.output.stopAfter && - output.eofVersion == _other.output.eofVersion && - input.mode == _other.input.mode && - assembly.targetMachine == _other.assembly.targetMachine && - assembly.inputLanguage == _other.assembly.inputLanguage && - linker.libraries == _other.linker.libraries && - formatting.json == _other.formatting.json && - formatting.coloredOutput == _other.formatting.coloredOutput && - formatting.withErrorIds == _other.formatting.withErrorIds && - compiler.outputs == _other.compiler.outputs && - compiler.estimateGas == _other.compiler.estimateGas && - compiler.combinedJsonRequests == _other.compiler.combinedJsonRequests && - metadata.format == _other.metadata.format && - metadata.hash == _other.metadata.hash && - metadata.literalSources == _other.metadata.literalSources && - optimizer.optimizeEvmasm == _other.optimizer.optimizeEvmasm && - optimizer.optimizeYul == _other.optimizer.optimizeYul && - optimizer.expectedExecutionsPerDeployment == _other.optimizer.expectedExecutionsPerDeployment && - optimizer.yulSteps == _other.optimizer.yulSteps && - modelChecker.initialize == _other.modelChecker.initialize && - modelChecker.settings == _other.modelChecker.settings; -} - OptimiserSettings CommandLineOptions::optimiserSettings() const { OptimiserSettings settings; diff --git a/solc/CommandLineParser.h b/solc/CommandLineParser.h index d8141cb4fcf0..46743232b468 100644 --- a/solc/CommandLineParser.h +++ b/solc/CommandLineParser.h @@ -62,8 +62,8 @@ enum class InputMode struct CompilerOutputs { - bool operator!=(CompilerOutputs const& _other) const noexcept { return !(*this == _other); } - bool operator==(CompilerOutputs const& _other) const noexcept; + bool operator!=(CompilerOutputs const& _other) const noexcept = default; + bool operator==(CompilerOutputs const& _other) const noexcept = default; friend std::ostream& operator<<(std::ostream& _out, CompilerOutputs const& _requests); static std::string const& componentName(bool CompilerOutputs::* _component); @@ -118,8 +118,8 @@ struct CompilerOutputs struct CombinedJsonRequests { - bool operator!=(CombinedJsonRequests const& _other) const noexcept { return !(*this == _other); } - bool operator==(CombinedJsonRequests const& _other) const noexcept; + bool operator!=(CombinedJsonRequests const& _other) const noexcept = default; + bool operator==(CombinedJsonRequests const& _other) const noexcept = default; friend std::ostream& operator<<(std::ostream& _out, CombinedJsonRequests const& _requests); static std::string const& componentName(bool CombinedJsonRequests::* _component); @@ -170,13 +170,16 @@ struct CombinedJsonRequests struct CommandLineOptions { - bool operator==(CommandLineOptions const& _other) const noexcept; - bool operator!=(CommandLineOptions const& _other) const noexcept { return !(*this == _other); } + bool operator==(CommandLineOptions const& _other) const noexcept = default; + bool operator!=(CommandLineOptions const& _other) const noexcept = default; OptimiserSettings optimiserSettings() const; - struct + struct Input { + bool operator==(Input const&) const noexcept = default; + bool operator!=(Input const&) const noexcept = default; + InputMode mode = InputMode::Compiler; std::set paths; std::vector remappings; @@ -188,8 +191,11 @@ struct CommandLineOptions bool noImportCallback = false; } input; - struct + struct Output { + bool operator==(Output const&) const noexcept = default; + bool operator!=(Output const&) const noexcept = default; + boost::filesystem::path dir; bool overwriteFiles = false; langutil::EVMVersion evmVersion; @@ -200,48 +206,69 @@ struct CommandLineOptions std::optional eofVersion; } output; - struct + struct Assembly { + bool operator==(Assembly const&) const noexcept = default; + bool operator!=(Assembly const&) const noexcept = default; + yul::YulStack::Machine targetMachine = yul::YulStack::Machine::EVM; yul::YulStack::Language inputLanguage = yul::YulStack::Language::StrictAssembly; } assembly; - struct + struct Linker { + bool operator==(Linker const&) const noexcept = default; + bool operator!=(Linker const&) const noexcept = default; + std::map libraries; // library name -> address } linker; - struct + struct Formatting { + bool operator==(Formatting const&) const noexcept = default; + bool operator!=(Formatting const&) const noexcept = default; + util::JsonFormat json; std::optional coloredOutput; bool withErrorIds = false; } formatting; - struct + struct Compiler { + bool operator==(Compiler const&) const noexcept = default; + bool operator!=(Compiler const&) const noexcept = default; + CompilerOutputs outputs; bool estimateGas = false; std::optional combinedJsonRequests; } compiler; - struct + struct Metadata { + bool operator==(Metadata const&) const noexcept = default; + bool operator!=(Metadata const&) const noexcept = default; + CompilerStack::MetadataFormat format = CompilerStack::defaultMetadataFormat(); CompilerStack::MetadataHash hash = CompilerStack::MetadataHash::IPFS; bool literalSources = false; } metadata; - struct + struct Optimizer { + bool operator==(Optimizer const&) const noexcept = default; + bool operator!=(Optimizer const&) const noexcept = default; + bool optimizeEvmasm = false; bool optimizeYul = false; std::optional expectedExecutionsPerDeployment; std::optional yulSteps; } optimizer; - struct + struct ModelChecker { + bool operator==(ModelChecker const&) const noexcept = default; + bool operator!=(ModelChecker const&) const noexcept = default; + bool initialize = false; ModelCheckerSettings settings; } modelChecker; From 6d538dd2056cd6dc9b8abfe15ebda1e1b5301f6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Sat, 20 Dec 2025 01:05:26 +0100 Subject: [PATCH 24/73] ReleaseChecklist: Split off Comms and Documentation sections from Post-release --- ReleaseChecklist.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ReleaseChecklist.md b/ReleaseChecklist.md index 9c3b2f89682d..f56ec55fef19 100644 --- a/ReleaseChecklist.md +++ b/ReleaseChecklist.md @@ -89,12 +89,13 @@ At least a day before the release: Inspect the tarball to ensure that it contains an up-to-date compiler binary (`soljson.js`). - [ ] Run `npm publish solc-x.y.z.tgz` to publish the newly created tarball. -### Post-release +### Documentation - [ ] Make sure the documentation for the new release has been published successfully. Go to the [documentation status page at ReadTheDocs](https://readthedocs.org/projects/solidity/) and verify that the new version is listed, works and is marked as default. - [ ] Remove "still in progress" warning from the [release notes](https://github.com/argotorg/solidity/releases). + +### Comms - [ ] Merge the [blog posts](https://github.com/argotorg/solidity-website/pulls) related to the release. -- [ ] Create a commit to increase the version number on `develop` in `CMakeLists.txt` and add a new skeleton changelog entry. - [ ] Update the release information section [in the source of soliditylang.org](https://github.com/argotorg/solidity-website/blob/main/src/pages/index.tsx). - [ ] Announce on [Twitter](https://twitter.com/solidity_lang), including links to the release and the blog post. - [ ] Announce on [Fosstodon](https://fosstodon.org/@solidity/), including links to the release and the blog post. @@ -102,6 +103,9 @@ At least a day before the release: - [ ] Share the announcement on the [Solidity forum](https://forum.soliditylang.org) in the `Announcements` category. - [ ] Share the announcement on [`#solidity` channel on Matrix](https://matrix.to/#/#ethereum_solidity:gitter.im). - [ ] Share the announcement on [`#solc-tooling`](https://matrix.to/#/#solc-tooling:matrix.org). + +### Post-release +- [ ] Create a commit to increase the version number on `develop` in `CMakeLists.txt` and add a new skeleton changelog entry. - [ ] If anything went wrong this time, mention it in [Learning from Past Releases](https://notes.argot.org/@solidity-release-mistakes). - [ ] Bump vendored dependencies. - [ ] Lean back, wait for bug reports and repeat from step 1 :). From 5e28f2a5a1ec43f2b6951971f51398500317de90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Sat, 20 Dec 2025 01:10:28 +0100 Subject: [PATCH 25/73] ReleaseChecklist: New step to verify links in release notes --- ReleaseChecklist.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ReleaseChecklist.md b/ReleaseChecklist.md index f56ec55fef19..637f8dc8a2fa 100644 --- a/ReleaseChecklist.md +++ b/ReleaseChecklist.md @@ -97,6 +97,7 @@ At least a day before the release: ### Comms - [ ] Merge the [blog posts](https://github.com/argotorg/solidity-website/pulls) related to the release. - [ ] Update the release information section [in the source of soliditylang.org](https://github.com/argotorg/solidity-website/blob/main/src/pages/index.tsx). +- [ ] Verify that the link to the blog post in [release notes](https://github.com/argotorg/solidity/releases) is not broken. - [ ] Announce on [Twitter](https://twitter.com/solidity_lang), including links to the release and the blog post. - [ ] Announce on [Fosstodon](https://fosstodon.org/@solidity/), including links to the release and the blog post. - [ ] Share the announcement on Reddit in [`/r/ethdev`](https://reddit.com/r/ethdev/), cross-posted to [`/r/ethereum`](https://reddit.com/r/ethereum/). From 4629368a8df56b84ca3b03ade67446b8e1634e54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Sat, 20 Dec 2025 01:17:09 +0100 Subject: [PATCH 26/73] ReleaseChecklist: Emphasize that blog/website drafts should be created ahead of time and only merged after release --- ReleaseChecklist.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ReleaseChecklist.md b/ReleaseChecklist.md index 637f8dc8a2fa..d9f6b84a80da 100644 --- a/ReleaseChecklist.md +++ b/ReleaseChecklist.md @@ -36,10 +36,11 @@ At least a day before the release: - [ ] Create drafts of blog posts. - [ ] Prepare drafts of Twitter, Reddit and Solidity Forum announcements. -### Blog Post +### Website/Blog Updates - [ ] Create a post on [solidity-website](https://github.com/argotorg/solidity-website/tree/main/src/posts) in the `Releases` category and explain some of the new features or concepts. - [ ] Create a post on [solidity-website](https://github.com/argotorg/solidity-website/tree/main/src/posts) in the `Security Alerts` category in case of important bug(s). -- [ ] Get the posts reviewed and approved **before the release starts**. +- [ ] Update the release information section [in the source of soliditylang.org](https://github.com/argotorg/solidity-website/blob/main/src/pages/index.tsx). +- [ ] Get the PR(s) for the above reviewed and approved **before the release starts**, but don't merge them yet. ### Changelog - [ ] Ensure that all changelog entries are correctly classified as language or compiler features. @@ -95,8 +96,7 @@ At least a day before the release: - [ ] Remove "still in progress" warning from the [release notes](https://github.com/argotorg/solidity/releases). ### Comms -- [ ] Merge the [blog posts](https://github.com/argotorg/solidity-website/pulls) related to the release. -- [ ] Update the release information section [in the source of soliditylang.org](https://github.com/argotorg/solidity-website/blob/main/src/pages/index.tsx). +- [ ] Merge the blog posts and website updates prepared for the release. - [ ] Verify that the link to the blog post in [release notes](https://github.com/argotorg/solidity/releases) is not broken. - [ ] Announce on [Twitter](https://twitter.com/solidity_lang), including links to the release and the blog post. - [ ] Announce on [Fosstodon](https://fosstodon.org/@solidity/), including links to the release and the blog post. From 7bd6b273180c798d559163c4cdec52e627d45d58 Mon Sep 17 00:00:00 2001 From: Matheus Aguiar Date: Thu, 11 Dec 2025 02:29:33 -0300 Subject: [PATCH 27/73] Replace transfer with call in smt tests --- .../model_checker_targets_assert_chc/err | 12 ++---- .../input.sol | 5 ++- .../err | 5 --- .../input.sol | 3 +- .../model_checker_targets_div_by_zero_chc/err | 7 +--- .../input.sol | 5 ++- .../model_checker_targets_error/input.sol | 5 ++- .../err | 12 ++---- .../input.sol | 5 ++- .../model_checker_targets_overflow_chc/err | 7 +--- .../input.sol | 5 ++- .../model_checker_targets_pop_empty_chc/err | 12 ++---- .../input.sol | 5 ++- .../model_checker_targets_underflow_chc/err | 7 +--- .../input.sol | 5 ++- .../err | 14 +++---- .../input.sol | 5 ++- .../err | 8 +--- .../input.sol | 5 ++- .../input.json | 3 +- .../output.json | 33 +++++------------ .../input.json | 3 +- .../output.json | 21 ----------- .../input.json | 3 +- .../output.json | 21 +---------- .../input.json | 3 +- .../input.json | 3 +- .../output.json | 33 +++++------------ .../input.json | 3 +- .../output.json | 21 +---------- .../input.json | 3 +- .../output.json | 33 +++++------------ .../input.json | 3 +- .../output.json | 21 +---------- .../input.json | 3 +- .../output.json | 37 +++++++------------ .../input.json | 3 +- .../output.json | 23 ++---------- .../input.json | 3 +- .../input.json | 3 +- .../input.json | 3 +- 41 files changed, 128 insertions(+), 286 deletions(-) delete mode 100644 test/cmdlineTests/model_checker_targets_constant_condition_chc/err diff --git a/test/cmdlineTests/model_checker_targets_assert_chc/err b/test/cmdlineTests/model_checker_targets_assert_chc/err index 096773e68ee0..fb4d9fcc598d 100644 --- a/test/cmdlineTests/model_checker_targets_assert_chc/err +++ b/test/cmdlineTests/model_checker_targets_assert_chc/err @@ -1,20 +1,16 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Assertion violation happens here. Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> input.sol:11:3: + a.call{value: x}("") -- untrusted external call + --> input.sol:12:3: | -11 | assert(x > 0); +12 | assert(x > 0); | ^^^^^^^^^^^^^ diff --git a/test/cmdlineTests/model_checker_targets_assert_chc/input.sol b/test/cmdlineTests/model_checker_targets_assert_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_assert_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_assert_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_constant_condition_chc/err b/test/cmdlineTests/model_checker_targets_constant_condition_chc/err deleted file mode 100644 index 4876e936610a..000000000000 --- a/test/cmdlineTests/model_checker_targets_constant_condition_chc/err +++ /dev/null @@ -1,5 +0,0 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:11:3: - | -11 | a.transfer(x); - | ^^^^^^^^^^ diff --git a/test/cmdlineTests/model_checker_targets_constant_condition_chc/input.sol b/test/cmdlineTests/model_checker_targets_constant_condition_chc/input.sol index 4b521b3deba1..4103252cad56 100644 --- a/test/cmdlineTests/model_checker_targets_constant_condition_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_constant_condition_chc/input.sol @@ -8,7 +8,8 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/model_checker_targets_div_by_zero_chc/err b/test/cmdlineTests/model_checker_targets_div_by_zero_chc/err index 3e00272485e6..b9b84f2917de 100644 --- a/test/cmdlineTests/model_checker_targets_div_by_zero_chc/err +++ b/test/cmdlineTests/model_checker_targets_div_by_zero_chc/err @@ -1,14 +1,9 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Division by zero happens here. Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/model_checker_targets_div_by_zero_chc/input.sol b/test/cmdlineTests/model_checker_targets_div_by_zero_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_div_by_zero_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_div_by_zero_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_error/input.sol b/test/cmdlineTests/model_checker_targets_error/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_error/input.sol +++ b/test/cmdlineTests/model_checker_targets_error/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/err b/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/err index 9026ef934dba..cefc673499de 100644 --- a/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/err +++ b/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/err @@ -1,20 +1,16 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Out of bounds access happens here. Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> input.sol:13:3: + a.call{value: x}("") -- untrusted external call + --> input.sol:14:3: | -13 | arr[x]; +14 | arr[x]; | ^^^^^^ diff --git a/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/input.sol b/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_out_of_bounds_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_overflow_chc/err b/test/cmdlineTests/model_checker_targets_overflow_chc/err index 178b59a44e73..bbaee177831f 100644 --- a/test/cmdlineTests/model_checker_targets_overflow_chc/err +++ b/test/cmdlineTests/model_checker_targets_overflow_chc/err @@ -1,14 +1,9 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Overflow (resulting value larger than 2**256 - 1) happens here. Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/model_checker_targets_overflow_chc/input.sol b/test/cmdlineTests/model_checker_targets_overflow_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_overflow_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_overflow_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_pop_empty_chc/err b/test/cmdlineTests/model_checker_targets_pop_empty_chc/err index e4c1bbc0effa..78524bd90385 100644 --- a/test/cmdlineTests/model_checker_targets_pop_empty_chc/err +++ b/test/cmdlineTests/model_checker_targets_pop_empty_chc/err @@ -1,20 +1,16 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Empty array "pop" happens here. Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> input.sol:12:3: + a.call{value: x}("") -- untrusted external call + --> input.sol:13:3: | -12 | arr.pop(); +13 | arr.pop(); | ^^^^^^^^^ diff --git a/test/cmdlineTests/model_checker_targets_pop_empty_chc/input.sol b/test/cmdlineTests/model_checker_targets_pop_empty_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_pop_empty_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_pop_empty_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_underflow_chc/err b/test/cmdlineTests/model_checker_targets_underflow_chc/err index f9fbf82eec31..f245215584d2 100644 --- a/test/cmdlineTests/model_checker_targets_underflow_chc/err +++ b/test/cmdlineTests/model_checker_targets_underflow_chc/err @@ -1,14 +1,9 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Underflow (resulting value less than 0) happens here. Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/model_checker_targets_underflow_chc/input.sol b/test/cmdlineTests/model_checker_targets_underflow_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_underflow_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_underflow_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/err b/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/err index f91c067026a8..8388d76eded1 100644 --- a/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/err +++ b/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/err @@ -1,14 +1,9 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Underflow (resulting value less than 0) happens here. Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -24,6 +19,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() @@ -39,12 +35,14 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> input.sol:11:3: + a.call{value: x}("") -- untrusted external call + --> input.sol:12:3: | -11 | assert(x > 0); +12 | assert(x > 0); | ^^^^^^^^^^^^^ diff --git a/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/input.sol b/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_underflow_overflow_assert_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/err b/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/err index 44faa5ae8388..5751c9072251 100644 --- a/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/err +++ b/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/err @@ -1,14 +1,9 @@ -Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }("")' instead. - --> input.sol:10:3: - | -10 | a.transfer(x); - | ^^^^^^^^^^ - Warning: CHC: Underflow (resulting value less than 0) happens here. Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -24,6 +19,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/input.sol b/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/input.sol index 33b5bfab3ff7..0061441c0cf8 100644 --- a/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/input.sol +++ b/test/cmdlineTests/model_checker_targets_underflow_overflow_chc/input.sol @@ -7,9 +7,10 @@ contract test { --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(""); + require(success); assert(x > 0); arr.pop(); arr[x]; } -} \ No newline at end of file +} diff --git a/test/cmdlineTests/standard_model_checker_targets_assert_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_assert_chc/input.json index a9a7b3fcdb92..e28a8d2259b1 100644 --- a/test/cmdlineTests/standard_model_checker_targets_assert_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_assert_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_assert_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_assert_chc/output.json index d7cfd4a82c4b..6bdd27918bd2 100644 --- a/test/cmdlineTests/standard_model_checker_targets_assert_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_assert_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "6328", @@ -27,14 +8,16 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> A:12:7: + a.call{value: x}(\"\") -- untrusted external call + --> A:13:7: | -12 | \t\t\t\t\t\tassert(x > 0); +13 | \t\t\t\t\t\tassert(x > 0); | \t\t\t\t\t\t^^^^^^^^^^^^^ ", @@ -43,16 +26,18 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] -test.f(0x0, 1)", +test.f(0x0, 1) + a.call{value: x}(\"\") -- untrusted external call", "severity": "warning", "sourceLocation": { - "end": 258, + "end": 308, "file": "A", - "start": 245 + "start": 295 }, "type": "Warning" } diff --git a/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/input.json index 365ca122be50..a7e2be42943c 100644 --- a/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/output.json index d6a7b5a4ef07..f047ff70a9eb 100644 --- a/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_constantCondition_chc/output.json @@ -1,25 +1,4 @@ { - "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - } - ], "sources": { "A": { "id": 0 diff --git a/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/input.json index 1c7af8d5c1f7..c7476eface2a 100644 --- a/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/output.json index e5a54e4c871a..867decb52adf 100644 --- a/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_div_by_zero_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "4281", @@ -27,6 +8,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -43,6 +25,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/standard_model_checker_targets_empty_array/input.json b/test/cmdlineTests/standard_model_checker_targets_empty_array/input.json index cb51e490582a..40ccfcbeb91e 100644 --- a/test/cmdlineTests/standard_model_checker_targets_empty_array/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_empty_array/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/input.json index cd0ba6d13594..63ccad902ffb 100644 --- a/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/output.json index ecb01eac357d..80d919066305 100644 --- a/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_out_of_bounds_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "6368", @@ -27,14 +8,16 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> A:14:7: + a.call{value: x}(\"\") -- untrusted external call + --> A:15:7: | -14 | \t\t\t\t\t\tarr[x]; +15 | \t\t\t\t\t\tarr[x]; | \t\t\t\t\t\t^^^^^^ ", @@ -43,16 +26,18 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] -test.f(0x0, 1)", +test.f(0x0, 1) + a.call{value: x}(\"\") -- untrusted external call", "severity": "warning", "sourceLocation": { - "end": 289, + "end": 339, "file": "A", - "start": 283 + "start": 333 }, "type": "Warning" } diff --git a/test/cmdlineTests/standard_model_checker_targets_overflow_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_overflow_chc/input.json index 522d2480ca57..0141cbdb0999 100644 --- a/test/cmdlineTests/standard_model_checker_targets_overflow_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_overflow_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_overflow_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_overflow_chc/output.json index 1b0078d57975..6180cdef7a15 100644 --- a/test/cmdlineTests/standard_model_checker_targets_overflow_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_overflow_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "4984", @@ -27,6 +8,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() @@ -43,6 +25,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/input.json index 7d2dc69e31eb..430201dbf6f5 100644 --- a/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/output.json index 6ac6acd960f4..ee0e0a6efe72 100644 --- a/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_pop_empty_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "2529", @@ -27,14 +8,16 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> A:13:7: + a.call{value: x}(\"\") -- untrusted external call + --> A:14:7: | -13 | \t\t\t\t\t\tarr.pop(); +14 | \t\t\t\t\t\tarr.pop(); | \t\t\t\t\t\t^^^^^^^^^ ", @@ -43,16 +26,18 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] -test.f(0x0, 1)", +test.f(0x0, 1) + a.call{value: x}(\"\") -- untrusted external call", "severity": "warning", "sourceLocation": { - "end": 275, + "end": 325, "file": "A", - "start": 266 + "start": 316 }, "type": "Warning" } diff --git a/test/cmdlineTests/standard_model_checker_targets_underflow_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_underflow_chc/input.json index ca33d2fdcc66..e590fcd4d888 100644 --- a/test/cmdlineTests/standard_model_checker_targets_underflow_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_underflow_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_underflow_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_underflow_chc/output.json index 67218582ba8f..373646fa7002 100644 --- a/test/cmdlineTests/standard_model_checker_targets_underflow_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_underflow_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "3944", @@ -27,6 +8,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -43,6 +25,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/input.json index 50f0e82dc583..6d4ad0c74a50 100644 --- a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/output.json index 8f28e7961574..0ab2d1d9884e 100644 --- a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_assert_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "3944", @@ -27,6 +8,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -43,6 +25,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -64,6 +47,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() @@ -80,6 +64,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() @@ -101,14 +86,16 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] test.f(0x0, 1) - --> A:12:7: + a.call{value: x}(\"\") -- untrusted external call + --> A:13:7: | -12 | \t\t\t\t\t\tassert(x > 0); +13 | \t\t\t\t\t\tassert(x > 0); | \t\t\t\t\t\t^^^^^^^^^^^^^ ", @@ -117,16 +104,18 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = true Transaction trace: test.constructor() State: arr = [] -test.f(0x0, 1)", +test.f(0x0, 1) + a.call{value: x}(\"\") -- untrusted external call", "severity": "warning", "sourceLocation": { - "end": 258, + "end": 308, "file": "A", - "start": 245 + "start": 295 }, "type": "Warning" } diff --git a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/input.json b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/input.json index 9fc834fd860f..a03420305891 100644 --- a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/output.json b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/output.json index 97442455c0b8..44c3d234085e 100644 --- a/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/output.json +++ b/test/cmdlineTests/standard_model_checker_targets_underflow_overflow_chc/output.json @@ -1,24 +1,5 @@ { "errors": [ - { - "component": "general", - "errorCode": "9207", - "formattedMessage": "Warning: 'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead. - --> A:11:7: - | -11 | \t\t\t\t\t\ta.transfer(x); - | \t\t\t\t\t\t^^^^^^^^^^ - -", - "message": "'transfer' is deprecated and scheduled for removal. Use 'call{value: }(\"\")' instead.", - "severity": "warning", - "sourceLocation": { - "end": 234, - "file": "A", - "start": 224 - }, - "type": "Warning" - }, { "component": "general", "errorCode": "3944", @@ -27,6 +8,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -43,6 +25,7 @@ Counterexample: arr = [] a = 0x0 x = 0 +success = false Transaction trace: test.constructor() @@ -64,6 +47,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() @@ -80,6 +64,7 @@ Counterexample: arr = [] a = 0x0 x = 1 +success = false Transaction trace: test.constructor() diff --git a/test/cmdlineTests/standard_model_checker_targets_wrong_target_types/input.json b/test/cmdlineTests/standard_model_checker_targets_wrong_target_types/input.json index a89271975cac..3e8b7414f08f 100644 --- a/test/cmdlineTests/standard_model_checker_targets_wrong_target_types/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_wrong_target_types/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_wrong_target_types_2/input.json b/test/cmdlineTests/standard_model_checker_targets_wrong_target_types_2/input.json index 136ce0978f91..0f450668dd76 100644 --- a/test/cmdlineTests/standard_model_checker_targets_wrong_target_types_2/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_wrong_target_types_2/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; diff --git a/test/cmdlineTests/standard_model_checker_targets_wrong_targets/input.json b/test/cmdlineTests/standard_model_checker_targets_wrong_targets/input.json index 1788fb6d5508..a2f3606757b4 100644 --- a/test/cmdlineTests/standard_model_checker_targets_wrong_targets/input.json +++ b/test/cmdlineTests/standard_model_checker_targets_wrong_targets/input.json @@ -11,7 +11,8 @@ --x; x + type(uint).max; 2 / x; - a.transfer(x); + (bool success, ) = a.call{value: x}(\"\"); + require(success); assert(x > 0); arr.pop(); arr[x]; From 041b918885a642a28525a3d1f4a2dda3d26f8a7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Fri, 10 Oct 2025 20:45:01 +0200 Subject: [PATCH 28/73] Reword docs about linux packages and add info about Nix --- docs/installing-solidity.rst | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/docs/installing-solidity.rst b/docs/installing-solidity.rst index 97a754eaaab0..f061829ecf32 100644 --- a/docs/installing-solidity.rst +++ b/docs/installing-solidity.rst @@ -113,23 +113,34 @@ self-contained (i.e. it does not refer to any external files that would have to Linux Packages ============== -Binary packages of Solidity are available at -`solidity/releases `_. +We provide :ref:`standalone binaries ` of the compiler that should run on most +distributions without any additional installation steps. Ubuntu packages for versions up to 0.8.30 are available in the `ethereum/ethereum PPA `_. However, we have discontinued this distribution method and future versions will not be added there. -Furthermore, some Linux distributions provide their own packages. These packages are not directly -maintained by us but usually kept up-to-date by the respective package maintainers. +Some Linux distributions provide their own packages. +These packages are not directly maintained by us but usually kept up-to-date by the respective +package maintainers. -For example, Arch Linux has packages for the latest development version as AUR packages: `solidity `_ -and `solidity-bin `_. +Unofficial, community-maintained scripts for building and installing the compiler are also +available for some distributions: + +- Arch Linux / (AUR): + + - `solidity `_ (builds from source), + - `solidity-bin `_ (uses our standalone binaries). + +- Nix: + + - `solc.nix `_ (builds from source). .. note:: - Please be aware that `AUR `_ packages - are user-produced content and unofficial packages. Exercise caution when using them. + Please be aware that these scripts are produced and maintained by users and not vetted in any + way by the distro maintainers. + Exercise caution when using them. There is also a `snap package `_, however, it is **currently unmaintained**. It is installable in all the `supported Linux distros `_. To @@ -192,6 +203,8 @@ Install it using ``brew``: # eg. Install 0.4.8 brew install solidity.rb +.. _static-binaries: + Static Binaries =============== From c1975a232f5a77d9ccd38b1fafbb0b3251c88c2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Sat, 11 May 2024 17:33:03 +0200 Subject: [PATCH 29/73] Remove the prerequisite steps from the default optimizer sequence --- Changelog.md | 1 + docs/using-the-compiler.rst | 2 +- libsolidity/interface/OptimiserSettings.h | 8 ++++---- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Changelog.md b/Changelog.md index 655e66e5418a..d1bc022e3a23 100644 --- a/Changelog.md +++ b/Changelog.md @@ -3,6 +3,7 @@ Language Features: Compiler Features: +* Yul Optimizer: Remove redundant prerequisite steps from the default optimizer sequence. Bugfixes: diff --git a/docs/using-the-compiler.rst b/docs/using-the-compiler.rst index 93d61af291ad..dbc797079454 100644 --- a/docs/using-the-compiler.rst +++ b/docs/using-the-compiler.rst @@ -349,7 +349,7 @@ Input Description // In particular if the whole value consists only of the delimiter, both sequences are empty. // Note that there are several hard-coded steps that always run, even when both sequences are empty. // For more information see "The Optimizer > Selecting Optimizations". - "optimizerSteps": "dhfoDgvulfnTUtnIf..." + "optimizerSteps": "dfDvulfnTUtnIf..." } } }, diff --git a/libsolidity/interface/OptimiserSettings.h b/libsolidity/interface/OptimiserSettings.h index d282e139d22a..eec1e42b0d8c 100644 --- a/libsolidity/interface/OptimiserSettings.h +++ b/libsolidity/interface/OptimiserSettings.h @@ -42,7 +42,7 @@ enum class OptimisationPreset struct OptimiserSettings { static char constexpr DefaultYulOptimiserSteps[] = - "dhfoDgvulfnTUtnIf" // None of these can make stack problems worse + "dfDvulfnTUtnIf" // None of these can make stack problems worse "xa[r]EscLM" // Turn into SSA and simplify "Vcul [j]" // Reverse SSA @@ -51,13 +51,13 @@ struct OptimiserSettings "Trpeul" // Run functional expression inliner "xa[r]cL" // Turn into SSA again and simplify - "gvifM" // Run full inliner + "vifM" // Run full inliner "CTUca[r]LSsTFOtfDnca[r]Iulc" // SSA plus simplify "scCTUt" - "gvifM" // Run full inliner + "vifM" // Run full inliner "x[scCTUt] TOntnfDIul" // Perform structural simplification - "gvifM" // Run full inliner + "vifM" // Run full inliner "jmul[jul] VcTOcul jmul"; // Make source short and pretty From 2583eccd17cf70cc8ff984e6866b197d6259fe58 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Tue, 6 Jan 2026 12:59:30 +0100 Subject: [PATCH 30/73] EVM instruction interpreter: Add support for loadimmutable and setimmutable Theoretically, loadimmutable inserts a placeholder into the contract to be deployed which is then replaced by setimmutable once the runtime code is loaded into memory. The interpreter is mainly used for differential fuzzing so we should satisfy that correct code never fails and we can still detect bugs otherwise, most of the time. Therefore loadimmutable is decoupled from setimmutable and just returns a random value (hash of the identifier), setimmutable is treated as a no-op. --- .../isoltestTesting/loadimmutable.yul | 11 ++++++++++ .../isoltestTesting/setimmutable_stub.yul | 9 +++++++++ .../EVMInstructionInterpreter.cpp | 20 +++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 test/libyul/yulInterpreterTests/isoltestTesting/loadimmutable.yul create mode 100644 test/libyul/yulInterpreterTests/isoltestTesting/setimmutable_stub.yul diff --git a/test/libyul/yulInterpreterTests/isoltestTesting/loadimmutable.yul b/test/libyul/yulInterpreterTests/isoltestTesting/loadimmutable.yul new file mode 100644 index 000000000000..3b13520f14a2 --- /dev/null +++ b/test/libyul/yulInterpreterTests/isoltestTesting/loadimmutable.yul @@ -0,0 +1,11 @@ +{ + // yields some value based on the hash of the argument literal + let value := loadimmutable("address") + mstore(0, value) +} +// ---- +// Trace: +// Memory dump: +// 0: 421683f821a0574472445355be6d2b769119e8515f8376a1d7878523dfdecf7b +// Storage dump: +// Transient storage dump: diff --git a/test/libyul/yulInterpreterTests/isoltestTesting/setimmutable_stub.yul b/test/libyul/yulInterpreterTests/isoltestTesting/setimmutable_stub.yul new file mode 100644 index 000000000000..2becc61b6e5a --- /dev/null +++ b/test/libyul/yulInterpreterTests/isoltestTesting/setimmutable_stub.yul @@ -0,0 +1,9 @@ +{ + // implemented as no-op + setimmutable(42, "42", 42) +} +// ---- +// Trace: +// Memory dump: +// Storage dump: +// Transient storage dump: diff --git a/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp b/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp index cec5d5501346..9d46c2b8934b 100644 --- a/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp +++ b/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp @@ -565,6 +565,26 @@ u256 EVMInstructionInterpreter::evalBuiltin( return 0; } + if (fun == "loadimmutable") + { + yulAssert(_arguments.size() == 1); + yulAssert(std::holds_alternative(_arguments[0])); + std::string const identifier = formatLiteral(std::get(_arguments[0])); + // Return a deterministic value based on the identifier. + // This is sufficient for differential fuzzing since the same identifier + // will always return the same value, maintaining trace equivalence. + return u256(h256(keccak256(identifier))); + } + + if (fun == "setimmutable") + { + yulAssert(_arguments.size() == 3); + // No-op: The real implementation patches placeholder bytes in memory-loaded runtime code. + // For differential fuzzing, this ensures correct code never fails (no false positives), though some + // bugs in setimmutable handling may not be detected (potential false negatives). + return 0; + } + yulAssert(false, "Unknown builtin: " + fun); } From 940aa92a382f210cc0b679fadbd5b8b264ec84ae Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 19 Jan 2026 17:46:35 +0100 Subject: [PATCH 31/73] EVMInstruction Interpreter: Improve linkersymbol to not just yield constant 0 --- .../isoltestTesting/linkersymbol.yul | 11 +++++++++++ .../yulInterpreter/EVMInstructionInterpreter.cpp | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 test/libyul/yulInterpreterTests/isoltestTesting/linkersymbol.yul diff --git a/test/libyul/yulInterpreterTests/isoltestTesting/linkersymbol.yul b/test/libyul/yulInterpreterTests/isoltestTesting/linkersymbol.yul new file mode 100644 index 000000000000..d7b896c14f66 --- /dev/null +++ b/test/libyul/yulInterpreterTests/isoltestTesting/linkersymbol.yul @@ -0,0 +1,11 @@ +{ + // yields some value based on the hash of the argument literal + let value := linkersymbol("address") + mstore(0, value) +} +// ---- +// Trace: +// Memory dump: +// 0: 421683f821a0574472445355be6d2b769119e8515f8376a1d7878523dfdecf7b +// Storage dump: +// Transient storage dump: diff --git a/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp b/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp index 9d46c2b8934b..8081a9df6eec 100644 --- a/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp +++ b/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp @@ -562,7 +562,7 @@ u256 EVMInstructionInterpreter::evalBuiltin( std::string const placeholder = formatLiteral(std::get(_arguments[0])); h256 const identifier(keccak256(placeholder)); m_linkerSymbols.emplace(identifier, placeholder); - return 0; + return u256(identifier); } if (fun == "loadimmutable") From e80f7db293eb32e3a974753c40a45bf5c36c5c72 Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Mon, 26 Jan 2026 18:39:25 +0100 Subject: [PATCH 32/73] Fix style check to detect misaligned pointer declarations --- scripts/check_style.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/check_style.sh b/scripts/check_style.sh index d67f7b60ca22..5ea0e07d5477 100755 --- a/scripts/check_style.sh +++ b/scripts/check_style.sh @@ -55,7 +55,7 @@ FORMATERROR=$( preparedGrep "^ [^*]|[^*] | [^*]" # uses spaces for indentation or mixes spaces and tabs preparedGrep "[a-zA-Z0-9_]\s*[&][a-zA-Z_]" | grep -E -v "return [&]" # right-aligned reference ampersand (needs to exclude return) # right-aligned reference pointer star (needs to exclude return and comments) - preparedGrep "[a-zA-Z0-9_]\s*[*][a-zA-Z_]" | grep -E -v -e "return [*]" -e "^* [*]" -e "^*//.*" + preparedGrep "[a-zA-Z0-9_]\s*[*][a-zA-Z_]" | grep -E -v -e "return [*]" -e ":[0-9]+:\s*\*\s" -e "//" # unqualified move()/forward() checks, i.e. make sure that std::move() and std::forward() are used instead of move() and forward() preparedGrep "move\(.+\)" | grep -v "std::move" | grep -E "[^a-z]move" preparedGrep "forward\(.+\)" | grep -v "std::forward" | grep -E "[^a-z]forward" From b8d14a5a251e20ec02df329c34519061b697f646 Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Mon, 26 Jan 2026 18:41:46 +0100 Subject: [PATCH 33/73] Fix pointer declaration alignment style --- libsolidity/analysis/ControlFlowBuilder.h | 2 +- libsolidity/analysis/TypeChecker.cpp | 2 +- libsolidity/ast/Types.cpp | 2 +- libsolidity/codegen/CompilerContext.h | 2 +- libsolidity/codegen/ExpressionCompiler.cpp | 2 +- libyul/backends/evm/StackLayoutGenerator.cpp | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libsolidity/analysis/ControlFlowBuilder.h b/libsolidity/analysis/ControlFlowBuilder.h index 7af843fcaec9..92ebe4f88a2b 100644 --- a/libsolidity/analysis/ControlFlowBuilder.h +++ b/libsolidity/analysis/ControlFlowBuilder.h @@ -152,7 +152,7 @@ class ControlFlowBuilder: private ASTConstVisitor, private yul::ASTWalker CFGNode* newLabel(); CFGNode* createLabelHere(); - void placeAndConnectLabel(CFGNode *_node); + void placeAndConnectLabel(CFGNode* _node); CFG::NodeContainer& m_nodeContainer; diff --git a/libsolidity/analysis/TypeChecker.cpp b/libsolidity/analysis/TypeChecker.cpp index 8556487ff4ca..b54e591d20b2 100644 --- a/libsolidity/analysis/TypeChecker.cpp +++ b/libsolidity/analysis/TypeChecker.cpp @@ -1447,7 +1447,7 @@ void TypeChecker::checkExpressionAssignment(Type const& _type, Expression const& { bool isLocalOrReturn = false; if (auto const* identifier = dynamic_cast(&_expression)) - if (auto const *variableDeclaration = dynamic_cast(identifier->annotation().referencedDeclaration)) + if (auto const* variableDeclaration = dynamic_cast(identifier->annotation().referencedDeclaration)) if (variableDeclaration->isLocalOrReturn()) isLocalOrReturn = true; if (!isLocalOrReturn) diff --git a/libsolidity/ast/Types.cpp b/libsolidity/ast/Types.cpp index 316d99ba3edc..8454fd1306d5 100644 --- a/libsolidity/ast/Types.cpp +++ b/libsolidity/ast/Types.cpp @@ -3474,7 +3474,7 @@ MemberList::MemberMap FunctionType::nativeMembers(ASTNode const* _scope) const if (auto const* functionDefinition = dynamic_cast(m_declaration)) { solAssert(functionDefinition->visibility() > Visibility::Internal, ""); - auto const *contract = dynamic_cast(m_declaration->scope()); + auto const* contract = dynamic_cast(m_declaration->scope()); solAssert(contract, ""); solAssert(contract->isLibrary(), ""); return {{"selector", TypeProvider::fixedBytes(4)}}; diff --git a/libsolidity/codegen/CompilerContext.h b/libsolidity/codegen/CompilerContext.h index 638ee6939ca8..49a996c6c829 100644 --- a/libsolidity/codegen/CompilerContext.h +++ b/libsolidity/codegen/CompilerContext.h @@ -374,7 +374,7 @@ class CompilerContext /// Stack of current visited AST nodes, used for location attachment std::stack m_visitedNodes; /// The runtime context if in Creation mode, this is used for generating tags that would be stored into the storage and then used at runtime. - CompilerContext *m_runtimeContext; + CompilerContext* m_runtimeContext; /// The index of the runtime subroutine. evmasm::SubAssemblyID m_runtimeSub{}; /// An index of low-level function labels by name. diff --git a/libsolidity/codegen/ExpressionCompiler.cpp b/libsolidity/codegen/ExpressionCompiler.cpp index 2927444e2be3..49313c8925c6 100644 --- a/libsolidity/codegen/ExpressionCompiler.cpp +++ b/libsolidity/codegen/ExpressionCompiler.cpp @@ -2298,7 +2298,7 @@ bool ExpressionCompiler::visit(IndexRangeAccess const& _indexAccess) Type const& baseType = *_indexAccess.baseExpression().annotation().type; - ArrayType const *arrayType = dynamic_cast(&baseType); + ArrayType const* arrayType = dynamic_cast(&baseType); if (!arrayType) if (ArraySliceType const* sliceType = dynamic_cast(&baseType)) arrayType = &sliceType->arrayType(); diff --git a/libyul/backends/evm/StackLayoutGenerator.cpp b/libyul/backends/evm/StackLayoutGenerator.cpp index f6d1108eeb78..9a37adeb25bb 100644 --- a/libyul/backends/evm/StackLayoutGenerator.cpp +++ b/libyul/backends/evm/StackLayoutGenerator.cpp @@ -371,7 +371,7 @@ void StackLayoutGenerator::processEntryPoint(CFG::BasicBlock const& _entry, CFG: // entry layout of the backwards jump target as the initial exit layout of the backwards-jumping block. while (!toVisit.empty()) { - CFG::BasicBlock const *block = *toVisit.begin(); + CFG::BasicBlock const* block = *toVisit.begin(); toVisit.pop_front(); if (visited.count(block)) From 2eea2ae53c2ebe5e15238c19954d43768afc745e Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Mon, 26 Jan 2026 18:48:31 +0100 Subject: [PATCH 34/73] Fix unnecessary escaping in comment exclusion regex --- scripts/check_style.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/check_style.sh b/scripts/check_style.sh index 5ea0e07d5477..7188f84f2b33 100755 --- a/scripts/check_style.sh +++ b/scripts/check_style.sh @@ -59,7 +59,7 @@ FORMATERROR=$( # unqualified move()/forward() checks, i.e. make sure that std::move() and std::forward() are used instead of move() and forward() preparedGrep "move\(.+\)" | grep -v "std::move" | grep -E "[^a-z]move" preparedGrep "forward\(.+\)" | grep -v "std::forward" | grep -E "[^a-z]forward" -) | grep -E -v -e "^[a-zA-Z\./]*:[0-9]*:\s*\/(\/|\*)" -e "^test/" || true +) | grep -E -v -e "^[a-zA-Z./]*:[0-9]*:\s*/[/*]" -e "^test/" || true ) # Special error handling for `using namespace std;` exclusion, since said statement can be present in the test directory From 12004a1a5a3a5c1f0207a1762cb47002cbe2ef10 Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Wed, 28 Jan 2026 10:58:51 +0100 Subject: [PATCH 35/73] Refactor ccache build commands into a single `run_with_ccache_unless_tag` command - Remove CCACHE_ENABLED and use CCACHE_DISABLE instead --- .circleci/config.yml | 163 +++++++++++---------------------- scripts/ci/build.sh | 20 ++-- scripts/ci/build_emscripten.sh | 18 ++-- scripts/ci/build_ossfuzz.sh | 20 ++-- scripts/ci/build_win.sh | 52 +++++------ 5 files changed, 97 insertions(+), 176 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 1b6a309fc1da..2fd7fe83a575 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -75,16 +75,20 @@ commands: event: release condition: on_success - ensure_ccache_key: - description: "Fail fast when CCACHE_KEY is missing." + ensure_ccache_key_unless_tag: + description: "Fail fast when CCACHE_KEY is missing (skipped on tags)." steps: - - run: - name: Check CCACHE_KEY - command: | - if [ -z "${CCACHE_KEY:-}" ]; then - echo "CCACHE_KEY is not set. Please set it in CircleCI environment settings." - exit 1 - fi + - when: + condition: + equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: Check CCACHE_KEY + command: | + if [ -z "${CCACHE_KEY:-}" ]; then + echo "CCACHE_KEY is not set. Please set it in CircleCI environment settings." + exit 1 + fi restore_ccache_if_allowed: description: "Restore ccache unless on a tag or a skipped branch." @@ -123,6 +127,29 @@ commands: key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} paths: - ~/.ccache + run_with_ccache_unless_tag: + description: "Run a command with ccache enabled unless building a tag." + parameters: + command: + type: string + step_name: + type: string + steps: + - when: + condition: + equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: << parameters.step_name >> (ccache) + command: << parameters.command >> + - when: + condition: + not: + equal: ["", << pipeline.git.tag >>] + steps: + - run: + name: << parameters.step_name >> (no ccache) + command: CCACHE_DISABLE=1 << parameters.command >> prepare_bytecode_report: description: "Generate bytecode report and upload it as an artifact." @@ -257,60 +284,22 @@ commands: run_build: steps: - - when: - condition: - equal: ["", << pipeline.git.tag >>] - steps: - - ensure_ccache_key + - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: Build (ccache) - command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build.sh - - when: - condition: - or: - - not: - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: Build (no ccache) - command: scripts/ci/build.sh - + - run_with_ccache_unless_tag: + step_name: Build + command: scripts/ci/build.sh - save_ccache_if_develop run_build_ossfuzz: steps: - - when: - condition: - equal: ["", << pipeline.git.tag >>] - steps: - - ensure_ccache_key + - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: Build_ossfuzz (ccache) - command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build_ossfuzz.sh - - when: - condition: - or: - - not: - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: Build_ossfuzz (no ccache) - command: scripts/ci/build_ossfuzz.sh - + - run_with_ccache_unless_tag: + step_name: Build_ossfuzz + command: scripts/ci/build_ossfuzz.sh - save_ccache_if_develop run_proofs: @@ -1352,32 +1341,12 @@ jobs: MAKEFLAGS: -j 10 steps: - checkout - - when: - condition: - equal: ["", << pipeline.git.tag >>] - steps: - - ensure_ccache_key + - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: Build (ccache) - command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build_emscripten.sh - - when: - condition: - or: - - not: - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: Build (no ccache) - command: | - scripts/ci/build_emscripten.sh - + - run_with_ccache_unless_tag: + step_name: Build + command: scripts/ci/build_emscripten.sh - save_ccache_if_develop - store_artifacts: path: upload/soljson.js @@ -1855,39 +1824,13 @@ jobs: key: dependencies-win-{{ arch }}-{{ checksum "scripts/install_deps.ps1" }} paths: - .\deps - - when: - condition: - equal: ["", << pipeline.git.tag >>] - steps: - - ensure_ccache_key + - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - - when: - condition: - and: - - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: "Building solidity (ccache)" - command: CCACHE_ENABLED=${CCACHE_ENABLED:-1} scripts/ci/build_win.sh - - when: - condition: - or: - - not: - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: "Building solidity (no ccache)" - command: scripts/ci/build_win.sh - # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. - - when: - condition: - equal: ["ci-ccache", << pipeline.git.branch >>] - steps: - - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache - paths: - - ~/.ccache + - run_with_ccache_unless_tag: + step_name: "Building solidity" + command: scripts/ci/build_win.sh + - save_ccache_if_develop - run: name: "Run solc.exe to make sure build was successful." command: .\build\solc\Release\solc.exe --version diff --git a/scripts/ci/build.sh b/scripts/ci/build.sh index 385d2d898915..e31b3f6f078e 100755 --- a/scripts/ci/build.sh +++ b/scripts/ci/build.sh @@ -16,23 +16,17 @@ cd build [[ -n $COVERAGE && -z $CIRCLE_TAG ]] && CMAKE_OPTIONS="$CMAKE_OPTIONS -DCOVERAGE=ON" -if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - export CCACHE_DIR="$HOME/.ccache" - export CCACHE_BASEDIR="$ROOTDIR" - export CCACHE_NOHASHDIR=1 - CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" - mkdir -p "$CCACHE_DIR" -fi +export CCACHE_DIR="$HOME/.ccache" +export CCACHE_BASEDIR="$ROOTDIR" +export CCACHE_NOHASHDIR=1 +CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" +mkdir -p "$CCACHE_DIR" # shellcheck disable=SC2086 cmake .. -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Release}" $CMAKE_OPTIONS -if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - ccache -z -fi +ccache -z cmake --build . -if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - ccache -s -fi +ccache -s diff --git a/scripts/ci/build_emscripten.sh b/scripts/ci/build_emscripten.sh index bf19bad3600d..035eedccb11a 100755 --- a/scripts/ci/build_emscripten.sh +++ b/scripts/ci/build_emscripten.sh @@ -54,14 +54,12 @@ function build() { # TODO: This can be removed if and when all usages of `move()` in our codebase use the `std::` qualifier. CMAKE_CXX_FLAGS="-Wno-unqualified-std-cast-call" - if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - export CCACHE_DIR="$HOME/.ccache" - CCACHE_BASEDIR="$(pwd)" - export CCACHE_BASEDIR - export CCACHE_NOHASHDIR=1 - mkdir -p "$CCACHE_DIR" - ccache -z - fi + export CCACHE_DIR="$HOME/.ccache" + CCACHE_BASEDIR="$(pwd)" + export CCACHE_BASEDIR + export CCACHE_NOHASHDIR=1 + mkdir -p "$CCACHE_DIR" + ccache -z mkdir -p "$build_dir" cd "$build_dir" @@ -73,9 +71,7 @@ function build() { -DTESTS=0 \ .. make soljson - if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - ccache -s - fi + ccache -s cd .. mkdir -p upload diff --git a/scripts/ci/build_ossfuzz.sh b/scripts/ci/build_ossfuzz.sh index 883c939b89ea..f3e65d22dd86 100755 --- a/scripts/ci/build_ossfuzz.sh +++ b/scripts/ci/build_ossfuzz.sh @@ -18,24 +18,18 @@ function generate_protobuf_bindings function build_fuzzers { cd "${BUILDDIR}" - if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - export CCACHE_DIR="$HOME/.ccache" - export CCACHE_BASEDIR="$ROOTDIR" - export CCACHE_NOHASHDIR=1 - CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" - mkdir -p "$CCACHE_DIR" - fi + export CCACHE_DIR="$HOME/.ccache" + export CCACHE_BASEDIR="$ROOTDIR" + export CCACHE_NOHASHDIR=1 + CMAKE_OPTIONS="${CMAKE_OPTIONS:-} -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" + mkdir -p "$CCACHE_DIR" # shellcheck disable=SC2086 cmake .. -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Release}" \ -DCMAKE_TOOLCHAIN_FILE="${ROOTDIR}"/cmake/toolchains/libfuzzer.cmake \ $CMAKE_OPTIONS - if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - ccache -z - fi + ccache -z make ossfuzz ossfuzz_proto ossfuzz_abiv2 -j 4 - if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - ccache -s - fi + ccache -s } generate_protobuf_bindings diff --git a/scripts/ci/build_win.sh b/scripts/ci/build_win.sh index 07604c8eb854..bd464647e73d 100755 --- a/scripts/ci/build_win.sh +++ b/scripts/ci/build_win.sh @@ -11,29 +11,27 @@ CMAKE_VS_GLOBALS_ARG=() cd "$ROOTDIR" "${ROOTDIR}/scripts/prerelease_suffix.sh" "$prerelease_source" "$CIRCLE_TAG" > prerelease.txt -if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - export CCACHE_DIR="$HOME/.ccache" - export CCACHE_BASEDIR="$ROOTDIR" - export CCACHE_NOHASHDIR=1 - export CCACHE_COMPILERTYPE=msvc - VSWHERE="${VSWHERE:-C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe}" - VS_INSTALL="$("$VSWHERE" -latest -products "*" \ - -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 \ - -property installationPath | tr -d '\r')" - VCTOOLS_VERSION="$(tr -d '\r' < "$VS_INSTALL/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt")" - CCACHE_COMPILER="$VS_INSTALL/VC/Tools/MSVC/$VCTOOLS_VERSION/bin/Hostx64/x64/cl.exe" - CCACHE_COMPILER="${CCACHE_COMPILER//\\//}" - export CCACHE_COMPILER - PATH="$ROOTDIR/deps/ccache:$(dirname "$CCACHE_COMPILER"):$PATH" - export PATH - # Use a Windows-style path for Visual Studio globals. - WIN_PWD="$(pwd -W)" - # Visual Studio generator doesn't use compiler launchers; use ccache masquerade. - # See https://github.com/ccache/ccache/wiki/MS-Visual-Studio - CMAKE_VS_GLOBALS="CLToolPath=${WIN_PWD}/deps/ccache;UseMultiToolTask=true" - CMAKE_VS_GLOBALS_ARG=(-DCMAKE_VS_GLOBALS="$CMAKE_VS_GLOBALS") - mkdir -p "$CCACHE_DIR" -fi +export CCACHE_DIR="$HOME/.ccache" +export CCACHE_BASEDIR="$ROOTDIR" +export CCACHE_NOHASHDIR=1 +export CCACHE_COMPILERTYPE=msvc +VSWHERE="${VSWHERE:-C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe}" +VS_INSTALL="$("$VSWHERE" -latest -products "*" \ + -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 \ + -property installationPath | tr -d '\r')" +VCTOOLS_VERSION="$(tr -d '\r' < "$VS_INSTALL/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt")" +CCACHE_COMPILER="$VS_INSTALL/VC/Tools/MSVC/$VCTOOLS_VERSION/bin/Hostx64/x64/cl.exe" +CCACHE_COMPILER="${CCACHE_COMPILER//\\//}" +export CCACHE_COMPILER +PATH="$ROOTDIR/deps/ccache:$(dirname "$CCACHE_COMPILER"):$PATH" +export PATH +# Use a Windows-style path for Visual Studio globals. +WIN_PWD="$(pwd -W)" +# Visual Studio generator doesn't use compiler launchers; use ccache masquerade. +# See https://github.com/ccache/ccache/wiki/MS-Visual-Studio +CMAKE_VS_GLOBALS="CLToolPath=${WIN_PWD}/deps/ccache;UseMultiToolTask=true" +CMAKE_VS_GLOBALS_ARG=(-DCMAKE_VS_GLOBALS="$CMAKE_VS_GLOBALS") +mkdir -p "$CCACHE_DIR" mkdir -p build/ cd build/ @@ -50,9 +48,7 @@ boost_dir=("${ROOTDIR}/deps/boost/lib/cmake/Boost-"*) "${CMAKE_VS_GLOBALS_ARG[@]}" \ ${CMAKE_OPTIONS:-} \ .. -if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - ccache -z -fi +ccache -z MSBuild.exe solidity.sln \ -property:Configuration=Release \ -maxCpuCount:10 \ @@ -62,6 +58,4 @@ MSBuild.exe solidity.sln \ -j 10 \ --target install \ --config Release -if [[ "${CCACHE_ENABLED:-}" == "1" ]]; then - ccache -s -fi +ccache -s From 81070d39868353ddada3f6c37ce052061f14ebec Mon Sep 17 00:00:00 2001 From: cui Date: Thu, 29 Jan 2026 16:41:30 +0800 Subject: [PATCH 36/73] perf: opt SimplePeepholeOptimizerMethod (#16426) perf: opt SimplePeepholeOptimizerMethod --- libevmasm/PeepholeOptimiser.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libevmasm/PeepholeOptimiser.cpp b/libevmasm/PeepholeOptimiser.cpp index 267700e457cd..7cd7c5e962ef 100644 --- a/libevmasm/PeepholeOptimiser.cpp +++ b/libevmasm/PeepholeOptimiser.cpp @@ -117,9 +117,10 @@ struct OpPop: SimplePeepholeOptimizerMethod if (_pop == Instruction::POP && _op.type() == Operation) { Instruction instr = _op.instruction(); - if (instructionInfo(instr, langutil::EVMVersion()).ret == 1 && !instructionInfo(instr, langutil::EVMVersion()).sideEffects) + auto const& info = instructionInfo(instr, langutil::EVMVersion()); + if (info.ret == 1 && !info.sideEffects) { - for (int j = 0; j < instructionInfo(instr, langutil::EVMVersion()).args; j++) + for (int j = 0; j < info.args; j++) *_out = {Instruction::POP, _op.debugData()}; return true; } From 04833a570c6f01f2f7f1a9d853321c327a66283b Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Mon, 2 Feb 2026 11:35:17 +0100 Subject: [PATCH 37/73] Update ccache commands to use 'develop' branch instead of 'ci-ccache' --- .circleci/config.yml | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2fd7fe83a575..8e4cd2fbfa1a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -93,12 +93,10 @@ commands: restore_ccache_if_allowed: description: "Restore ccache unless on a tag or a skipped branch." parameters: - # TODO: remove the line below - # Before merging this PR we need to use an alternative develop branch to test the functionality, `ci-ccache` skip_branches_regex: description: "Regex of branches that should skip restoring the cache." type: string - default: "^(ci-ccache|breaking)$" + default: "^(develop|breaking)$" steps: # Tags always skip ccache. Selected branches intentionally start from scratch. - when: @@ -112,19 +110,19 @@ commands: steps: - restore_cache: keys: - # Reuse cache produced on ci-ccache (prefix match; restores the most recent). - - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache- + # Reuse cache produced on develop (prefix match; restores the most recent). + - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-develop- save_ccache_if_develop: - description: "Save a fresh ccache only on the ci-ccache branch." + description: "Save a fresh ccache only on the develop branch." steps: - # On `ci-ccache` we always generate a fresh cache by never restoring and by saving under a unique key. + # On `develop` we always generate a fresh cache by never restoring and by saving under a unique key. - when: condition: - equal: ["ci-ccache", << pipeline.git.branch >>] + equal: ["develop", << pipeline.git.branch >>] steps: - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-ci-ccache-{{ .Revision }} + key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-develop-{{ .Revision }} paths: - ~/.ccache run_with_ccache_unless_tag: From 21e284ee234c6f5ae972ca66762ef0f7f1e578bd Mon Sep 17 00:00:00 2001 From: r0qs <457348+r0qs@users.noreply.github.com> Date: Fri, 19 Dec 2025 23:14:27 -0300 Subject: [PATCH 38/73] evmasm: Remove unused return value from `clearStorageLoop()` --- libsolidity/codegen/ArrayUtils.cpp | 16 +++++++--------- libsolidity/codegen/ArrayUtils.h | 2 +- .../array/copying/array_copy_including_array.sol | 8 ++++---- .../array/delete/delete_storage_array_packed.sol | 4 ++-- .../semanticTests/array/fixed_array_cleanup.sol | 4 ++-- .../array/pop/array_pop_array_transition.sol | 4 ++-- .../storage_boundary_delete_overflow_bug.sol | 4 ++-- ...storage_boundary_struct_array_mixed_types.sol | 4 ++-- .../storage_boundary_struct_array_multislot.sol | 4 ++-- .../structs/struct_delete_storage_with_array.sol | 8 ++++---- .../userDefinedValueType/calldata.sol | 8 ++++---- 11 files changed, 32 insertions(+), 34 deletions(-) diff --git a/libsolidity/codegen/ArrayUtils.cpp b/libsolidity/codegen/ArrayUtils.cpp index 841161fa91b6..80ee9553c0ae 100644 --- a/libsolidity/codegen/ArrayUtils.cpp +++ b/libsolidity/codegen/ArrayUtils.cpp @@ -402,7 +402,6 @@ void ArrayUtils::clearArray(ArrayType const& _typeIn) const ArrayUtils(_context).clearStorageLoop(TypeProvider::uint256()); else ArrayUtils(_context).clearStorageLoop(_type.baseType()); - _context << Instruction::POP; } solAssert(_context.stackHeight() == stackHeightStart - 2, ""); } @@ -425,9 +424,10 @@ void ArrayUtils::clearDynamicArray(ArrayType const& _type) const // stack: ref old_length m_context << Instruction::DUP1 << u256(31) << Instruction::LT; evmasm::AssemblyItem longByteArray = m_context.appendConditionalJump(); - m_context << Instruction::POP; + // Short byte array: no data slots to clear, just pop and exit + m_context << Instruction::POP << Instruction::POP; m_context.appendJumpTo(endTag); - m_context.adjustStackOffset(1); // needed because of jump + m_context.adjustStackOffset(2); // the longByteArray path has 2 more items on stack m_context << longByteArray; } // stack: ref old_length @@ -444,7 +444,6 @@ void ArrayUtils::clearDynamicArray(ArrayType const& _type) const clearStorageLoop(_type.baseType()); // cleanup m_context << endTag; - m_context << Instruction::POP; } void ArrayUtils::incrementDynamicArraySize(ArrayType const& _type) const @@ -585,13 +584,13 @@ void ArrayUtils::clearStorageLoop(Type const* _type) const m_context.callLowLevelFunction( "$clearStorageLoop_" + _type->identifier(), 2, - 1, + 0, [_type](CompilerContext& _context) { unsigned stackHeightStart = _context.stackHeight(); if (_type->category() == Type::Category::Mapping) { - _context << Instruction::POP; + _context << Instruction::POP << Instruction::POP; return; } // stack: start_pos slot_count @@ -618,9 +617,8 @@ void ArrayUtils::clearStorageLoop(Type const* _type) const // cleanup _context << zeroLoopEnd; // stack: start_pos slot_count i - _context << Instruction::POP << Instruction::POP; - // stack: start_pos - solAssert(_context.stackHeight() == stackHeightStart - 1, ""); + _context << Instruction::POP << Instruction::POP << Instruction::POP; + solAssert(_context.stackHeight() == stackHeightStart - 2, ""); } ); } diff --git a/libsolidity/codegen/ArrayUtils.h b/libsolidity/codegen/ArrayUtils.h index a62df8a7b2ab..a5eda28f5275 100644 --- a/libsolidity/codegen/ArrayUtils.h +++ b/libsolidity/codegen/ArrayUtils.h @@ -74,7 +74,7 @@ class ArrayUtils void popStorageArrayElement(ArrayType const& _type) const; /// Appends a loop that clears a sequence of storage slots of the given type. /// Stack pre: start_ref slot_count - /// Stack post: start_ref + /// Stack post: void clearStorageLoop(Type const* _type) const; /// Converts length to size (number of storage slots or calldata/memory bytes). /// if @a _pad then add padding to multiples of 32 bytes for calldata/memory. diff --git a/test/libsolidity/semanticTests/array/copying/array_copy_including_array.sol b/test/libsolidity/semanticTests/array/copying/array_copy_including_array.sol index ba50c7300f65..5f1dae910d6b 100644 --- a/test/libsolidity/semanticTests/array/copying/array_copy_including_array.sol +++ b/test/libsolidity/semanticTests/array/copying/array_copy_including_array.sol @@ -36,11 +36,11 @@ contract c { // ---- // test() -> 0x02000202 // gas irOptimized: 4560468 -// gas legacy: 4536566 -// gas legacyOptimized: 4456759 +// gas legacy: 4536539 +// gas legacyOptimized: 4456732 // storageEmpty -> 1 // clear() -> 0, 0 // gas irOptimized: 4488719 -// gas legacy: 4407780 -// gas legacyOptimized: 4385089 +// gas legacy: 4407759 +// gas legacyOptimized: 4385068 // storageEmpty -> 1 diff --git a/test/libsolidity/semanticTests/array/delete/delete_storage_array_packed.sol b/test/libsolidity/semanticTests/array/delete/delete_storage_array_packed.sol index 23b0466e7530..cf416c16d192 100644 --- a/test/libsolidity/semanticTests/array/delete/delete_storage_array_packed.sol +++ b/test/libsolidity/semanticTests/array/delete/delete_storage_array_packed.sol @@ -15,5 +15,5 @@ contract C { // ---- // f() -> 0, 0, 0 // gas irOptimized: 88028 -// gas legacy: 88799 -// gas legacyOptimized: 87706 +// gas legacy: 88796 +// gas legacyOptimized: 87704 diff --git a/test/libsolidity/semanticTests/array/fixed_array_cleanup.sol b/test/libsolidity/semanticTests/array/fixed_array_cleanup.sol index af0ec6b7faf0..86484ecdef09 100644 --- a/test/libsolidity/semanticTests/array/fixed_array_cleanup.sol +++ b/test/libsolidity/semanticTests/array/fixed_array_cleanup.sol @@ -16,6 +16,6 @@ contract c { // storageEmpty -> 0 // clear() -> // gas irOptimized: 97800 -// gas legacy: 97947 -// gas legacyOptimized: 97882 +// gas legacy: 97944 +// gas legacyOptimized: 97880 // storageEmpty -> 1 diff --git a/test/libsolidity/semanticTests/array/pop/array_pop_array_transition.sol b/test/libsolidity/semanticTests/array/pop/array_pop_array_transition.sol index 3b96397166ea..ed4e9b87737c 100644 --- a/test/libsolidity/semanticTests/array/pop/array_pop_array_transition.sol +++ b/test/libsolidity/semanticTests/array/pop/array_pop_array_transition.sol @@ -24,6 +24,6 @@ contract c { // ---- // test() -> 1, 2, 3 // gas irOptimized: 1828383 -// gas legacy: 1841995 -// gas legacyOptimized: 1821687 +// gas legacy: 1841877 +// gas legacyOptimized: 1821569 // storageEmpty -> 1 diff --git a/test/libsolidity/semanticTests/storage/storage_boundary_delete_overflow_bug.sol b/test/libsolidity/semanticTests/storage/storage_boundary_delete_overflow_bug.sol index 3ffb7774710a..09aae988e511 100644 --- a/test/libsolidity/semanticTests/storage/storage_boundary_delete_overflow_bug.sol +++ b/test/libsolidity/semanticTests/storage/storage_boundary_delete_overflow_bug.sol @@ -72,8 +72,8 @@ contract C { // gas legacyOptimized: 598016 // clearArray() // gas irOptimized: 580378 -// gas legacy: 582976 -// gas legacyOptimized: 581290 +// gas legacy: 582973 +// gas legacyOptimized: 581299 // x() -> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // gas irOptimized: 604108 // gas legacy: 644983 diff --git a/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_mixed_types.sol b/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_mixed_types.sol index 213dee1dae23..444f86286453 100644 --- a/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_mixed_types.sol +++ b/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_mixed_types.sol @@ -159,8 +159,8 @@ contract C { // gas legacyOptimized: 112505 // deleteBoundaryArray() // gas irOptimized: 177968 -// gas legacy: 180997 -// gas legacyOptimized: 178175 +// gas legacy: 180995 +// gas legacyOptimized: 178182 // canaryValue() -> 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff // boundaryArray() -> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // gas irOptimized: 113169 diff --git a/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_multislot.sol b/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_multislot.sol index 55e36cd08e06..05ad53cf0bfa 100644 --- a/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_multislot.sol +++ b/test/libsolidity/semanticTests/storage/storage_boundary_struct_array_multislot.sol @@ -121,8 +121,8 @@ contract C { // destArray() -> 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 // deleteBoundaryArray() // gas irOptimized: 137824 -// gas legacy: 137973 -// gas legacyOptimized: 137743 +// gas legacy: 137971 +// gas legacyOptimized: 137750 // canaryValue() -> 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff // boundaryArray() -> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // destArray() -> 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 diff --git a/test/libsolidity/semanticTests/structs/struct_delete_storage_with_array.sol b/test/libsolidity/semanticTests/structs/struct_delete_storage_with_array.sol index cd49ea27ad0e..7ae78437e408 100644 --- a/test/libsolidity/semanticTests/structs/struct_delete_storage_with_array.sol +++ b/test/libsolidity/semanticTests/structs/struct_delete_storage_with_array.sol @@ -43,9 +43,9 @@ contract C { // ---- // f() -> // gas irOptimized: 113388 -// gas legacy: 113588 -// gas legacyOptimized: 113104 +// gas legacy: 113583 +// gas legacyOptimized: 113119 // g() -> // gas irOptimized: 118768 -// gas legacy: 118766 -// gas legacyOptimized: 118188 +// gas legacy: 118761 +// gas legacyOptimized: 118203 diff --git a/test/libsolidity/semanticTests/userDefinedValueType/calldata.sol b/test/libsolidity/semanticTests/userDefinedValueType/calldata.sol index 03c6e11bcc3c..63f1ff1dd18e 100644 --- a/test/libsolidity/semanticTests/userDefinedValueType/calldata.sol +++ b/test/libsolidity/semanticTests/userDefinedValueType/calldata.sol @@ -50,12 +50,12 @@ contract C { // ---- // test_f() -> true // gas irOptimized: 122114 -// gas legacy: 126162 -// gas legacyOptimized: 122757 +// gas legacy: 126159 +// gas legacyOptimized: 122742 // test_g() -> true // gas irOptimized: 106248 -// gas legacy: 111824 -// gas legacyOptimized: 106606 +// gas legacy: 111821 +// gas legacyOptimized: 106591 // addresses(uint256): 0 -> 0x18 // addresses(uint256): 1 -> 0x19 // addresses(uint256): 3 -> 0x1b From cd1472967ce453feadbc8c3822559c1ece5acd17 Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Mon, 2 Feb 2026 15:55:24 +0100 Subject: [PATCH 39/73] Remove CCACHE_KEY from cache keys in CircleCI config --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 8e4cd2fbfa1a..70060258a525 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -111,7 +111,7 @@ commands: - restore_cache: keys: # Reuse cache produced on develop (prefix match; restores the most recent). - - v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-develop- + - v1-ccache-{{ .Environment.CIRCLE_JOB }}-develop- save_ccache_if_develop: description: "Save a fresh ccache only on the develop branch." @@ -122,7 +122,7 @@ commands: equal: ["develop", << pipeline.git.branch >>] steps: - save_cache: - key: v1-{{ .Environment.CCACHE_KEY }}-ccache-{{ .Environment.CIRCLE_JOB }}-develop-{{ .Revision }} + key: v1-ccache-{{ .Environment.CIRCLE_JOB }}-develop-{{ .Revision }} paths: - ~/.ccache run_with_ccache_unless_tag: From b8e0364bb678ffca2090becdeb6c48b13339abbb Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Mon, 2 Feb 2026 16:13:41 +0100 Subject: [PATCH 40/73] Remove `ensure_ccache_key_unless_tag` and its usages --- .circleci/config.yml | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 70060258a525..ff4246399218 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -75,21 +75,6 @@ commands: event: release condition: on_success - ensure_ccache_key_unless_tag: - description: "Fail fast when CCACHE_KEY is missing (skipped on tags)." - steps: - - when: - condition: - equal: ["", << pipeline.git.tag >>] - steps: - - run: - name: Check CCACHE_KEY - command: | - if [ -z "${CCACHE_KEY:-}" ]; then - echo "CCACHE_KEY is not set. Please set it in CircleCI environment settings." - exit 1 - fi - restore_ccache_if_allowed: description: "Restore ccache unless on a tag or a skipped branch." parameters: @@ -282,7 +267,6 @@ commands: run_build: steps: - - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - run_with_ccache_unless_tag: @@ -292,7 +276,6 @@ commands: run_build_ossfuzz: steps: - - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - run_with_ccache_unless_tag: @@ -1339,7 +1322,6 @@ jobs: MAKEFLAGS: -j 10 steps: - checkout - - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - run_with_ccache_unless_tag: @@ -1822,7 +1804,6 @@ jobs: key: dependencies-win-{{ arch }}-{{ checksum "scripts/install_deps.ps1" }} paths: - .\deps - - ensure_ccache_key_unless_tag - restore_ccache_if_allowed # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings - run_with_ccache_unless_tag: From eb3dc0c425d5e6b462fb6737fe0e1793df13c87c Mon Sep 17 00:00:00 2001 From: Marco Castignoli Date: Mon, 2 Feb 2026 16:24:44 +0100 Subject: [PATCH 41/73] Fix comment for resetting ccache --- .circleci/config.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index ff4246399218..27a331cd7c6f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -268,7 +268,7 @@ commands: run_build: steps: - restore_ccache_if_allowed - # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings + # WARNING! If you edit anything between here and save_cache, remember to invalidate the cache manually by bumping the version - run_with_ccache_unless_tag: step_name: Build command: scripts/ci/build.sh @@ -277,7 +277,7 @@ commands: run_build_ossfuzz: steps: - restore_ccache_if_allowed - # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings + # WARNING! If you edit anything between here and save_cache, remember to invalidate the cache manually by bumping the version - run_with_ccache_unless_tag: step_name: Build_ossfuzz command: scripts/ci/build_ossfuzz.sh @@ -1323,7 +1323,7 @@ jobs: steps: - checkout - restore_ccache_if_allowed - # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings + # WARNING! If you edit anything between here and save_cache, remember to invalidate the cache manually by bumping the version - run_with_ccache_unless_tag: step_name: Build command: scripts/ci/build_emscripten.sh @@ -1805,7 +1805,7 @@ jobs: paths: - .\deps - restore_ccache_if_allowed - # WARNING! If you edit anything between here and save_cache, remember to bump the CCACHE_KEY version in CircleCI environment settings + # WARNING! If you edit anything between here and save_cache, remember to invalidate the cache manually by bumping the version - run_with_ccache_unless_tag: step_name: "Building solidity" command: scripts/ci/build_win.sh From abeaab4409e10ac03f644d71f176e98a7d935177 Mon Sep 17 00:00:00 2001 From: Jacopo Pierantozzi Date: Thu, 29 Jan 2026 12:47:03 +0100 Subject: [PATCH 42/73] Clarify remapping rules in path-resolution documentation --- docs/path-resolution.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/path-resolution.rst b/docs/path-resolution.rst index 492959bc1ebb..2339a3624cb2 100644 --- a/docs/path-resolution.rst +++ b/docs/path-resolution.rst @@ -629,9 +629,9 @@ Here are the detailed rules governing the behavior of remappings: #. **At most one remapping is applied to a single import.** - - If multiple remappings match the same source unit name, the one with the longest matching - prefix is chosen. - - If prefixes are identical, the one specified last wins. + - If multiple remappings match the same source unit name, the one with the longest matching context is chosen. + - If contexts are identical, the one with the longest matching prefix is chosen. + - If contexts and prefixes are identical, the one specified last wins. - Remappings do not work on other remappings. For example ``a=b b=c c=d`` will not result in ``a`` being remapped to ``d``. From cf1a3b07aba8c6588bba8bb8827ed0632ed0bbb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Sat, 26 Apr 2025 00:54:14 +0200 Subject: [PATCH 43/73] EVMAssemblyTest: Warn about custom expectedExecutionsPerDeployment having no effect --- test/libevmasm/EVMAssemblyTest.cpp | 11 +++++++++++ test/libevmasm/EVMAssemblyTest.h | 1 + 2 files changed, 12 insertions(+) diff --git a/test/libevmasm/EVMAssemblyTest.cpp b/test/libevmasm/EVMAssemblyTest.cpp index 0c1dbb07ed7c..3bc43b188294 100644 --- a/test/libevmasm/EVMAssemblyTest.cpp +++ b/test/libevmasm/EVMAssemblyTest.cpp @@ -78,10 +78,13 @@ EVMAssemblyTest::EVMAssemblyTest(std::string const& _filename): "none" ); m_optimizerSettings = Assembly::OptimiserSettings::translateSettings(OptimiserSettings::preset(optimizationPreset)); + size_t defaultExpectedExecutionsPerDeployment = m_optimizerSettings.expectedExecutionsPerDeployment; m_optimizerSettings.expectedExecutionsPerDeployment = m_reader.sizetSetting( "optimizer.expectedExecutionsPerDeployment", m_optimizerSettings.expectedExecutionsPerDeployment ); + m_usingDefaultExpectedExecutionsPerDeployment = + m_optimizerSettings.expectedExecutionsPerDeployment == defaultExpectedExecutionsPerDeployment; auto const optimizerComponentSetting = [&](std::string const& _component, bool& _setting) { _setting = m_reader.boolSetting("optimizer." + _component, _setting); @@ -132,6 +135,14 @@ TestCase::TestResult EVMAssemblyTest::run(std::ostream& _stream, std::string con return checkResult(_stream, _linePrefix, _formatted); } + soltestAssert(evmAssemblyStack.evmAssembly()); + if (!m_usingDefaultExpectedExecutionsPerDeployment && evmAssemblyStack.evmAssembly()->numSubs() == 0) + // This is a common mistake. We can't issue a warning here, so let's report it as an error. + BOOST_THROW_EXCEPTION(std::runtime_error( + "The custom value specified for optimizer.expectedExecutionsPerDeployment has no effect " + "on the creation assembly, which is the only assembly in the test." + )); + try { evmAssemblyStack.assemble(); diff --git a/test/libevmasm/EVMAssemblyTest.h b/test/libevmasm/EVMAssemblyTest.h index 9059fd716d81..9a276ddeb6b4 100644 --- a/test/libevmasm/EVMAssemblyTest.h +++ b/test/libevmasm/EVMAssemblyTest.h @@ -75,6 +75,7 @@ class EVMAssemblyTest: public frontend::test::EVMVersionRestrictedTestCase AssemblyFormat m_assemblyFormat{}; std::string m_selectedOutputs; evmasm::Assembly::OptimiserSettings m_optimizerSettings; + bool m_usingDefaultExpectedExecutionsPerDeployment{}; }; } From f0486ba76b6ba4c3ff9b7892026b652036ca8fe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Mon, 2 Feb 2026 17:54:09 +0100 Subject: [PATCH 44/73] CI: Move constantinople and petersburg EVM runs back from nightly to the main workflow --- .circleci/config.yml | 2 +- .circleci/soltest_all.sh | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 27a331cd7c6f..55f12f669cb1 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1400,7 +1400,7 @@ jobs: - attach_workspace: at: build - run_soltest_all: - evm_versions: homestead byzantium constantinople petersburg + evm_versions: homestead byzantium - store_test_results: path: test_results/ - store_artifacts_test_results diff --git a/.circleci/soltest_all.sh b/.circleci/soltest_all.sh index effbc33da0da..6f8ea14f398f 100755 --- a/.circleci/soltest_all.sh +++ b/.circleci/soltest_all.sh @@ -31,7 +31,18 @@ REPODIR="$(realpath "$(dirname "$0")"/..)" # shellcheck source=scripts/common.sh source "${REPODIR}/scripts/common.sh" -DEFAULT_EVM_VALUES=(istanbul berlin london paris shanghai cancun prague osaka) +DEFAULT_EVM_VALUES=( + constantinople + petersburg + istanbul + berlin + london + paris + shanghai + cancun + prague + osaka +) EVMS_WITH_EOF=(osaka) # Deserialize the EVM_VALUES array if it was provided as argument or From fc639436584ddbdbf517cf1e12bbeff3bfda38f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Mon, 2 Feb 2026 18:05:34 +0100 Subject: [PATCH 45/73] CI: Replace homestead with prague and petersburg in the nightly run - homestead is useful on PRs while prague and petersburg did not introduce any changes in EVM behavior - Rename the job and explain why we're doing it --- .circleci/config.yml | 19 +++++++++++++++---- .circleci/soltest_all.sh | 3 +-- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 55f12f669cb1..1ca83b526fed 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -299,7 +299,7 @@ commands: run_soltest_all: parameters: # NOTE: If not specified, soltest_all.sh will use the default values as specified in the script. - # In other words, it will execute for all EVM versions that are not marked as deprecated. + # In other words, it will execute for all EVM versions that are not marked as low priority. evm_versions: description: "List of EVM versions (separated by space)." type: string @@ -1392,7 +1392,7 @@ jobs: - store_artifacts_test_results - matrix_notify_failure_unless_pr - t_ubu_soltest_deprecated_evm_versions: &t_ubu_soltest_deprecated_evm_versions + t_ubu_soltest_low_priority_evm_versions: &t_ubu_soltest_low_priority_evm_versions <<: *base_ubuntu2404_large parallelism: 50 steps: @@ -1400,7 +1400,18 @@ jobs: - attach_workspace: at: build - run_soltest_all: - evm_versions: homestead byzantium + # We test most EVM versions on every PR. The ones below are the exceptions. + # + # We do not test these at all. We were never doing that and no point starting now since + # they are deprecated anyway: + # - tangerineWhistle + # - spuriousDragon + # + # These have a low chance of breaking so we only run them in nightly to save credits: + # - byzantium: deprecated, if it breaks, homestead likely will as well + # - petersburg: no changes compared to constantinople + # - prague: no changes compared to cancun + evm_versions: byzantium petersburg prague - store_test_results: path: test_results/ - store_artifacts_test_results @@ -2259,7 +2270,7 @@ workflows: # Deprecated EVM versions tests - b_ubu: *requires_nothing - - t_ubu_soltest_deprecated_evm_versions: *requires_b_ubu + - t_ubu_soltest_low_priority_evm_versions: *requires_b_ubu # Build in a Docker container (on Alpine Linux) - b_alpine_docker: *requires_nothing diff --git a/.circleci/soltest_all.sh b/.circleci/soltest_all.sh index 6f8ea14f398f..38906185947d 100755 --- a/.circleci/soltest_all.sh +++ b/.circleci/soltest_all.sh @@ -32,15 +32,14 @@ REPODIR="$(realpath "$(dirname "$0")"/..)" source "${REPODIR}/scripts/common.sh" DEFAULT_EVM_VALUES=( + homestead constantinople - petersburg istanbul berlin london paris shanghai cancun - prague osaka ) EVMS_WITH_EOF=(osaka) From 5e6d9f15793a8bdd712e5b2a507aa08b8e9c3941 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 2 Feb 2026 10:42:18 +0100 Subject: [PATCH 46/73] Add arithmetic concept and arithmetic string parsing utilities --- libsolutil/Common.h | 8 ++++++++ libsolutil/StringUtils.cpp | 2 ++ libsolutil/StringUtils.h | 15 +++++++++++++-- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/libsolutil/Common.h b/libsolutil/Common.h index c908c13ae2bc..5ee0e11591b7 100644 --- a/libsolutil/Common.h +++ b/libsolutil/Common.h @@ -43,6 +43,7 @@ #include #include +#include #include #include #include @@ -52,6 +53,13 @@ namespace solidity { +namespace concepts +{ +/// Concept denoting some arithmetic type. +template +concept arithmetic = std::integral || std::floating_point; +} + // Binary data types. using bytes = std::vector; using bytesRef = util::vector_ref; diff --git a/libsolutil/StringUtils.cpp b/libsolutil/StringUtils.cpp index f5d2bbfb3735..50191c083b6a 100644 --- a/libsolutil/StringUtils.cpp +++ b/libsolutil/StringUtils.cpp @@ -26,6 +26,8 @@ #include +#include + #include #include #include diff --git a/libsolutil/StringUtils.h b/libsolutil/StringUtils.h index 763f1ea64f41..87f46252e82f 100644 --- a/libsolutil/StringUtils.h +++ b/libsolutil/StringUtils.h @@ -27,11 +27,11 @@ #include #include -#include - #include +#include #include #include +#include #include #include @@ -208,4 +208,15 @@ inline std::string indent(std::string const& _input, bool _indentEmptyLines = fa return prefixLines(_input, " ", !_indentEmptyLines); } +/// Parses an arithmetic value from a `string_view` without allocating and/or throwing. Returns `nullopt` on error. +template +std::optional parseArithmetic(std::string_view const sv) +{ + T result; + auto const errorCondition = std::from_chars(sv.data(), sv.data() + sv.size(), result).ec; + if (errorCondition == std::errc()) + return result; + return std::nullopt; +} + } From 31ef2784308f4c24e722949ad93c4eaf145854db Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 2 Feb 2026 11:09:51 +0100 Subject: [PATCH 47/73] Pull Stack Depth and Offset definitions out of the Stack itself They do not depend on the callbacks template at all. --- libyul/backends/evm/ssa/Stack.h | 52 +++++++++++++++++---------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/libyul/backends/evm/ssa/Stack.h b/libyul/backends/evm/ssa/Stack.h index 20207ebc7e4a..31f7ac1509e2 100644 --- a/libyul/backends/evm/ssa/Stack.h +++ b/libyul/backends/evm/ssa/Stack.h @@ -156,6 +156,31 @@ struct NoOpStackManipulationCallbacks }; static_assert(StackManipulationCallbackConcept); +/// Array index into stack from the bottom (offset 0 = bottom). +/// Natural for array-like access and iteration; used when treating the stack as a data structure. +struct StackOffset +{ + explicit constexpr StackOffset(size_t _value) : value(_value) {} + size_t value; + auto operator<=>(StackOffset const&) const = default; +}; +// comparison operations with size_t +constexpr auto operator<=>(StackOffset const lhs, size_t const rhs) noexcept { return lhs.value <=> rhs; } +constexpr auto operator<=>(size_t const lhs, StackOffset const rhs) noexcept { return lhs <=> rhs.value; } + +/// Distance from the stack top (depth 0 = top). +/// Natural for stack operations (SWAP1 = swap with depth 1); used for operations that +/// conceptually work "from the top". +struct StackDepth +{ + explicit constexpr StackDepth(size_t _value) : value(_value) {} + size_t value; + auto operator<=>(StackDepth const&) const = default; +}; +// comparison operations with size_t +constexpr auto operator<=>(StackDepth const lhs, size_t const rhs) noexcept { return lhs.value <=> rhs; } +constexpr auto operator<=>(size_t const lhs, StackDepth const rhs) noexcept { return lhs <=> rhs.value; } + template< StackManipulationCallbackConcept CallbacksType = NoOpStackManipulationCallbacks > @@ -167,31 +192,8 @@ class Stack using Slot = StackSlot; using Data = StackData; - - /// Array index into stack from the bottom (offset 0 = bottom). - /// Natural for array-like access and iteration; used when treating the stack as a data structure. - struct Offset - { - explicit constexpr Offset(size_t _value) : value(_value) {} - size_t value; - auto operator<=>(Offset const&) const = default; - }; - // comparison operations with size_t - friend constexpr auto operator<=>(Offset lhs, size_t rhs) noexcept { return lhs.value <=> rhs; } - friend constexpr auto operator<=>(size_t lhs, Offset rhs) noexcept { return lhs <=> rhs.value; } - - /// Distance from the stack top (depth 0 = top). - /// Natural for stack operations (SWAP1 = swap with depth 1); used for operations that - /// conceptually work "from the top". - struct Depth - { - explicit constexpr Depth(size_t _value) : value(_value) {} - size_t value; - auto operator<=>(Depth const&) const = default; - }; - // comparison operations with size_t - friend constexpr auto operator<=>(Depth lhs, size_t rhs) noexcept { return lhs.value <=> rhs; } - friend constexpr auto operator<=>(size_t lhs, Depth rhs) noexcept { return lhs <=> rhs.value; } + using Depth = StackDepth; + using Offset = StackOffset; Stack( Data& _data, From e1cb8431760d8822728f67151fc9bdefc10abf01 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 2 Feb 2026 11:10:15 +0100 Subject: [PATCH 48/73] Fix dup implementation in ssa Stack abstraction --- libyul/backends/evm/ssa/Stack.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libyul/backends/evm/ssa/Stack.h b/libyul/backends/evm/ssa/Stack.h index 31f7ac1509e2..a98977380cd9 100644 --- a/libyul/backends/evm/ssa/Stack.h +++ b/libyul/backends/evm/ssa/Stack.h @@ -240,10 +240,11 @@ class Stack void dup(Depth const& _depth) { dup(depthToOffset(_depth)); } void dup(Offset const& _offset) { - yulAssert(dupReachable(_offset), "Stack too deep"); + auto const depth = offsetToDepth(_offset); + yulAssert(dupReachable(depth), "Stack too deep"); m_data->push_back((*m_data)[_offset.value]); if constexpr (!std::is_same_v) - m_callbacks.dup(offsetToDepth(_offset).value + 1); + m_callbacks.dup(depth.value + 1); } bool dupReachable(Offset const& _offset) const noexcept { return dupReachable(offsetToDepth(_offset)); } From 0d10f892b5ee1175b22bd4683c2d9abc99e1e6df Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 2 Feb 2026 11:15:28 +0100 Subject: [PATCH 49/73] Simplify stack and slot to string functions for ssa Stack --- libyul/backends/evm/ssa/SSACFG.h | 39 ++++++++++++++++++++++++ libyul/backends/evm/ssa/Stack.cpp | 50 ++----------------------------- libyul/backends/evm/ssa/Stack.h | 2 -- 3 files changed, 41 insertions(+), 50 deletions(-) diff --git a/libyul/backends/evm/ssa/SSACFG.h b/libyul/backends/evm/ssa/SSACFG.h index 40537cfcd557..49d5a4e946a5 100644 --- a/libyul/backends/evm/ssa/SSACFG.h +++ b/libyul/backends/evm/ssa/SSACFG.h @@ -316,3 +316,42 @@ class SSACFG }; } + +template<> +struct fmt::formatter +{ + static auto constexpr parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } + + template + auto format(solidity::yul::ssa::SSACFG::BlockId const& _blockId, FormatContext& _ctx) const -> decltype(_ctx.out()) + { + if (!_blockId.hasValue()) + return fmt::format_to(_ctx.out(), "empty"); + return fmt::format_to(_ctx.out(), "{}", _blockId.value); + } +}; + +template<> +struct fmt::formatter +{ + static auto constexpr parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } + + template + auto format(solidity::yul::ssa::SSACFG::ValueId const& _valueId, FormatContext& _ctx) const -> decltype(_ctx.out()) + { + if (!_valueId.hasValue()) + return fmt::format_to(_ctx.out(), "empty"); + switch (_valueId.kind()) + { + case solidity::yul::ssa::SSACFG::ValueId::Kind::Literal: + return fmt::format_to(_ctx.out(), "lit{}", _valueId.value()); + case solidity::yul::ssa::SSACFG::ValueId::Kind::Variable: + return fmt::format_to(_ctx.out(), "v{}", _valueId.value()); + case solidity::yul::ssa::SSACFG::ValueId::Kind::Phi: + return fmt::format_to(_ctx.out(), "phi{}", _valueId.value()); + case solidity::yul::ssa::SSACFG::ValueId::Kind::Unreachable: + return fmt::format_to(_ctx.out(), "unreachable"); + } + solidity::util::unreachable(); + } +}; diff --git a/libyul/backends/evm/ssa/Stack.cpp b/libyul/backends/evm/ssa/Stack.cpp index 17c8c3f446ee..59534019da54 100644 --- a/libyul/backends/evm/ssa/Stack.cpp +++ b/libyul/backends/evm/ssa/Stack.cpp @@ -18,20 +18,9 @@ #include +#include #include -#include -#include - -namespace -{ -size_t junkTailSize(solidity::yul::ssa::StackData const& _stackData) -{ - auto junkTail = _stackData | ranges::views::take_while([](auto const& slot) { return slot.isJunk(); }); - return static_cast(ranges::distance(junkTail)); -} -} - namespace solidity::yul::ssa { @@ -40,10 +29,7 @@ std::string slotToString(StackSlot const& _slot) switch (_slot.kind()) { case StackSlot::Kind::ValueID: - if (_slot.isLiteralValueID()) - return fmt::format("lit{}", _slot.valueID().value()); - else - return fmt::format("v{}", _slot.valueID().value()); + return fmt::format("{}", _slot.valueID()); case StackSlot::Kind::Junk: return "JUNK"; case StackSlot::Kind::FunctionCallReturnLabel: @@ -54,44 +40,12 @@ std::string slotToString(StackSlot const& _slot) util::unreachable(); } -std::string slotToString(StackSlot const& _slot, SSACFG const& _cfg) -{ - if (_slot.kind() == StackSlot::Kind::ValueID) - return _slot.valueID().str(_cfg); - - return slotToString(_slot); -} - std::string stackToString(StackData const& _stackData) { - auto const numJunk = junkTailSize(_stackData); - if (numJunk > 0) - return fmt::format( - "[JUNK x {}, {}]", - numJunk, - fmt::join(_stackData | ranges::views::drop(numJunk) | ranges::views::transform([&](auto const& _slot) { return slotToString(_slot); }), ", ") - ); - return fmt::format( "[{}]", fmt::join(_stackData | ranges::views::transform([&](auto const& _slot) { return slotToString(_slot); }), ", ") ); } -std::string stackToString(StackData const& _stackData, SSACFG const& _cfg) -{ - auto const numJunk = junkTailSize(_stackData); - if (numJunk > 0) - return fmt::format( - "[JUNK x {}, {}]", - numJunk, - fmt::join(_stackData | ranges::views::drop(numJunk) | ranges::views::transform([&](auto const& _slot) { return slotToString(_slot, _cfg); }), ", ") - ); - - return fmt::format( - "[{}]", - fmt::join(_stackData | ranges::views::transform([&](auto const& _slot) { return slotToString(_slot, _cfg); }), ", ") - ); -} - } diff --git a/libyul/backends/evm/ssa/Stack.h b/libyul/backends/evm/ssa/Stack.h index a98977380cd9..95ff377e7db4 100644 --- a/libyul/backends/evm/ssa/Stack.h +++ b/libyul/backends/evm/ssa/Stack.h @@ -130,8 +130,6 @@ static_assert(std::is_trivial_v, "Want to have no init/cpy overhead") using StackData = std::vector; std::string slotToString(StackSlot const& _slot); -std::string slotToString(StackSlot const& _slot, SSACFG const& _cfg); -std::string stackToString(StackData const& _stackData, SSACFG const& _cfg); std::string stackToString(StackData const& _stackData); template From 02af154f6b61e706ea00460506f36967a78acf2d Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 2 Feb 2026 11:15:51 +0100 Subject: [PATCH 50/73] Add the ssa stack shuffler --- libyul/CMakeLists.txt | 2 + libyul/backends/evm/ssa/StackShuffler.cpp | 165 +++++ libyul/backends/evm/ssa/StackShuffler.h | 853 ++++++++++++++++++++++ 3 files changed, 1020 insertions(+) create mode 100644 libyul/backends/evm/ssa/StackShuffler.cpp create mode 100644 libyul/backends/evm/ssa/StackShuffler.h diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index ff94a3905e8f..9d0bfe1e2e53 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -92,6 +92,8 @@ add_library(yul backends/evm/ssa/SSACFGJsonExporter.h backends/evm/ssa/Stack.cpp backends/evm/ssa/Stack.h + backends/evm/ssa/StackShuffler.cpp + backends/evm/ssa/StackShuffler.h optimiser/ASTCopier.cpp optimiser/ASTCopier.h optimiser/ASTWalker.cpp diff --git a/libyul/backends/evm/ssa/StackShuffler.cpp b/libyul/backends/evm/ssa/StackShuffler.cpp new file mode 100644 index 000000000000..b42d2bb2446c --- /dev/null +++ b/libyul/backends/evm/ssa/StackShuffler.cpp @@ -0,0 +1,165 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#include + +#include +#include + +using namespace solidity::yul::ssa; +using namespace solidity::yul::ssa::detail; + +Target::Target(StackData const& _args, LivenessAnalysis::LivenessData const& _liveOut, std::size_t const _targetSize): + args(_args), + liveOut(_liveOut), + size(_targetSize), + tailSize(_targetSize - _args.size()) +{ + minCount.reserve(_args.size() + _liveOut.size()); + for (auto const& arg: _args) + if (!arg.isJunk()) + ++minCount[arg]; + for (auto const& _liveValueId: _liveOut | ranges::views::keys) + ++minCount[StackSlot::makeValueID(_liveValueId)]; +} + +State::State(StackData const& _stackData, Target const& _target, std::size_t const _reachableStackDepth): + m_stackData(_stackData), + m_target(_target), + m_reachableStackDepth(_reachableStackDepth) +{ + m_histogram.reserve(_stackData.size()); + m_histogramReachable.reserve(_stackData.size()); + m_histogramTail.reserve(_stackData.size()); + m_histogramArgs.reserve(_target.args.size()); + for (auto const& [i, slot]: _stackData | ranges::views::enumerate) + { + // we don't care about junk in the tail + if (i < _target.tailSize && slot.isJunk()) + continue; + // we purposefully skip over junk in the target args as they are always 'correct' + if (i >= _target.tailSize && i < _target.size && _target.args[i - _target.tailSize].isJunk()) + continue; + + ++m_histogram[slot]; + if (i < _target.tailSize) + ++m_histogramTail[slot]; + else if (i < _target.size) + ++m_histogramArgs[slot]; + if (_stackData.size() - i - 1 < _reachableStackDepth) + ++m_histogramReachable[slot]; + } +} + +std::size_t State::size() const +{ + return m_stackData.size(); +} + +std::size_t State::count(StackSlot const& _slot) const +{ + return util::valueOrDefault(m_histogram, _slot, static_cast(0)); +} + +std::size_t State::countInArgs(StackSlot const& _slot) const +{ + return util::valueOrDefault(m_histogramArgs, _slot, static_cast(0)); +} + +std::size_t State::countInTail(StackSlot const& _slot) const +{ + return util::valueOrDefault(m_histogramTail, _slot, static_cast(0)); +} + +std::size_t State::countReachable(StackSlot const& _slot) const +{ + return util::valueOrDefault(m_histogramReachable, _slot, static_cast(0)); +} + +std::size_t State::targetMinCount(StackSlot const& _slot) const +{ + return util::valueOrDefault(m_target.minCount, _slot, static_cast(0)); +} + +std::size_t State::targetArgsCount(StackSlot const& _slot) const +{ + return static_cast(ranges::count(m_target.args, _slot)); +} + +bool State::admissible() const +{ + if (m_target.size != m_stackData.size()) + return false; + + // check if the args are correct + for (size_t i = 0; i < m_target.args.size(); ++i) + if (!isArgsCompatible(StackOffset{m_stackData.size() - i - 1}, StackOffset{m_stackData.size() - i - 1})) + return false; + + // check if the distribution is correct (implying that the stack is admissible as JUNK target args are not counted) + for (auto const& [targetSlot, targetMinCount]: m_target.minCount) + if (count(targetSlot) < targetMinCount) + return false; + return true; +} + +bool State::requiredInArgs(StackSlot const& _slot) const +{ + return ranges::find(m_target.args, _slot) != ranges::end(m_target.args); +} + +bool State::requiredInTail(StackSlot const& _slot) const +{ + return _slot.isValueID() && m_target.liveOut.contains(_slot.valueID()); +} + +bool State::offsetInTargetArgsRegion(StackOffset const _offset) const +{ + return _offset.value >= m_target.size - m_target.args.size() && _offset.value < m_target.size; +} + +StackSlot const& State::targetArg(StackOffset const _targetOffset) const +{ + yulAssert(offsetInTargetArgsRegion(_targetOffset)); + return m_target.args[_targetOffset.value - m_target.tailSize]; +} + +bool State::isArgsCompatible(StackOffset const _sourceOffset, StackOffset const _targetOffset) const +{ + if (_sourceOffset >= m_stackData.size() || !offsetInTargetArgsRegion(_targetOffset)) + return false; + auto const& arg = targetArg(_targetOffset); + return arg.isJunk() || m_stackData[_sourceOffset.value] == arg; +} + +bool State::targetArbitrary(StackOffset const _targetOffset) const +{ + return targetArg(_targetOffset).isJunk(); +} + +bool State::isSourceCompatible(StackOffset const _sourceOffset1, StackOffset const _sourceOffset2) const +{ + return _sourceOffset1 < m_stackData.size() && + _sourceOffset2 < m_stackData.size() && + m_stackData[_sourceOffset1.value] == m_stackData[_sourceOffset2.value]; +} + +Target const& State::target() const +{ + return m_target; +} diff --git a/libyul/backends/evm/ssa/StackShuffler.h b/libyul/backends/evm/ssa/StackShuffler.h new file mode 100644 index 000000000000..983505bb2cdf --- /dev/null +++ b/libyul/backends/evm/ssa/StackShuffler.h @@ -0,0 +1,853 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include +#include + +#include + +#include + +#include +#include + +namespace solidity::yul::ssa +{ + +namespace detail +{ +/// Contains information about the shuffling target, aggregates over args and live out to +/// provide a lower bound for the slot distribution. +struct Target +{ + Target(StackData const& _args, LivenessAnalysis::LivenessData const& _liveOut, std::size_t _targetSize); + + StackData const& args; + LivenessAnalysis::LivenessData const& liveOut; + std::size_t const size; + std::size_t const tailSize; + boost::container::flat_map minCount; +}; +/// Current state of the stack vs the shuffling target. +class State +{ +public: + State(StackData const& _stackData, Target const& _target, std::size_t _reachableStackDepth); + + std::size_t size() const; + /// How many of `_slot` do we have on stack + std::size_t count(StackSlot const& _slot) const; + /// How many of `_slot` do we have in the args section of the stack + std::size_t countInArgs(StackSlot const& _slot) const; + /// How many of `_slot` do we have in the tail section of the stack + std::size_t countInTail(StackSlot const& _slot) const; + /// How many of `_slot` are (dup) reachable on stack + std::size_t countReachable(StackSlot const& _slot) const; + + /// Obtain the amount of the provided slot that is required for distribution correctness + std::size_t targetMinCount(StackSlot const& _slot) const; + /// Obtain the amount of the provided slot that is required in target args + std::size_t targetArgsCount(StackSlot const& _slot) const; + + /// Checks if the state is compatible with the target + bool admissible() const; + + /// Checks if a particular slot is required in the target args + bool requiredInArgs(StackSlot const& _slot) const; + /// Checks if a particular slot is required in the target tail + bool requiredInTail(StackSlot const& _slot) const; + + /// Checks if an offset is in the target args (bounded from below by tail size, from above by target size) + bool offsetInTargetArgsRegion(StackOffset _offset) const; + /// Retrieves the required argument slot for a specific stack offset + StackSlot const& targetArg(StackOffset _targetOffset) const; + /// Checks the current stack offset is args-compatible with a target stack offset, meaning the target offset is + /// in the target args region and either a wildcard slot (JUNK) or a precise match for the slot at `_sourceOffset` + bool isArgsCompatible(StackOffset _sourceOffset, StackOffset _targetOffset) const; + /// Checks if the slot at `_targetOffset` admits any slot + bool targetArbitrary(StackOffset _targetOffset) const; + /// Yields whether two slots on the current stack are same, respecting stack size limits + bool isSourceCompatible(StackOffset _sourceOffset1, StackOffset _sourceOffset2) const; + /// Shuffling target information + Target const& target() const; + + /// A range of offsets `[argsBegin, argsEnd)` intersected with the current stack size + auto stackArgsRange() const + { + return ranges::views::iota(std::min(m_target.tailSize, m_stackData.size()), std::min(m_target.size, m_stackData.size())) | ranges::views::transform([](auto _i) { return StackOffset{_i}; }); + } + + /// A range of offsets `[0, argsBegin)` intersected with the current stack size + auto stackTailRange() const + { + return ranges::views::iota(0u, std::min(m_target.tailSize, m_stackData.size())) | ranges::views::transform([](auto _i) { return StackOffset{_i}; }); + } + + /// A range of offsets `[0, stackSize)` + auto stackRange() const + { + return ranges::views::iota(0u, m_stackData.size()) | ranges::views::transform([&](auto _i) { return StackOffset{_i}; }); + } + + /// A reversed range of offsets `[stackSize - reachableStackDepth - 1, stackSize)` + auto stackSwapReachableRange() const + { + return ranges::views::iota(0u, std::min(m_stackData.size(), m_reachableStackDepth + 1)) | ranges::views::transform([&](auto _i) { return StackOffset{m_stackData.size() - _i - 1}; }); + } + + /// A reversed range of offsets `[stackSize - reachableStackDepth - 1, stackSize)` + auto stackDupReachableRange() const + { + return ranges::views::iota(0u, std::min(m_stackData.size(), m_reachableStackDepth)) | ranges::views::transform([&](auto _i) { return StackOffset{m_stackData.size() - _i - 1}; }); + } + +private: + StackData const& m_stackData; + Target const& m_target; + std::size_t const m_reachableStackDepth; + boost::container::flat_map m_histogramTail; + boost::container::flat_map m_histogramArgs; + boost::container::flat_map m_histogramReachable; + boost::container::flat_map m_histogram; +}; +} + +template +class StackShuffler +{ + using Slot = StackSlot; + +public: + static void shuffle( + Stack& _stack, + StackData const& _args, + LivenessAnalysis::LivenessData const& _liveOut, + std::size_t _targetStackSize + ) + { + detail::Target const target(_args, _liveOut, _targetStackSize); + yulAssert(_liveOut.size() <= target.size, "not enough tail space"); + { + // check that all required values are on stack + detail::State const state(_stack.data(), target, ReachableStackDepth); + for (auto const& liveVariable: _liveOut | ranges::views::keys | ranges::views::transform(Slot::makeValueID)) + yulAssert(_stack.canBeFreelyGenerated(liveVariable) || ranges::find(_stack.data(), liveVariable) != ranges::end(_stack.data())); + for (auto const& arg: _args) + yulAssert(_stack.canBeFreelyGenerated(arg) || ranges::find(_stack.data(), arg) != ranges::end(_stack.data())); + } + + static std::size_t constexpr maxIterations = 1000; + std::size_t i = 0; + while (i < maxIterations) + { + detail::State const state(_stack.data(), target, ReachableStackDepth); + if (!shuffleStep(_stack, state)) + { + yulAssert(state.admissible()); + break; + } + ++i; + } + + yulAssert(i < maxIterations, fmt::format("Maximum iterations reached on {}", stackToString(_stack.data()))); + } + +private: + /// Make a local step in stack space that should bring us closer to the target. Returns true if more shuffling + /// is required, returns false if finished. + static bool shuffleStep(Stack& _stack, detail::State const& _state) + { + // if the stack is too large, we try to shrink it + if (_stack.size() > _state.target().size) + { + if (shrinkStack(_stack, _state)) + return true; + // couldn't shrink to required size, need to spill to memory or increase target size + yulAssert(false, "stack too deep"); + } + yulAssert(_stack.size() <= _state.target().size, "I1 violated: Stack size too large"); + + // after this, all current slots are either in acceptable positions or at least dup-reachable + if (auto unreachableOffset = allNecessarySlotsReachableOrFinal(_stack, _state)) + { + // !allNecessarySlotsReachableOrFinal(ops) ≡ ÂŹ(∀s: reachable(s) √ final(s)) ≡ ∃s: ÂŹreachable(s) ∧ ÂŹfinal(s) + if (shrinkStack(_stack, _state)) + return true; + + yulAssert(false, fmt::format("stack too deep, couldn't reach offset {}", unreachableOffset->value)); + } + + // this will either grow the tail as needed, swap down something from args that needs to be in the tail, + // or return false when there's nothing to be done + if (fixTailSlot(_stack, _state)) + return true; + + // fixing tail slot fills up the tail so that now the stack must reach into the args region but also not + // exceed it as per our first invariant + yulAssert(_state.target().tailSize <= _stack.size() && _stack.size() <= _state.target().size); + + // if the stack reaches into the args region try fixing a slot in there until there's nothing left to be fixed + // within the target size constraints + if (fixArgsSlot(_stack, _state)) + return true; + + // if there are no args, we should be done now + if (_state.target().args.empty()) + return false; + yulAssert(_stack.size() == _state.target().size); + + // check whether we are done + if (_state.admissible()) + return false; + + // We couldn't improve the args tail or args situation, and we are not admissible yet, so try to reduce the + // stack size and pop something that we don't need so we make space to dup/push stuff within target size + if (shrinkStack(_stack, _state)) + return true; + + yulAssert(false, "reached final and forbidden state"); + } + + /// Select an optimal slot to dup based on liveness analysis. + /// Prioritizes slots that have the highest deficit with respect to liveOut counts. + static std::optional selectOptimalSlotToDup(Stack const& _stack, detail::State const& _state) + { + std::optional bestSlot; + int bestDeficit = 0; // Only consider positive deficits + + // Iterate through all slots on the stack that can be DUPed + for (StackOffset offset: _state.stackDupReachableRange() | ranges::views::reverse) + { + Slot const& slot = _stack[offset]; + + // Skip junk slots + if (slot.isJunk()) + continue; + + // Calculate deficit: how many more of this slot do we need? + // Uses the deficit of slots which we need to produce more of based on usage counts in liveness. + // Prioritizes slots that need more copies to be consumed down the line. + int currentCount = static_cast(_state.count(slot)); + + int liveOutCount = 0; + if (slot.isValueID() && _state.target().liveOut.contains(slot.valueID())) + liveOutCount = static_cast(_state.target().liveOut.count(slot.valueID())); + int deficit = liveOutCount - currentCount; + + // Update best if this deficit is higher + if (deficit > bestDeficit) + { + bestDeficit = deficit; + bestSlot = _stack.offsetToDepth(offset); + } + } + + return bestSlot; + } + + /// Dups the deepest reachable slot in the tail that is required in args + static bool dupDeepestRelevantTailSlot(Stack& _stack, detail::State const& _state) + { + // dup up the deepest slot that is required in args (or compress if unreachable) + for (StackOffset offset: _state.stackRange()) + { + // if we need the slot in args and there's no slot of the same kind further up + if ( + _state.requiredInArgs(_stack[offset]) && + ranges::find(ranges::begin(_stack) + static_cast(offset.value) + 1, ranges::end(_stack), _stack[offset]) == ranges::end(_stack) + ) + { + // dup if we can + if (_stack.dupReachable(offset)) + { + _stack.dup(offset); + return true; + } + + // try to compress + if (shrinkStack(_stack, _state)) + return true; + + yulAssert(false, fmt::format("Stack too deep: can't reach slot at offset {}", offset.value)); + } + } + return false; + } + + /// If dupping an ideal slot causes a slot that will still be required to become unreachable, then dup + /// the latter slot first + static bool dupDeepSlotIfRequired(Stack& _stack, detail::State const& _state) + { + // Check if the stack is large enough for anything to potentially become unreachable. + if (_stack.size() < ReachableStackDepth - 1) + return false; + // Check whether any deep slot might still be needed later (i.e. we still need to reach it with a DUP or SWAP). + for (StackOffset sourceOffset{0u}; sourceOffset < _stack.size() - (ReachableStackDepth - 1); ++sourceOffset.value) + { + // This slot needs to be moved into args and there is no tail slot of the same kind further up in the stack. + auto const& endangeredSlot = _stack[sourceOffset]; + // no need to dup deep junk + if (endangeredSlot.isJunk()) + continue; + // check if we have more of the same slot further up in the stack + bool const neededInArgs = _state.targetArgsCount(endangeredSlot) > _state.countInArgs(endangeredSlot); + bool const needMore = _state.targetMinCount(endangeredSlot) > _state.count(endangeredSlot); + if (neededInArgs || needMore) + { + // if we ever need more of a slot then this can only happen if it is something we require + // in the arguments + yulAssert(_state.requiredInArgs(endangeredSlot)); + + auto const haveMoreAbove = [&] + { + for (StackOffset offset{sourceOffset.value + 1}; offset < _stack.size(); ++offset.value) + { + if (_stack[offset] == endangeredSlot) + return true; + } + return false; + }(); + + // if we have more of the same further above, just unconditionally skip this one + if (haveMoreAbove) + continue; + + if (_stack.dupReachable(sourceOffset)) + { + + // if we can safely swap the current stack top with the endangered slot, we do that instead of DUP + if ( + !_state.isArgsCompatible(sourceOffset, sourceOffset) && // the offset isn't already in the right position wrt args + !_state.isArgsCompatible(StackOffset{_stack.size() - 1}, StackOffset{_stack.size() - 1}) && // the top isn't already in the right position wrt args + ( + !_state.requiredInArgs(_stack.top()) || // current top can go into tail, ie it's not required as arg or + _state.countReachable(_stack.top()) > 1 // there's more of it in reachable stack depth + ) && + ( + _state.target().tailSize <= sourceOffset.value || // sourceOffset not in tail + !_state.requiredInTail(endangeredSlot) || // we're in tail but sourceOffset not needed in tail + (_state.countInTail(endangeredSlot) > 1 && _state.requiredInTail(endangeredSlot)) // swapping source offset away from tail doesn't decrease tail correctness + ) + ) + { + // top can go into the tail bit, swap it down + _stack.swap(sourceOffset); + return true; + } + else + { + // we need more of the slot that is about to go out of reach, dup it + _stack.dup(sourceOffset); + return true; + } + } + else + { + std::optional depth = _stack.findSlotDepth(_stack[sourceOffset]); + yulAssert(depth); + // if there's a shallower slot with the same info that is reachable, skip this one + if (*depth < _stack.offsetToDepth(sourceOffset)) + continue; + + // the slot we need something in the args region of is unreachable, try compressing the stack, + // first looking at the top + if (shrinkStack(_stack, _state)) + return true; + + yulAssert(false, fmt::format("Stack too deep, can't reach slot at depth {}", depth->value)); + } + } + } + return false; + } + + /// Tries to fix a slot in the args section of the stack + static bool fixArgsSlot(Stack& _stack, detail::State const& _state) + { + yulAssert(_stack.size() <= _state.target().size, "this method assumes that the stack isn't too large"); + if (_stack.size() < _state.target().tailSize) + return false; + + // if we have at least one slot in the args section, try to fix something there + if (!_stack.empty() && _stack.size() >= _state.target().tailSize) + { + StackOffset const stackTop{_stack.size() - 1}; + // if the stack top isn't where it likes to be right now, try to put it somewhere more sensible + if (!_state.isArgsCompatible(stackTop, stackTop)) + { + // if the stack top should go into the tail but isn't there yet and we have enough of it in args + if ( + _state.requiredInTail(_stack[stackTop]) && + _state.countInTail(_stack[stackTop]) == 0 && + _state.countInArgs(_stack[stackTop]) > _state.targetArgsCount(_stack[stackTop]) + ) + { + // try swapping it with something in the tail that also fixes the top + for (StackOffset offset: _state.stackTailRange()) + if (_stack.swapReachable(offset) && _state.isArgsCompatible(offset, stackTop)) + { + _stack.swap(offset); + return true; + } + // otherwise try swapping it with something that needs to go into args + for (StackOffset offset: _state.stackTailRange()) + if (_stack.swapReachable(offset) && _state.countInArgs(_stack[offset]) < _state.targetArgsCount(_stack[offset])) + { + _stack.swap(offset); + return true; + } + // otherwise try swapping it with something that can be popped + for (StackOffset offset: _state.stackTailRange()) + if (_stack.swapReachable(offset) && _stack.canBeFreelyGenerated(_stack[offset]) && !_stack[offset].isLiteralValueID()) + { + _stack.swap(offset); + return true; + } + // otherwise try swapping it with a literal + for (StackOffset offset: _state.stackTailRange()) + if (_stack.swapReachable(offset) && _stack[offset].isLiteralValueID()) + { + _stack.swap(offset); + return true; + } + } + // try finding a slot that is compatible with the top and also admits the current top: + // - could be that the top slot is used elsewhere in the args (exclude junk) + // - could be that the top slot is something that is only required in the tail + for (StackOffset offset: _state.stackArgsRange()) + if ( + offset != stackTop && + _stack[offset] != _stack[stackTop] && // don't swap identical values (no-op) + _stack.swapReachable(offset) && + _state.isArgsCompatible(offset, stackTop) && + _state.isArgsCompatible(stackTop, offset) && + !_state.targetArbitrary(offset) + ) + { + _stack.swap(offset); + return true; + } + + // try finding a slot in args that wants to have the top, swap that + for (StackOffset offset: _state.stackArgsRange()) + if ( + offset != stackTop && + _stack[offset] != _stack[stackTop] && // don't swap identical values (no-op) + _stack.swapReachable(offset) && + !_state.isArgsCompatible(offset, offset) && + _state.isArgsCompatible(stackTop, offset) + ) + { + _stack.swap(offset); + return true; + } + + // try swapping top with a tail slot that has what we need at top + for (StackOffset tailOffset: _state.stackTailRange()) + if ( + _stack.swapReachable(tailOffset) && + _state.isArgsCompatible(tailOffset, stackTop) && + (!_state.requiredInTail(_stack[tailOffset]) || _state.countInTail(_stack[tailOffset]) > 1) && + // current top can safely go to tail (not needed in args, or we have excess) + ( + !_state.requiredInArgs(_stack[stackTop]) || + _state.countInArgs(_stack[stackTop]) > _state.targetArgsCount(_stack[stackTop]) + ) + ) + { + _stack.swap(tailOffset); + return true; + } + } + + // swap up any slot in args that is out of position and has a slot available in args that it can occupy + for (StackOffset offset: _state.stackArgsRange()) + { + bool const reachable = _stack.swapReachable(offset); + bool const identical = _state.isArgsCompatible(offset, stackTop) && !_state.targetArbitrary(stackTop); + if ( + reachable && + !identical && // we wouldn't just be swapping identical things + ( + !_state.isArgsCompatible(offset, offset) || // the slot at offset isn't final + (_state.targetArbitrary(offset) && !_stack.slot(offset).isJunk()) // or the target is arbitrary and the current slot isn't already junk + ) + ) + { + // for each `targetOffset` in target args, see if we can't swap the out of position `offset` to `targetOffset` + for (StackOffset targetOffset: _state.stackArgsRange()) + if ( + targetOffset != offset && // we shouldn't be looking at the very same offset + _stack.swapReachable(targetOffset) && // the target offset should be within reach + _state.isArgsCompatible(offset, targetOffset) && // we can put offset -> targetOffset + !_state.isArgsCompatible(targetOffset, targetOffset) // targetOffset doesn't like where it is + ) + { + if (offset != stackTop) + // swap up slot at offset + _stack.swap(offset); + // bring slot at offset into fixed position + _stack.swap(targetOffset); + return true; + } + } + } + } + + // dup up whatever is missing + if (_stack.size() < _state.target().size) + { + if (dupDeepSlotIfRequired(_stack, _state)) + return true; + + { + StackOffset const targetOffset{_stack.size()}; + if (_state.count(_state.targetArg(targetOffset)) < _state.targetMinCount(_state.targetArg(targetOffset))) + { + auto const sourceDepth = _stack.findSlotDepth(_state.targetArg(targetOffset)); + if (!sourceDepth) + { + _stack.push(_state.targetArg(targetOffset)); + return true; + } + + if (!_stack.dupReachable(*sourceDepth)) + yulAssert(false, fmt::format("todo: stack too deep handling, couldn't dup up arg {}", slotToString(_state.targetArg(_stack.depthToOffset(*sourceDepth))))); + _stack.dup(*sourceDepth); + return true; + } + } + + // if we can't directly produce targetOffset, take the deepest arg that we don't have enough of and dup/push that + // First, prioritize duping args that are on the stack over pushing freely-generatable ones + for (StackOffset offset{_state.target().tailSize}; offset < _state.target().size; ++offset.value) + { + Slot const& arg = _state.targetArg(offset); + if (!arg.isJunk() && (_state.count(arg) < _state.targetMinCount(arg) || _state.countInArgs(arg) < _state.targetArgsCount(arg))) + { + if (auto sourceDepth = _stack.findSlotDepth(arg)) + { + if (_stack.dupReachable(*sourceDepth)) + { + _stack.dup(*sourceDepth); + return true; + } + yulAssert(false, "stack too deep handling"); + } + yulAssert(_stack.canBeFreelyGenerated(arg)); + _stack.push(arg); + return true; + } + } + + // Try to dup the optimal slot based on liveness analysis + if (auto slotToDup = selectOptimalSlotToDup(_stack, _state)) + _stack.dup(*slotToDup); + else + // If no suitable slot found, push junk + _stack.push(Slot::makeJunk()); + return true; + } + + // if we're at size and have to push or dup something to satisfy args + if (_stack.size() == _state.target().size) + { + for (auto const& arg: _state.target().args) + if (_state.count(arg) < _state.targetMinCount(arg)) + { + // we have asserted that all relevant slots are reachable or final, so the arg must either be + // within dup-reach or we can just push it + if (auto depth = _stack.findSlotDepth(arg)) + { + yulAssert(depth->value == 0 || _stack.swapReachable(*depth)); + // if we can't outright dup the slot, let's shrink the stack first + if (!_stack.dupReachable(*depth)) + { + yulAssert(shrinkStack(_stack, _state), "stack too deep, need to spill arg to memory"); + return true; + } + _stack.dup(*depth); + return true; + } + else + { + yulAssert(_stack.canBeFreelyGenerated(arg)); + if (!dupDeepSlotIfRequired(_stack, _state)) + _stack.push(arg); + return true; + } + } + } + return false; + } + + /// Grows the tail if too small, otherwise tries swapping something down from args if its required in tail but not + /// there yet. + static bool fixTailSlot(Stack& _stack, detail::State const& _state) + { + yulAssert(_stack.size() <= _state.target().size, "this method assumes that the stack isn't exceeding target size"); + for (StackOffset offset: _state.stackArgsRange() | ranges::views::reverse) + { + Slot const& slotAtOffset = _stack[offset]; + if ( + _state.requiredInTail(slotAtOffset) && // if we need the slot in tail + _state.countInTail(slotAtOffset) == 0 // if we don't have the slot in tail right now + ) + { + // If we don't have enough copies of this slot, dup first instead of swapping. + if (_state.count(slotAtOffset) < _state.targetMinCount(slotAtOffset)) + { + if (_stack.dupReachable(offset)) + { + _stack.dup(offset); + return true; + } + } + + // find the lowest swappable slot in tail that needs to go to args, swap + for (StackOffset tailOffset: _state.stackTailRange()) + { + auto const& slotAtTailOffset = _stack[tailOffset]; + if ( + _stack.swapReachable(tailOffset) && // we can swap that deep + (!_state.requiredInTail(slotAtTailOffset) || _state.countInTail(slotAtTailOffset) > 1) && // dont need it in tail or it's available more than once + _state.requiredInArgs(slotAtTailOffset) && // we need the tail offset slot in args + _state.targetArgsCount(slotAtTailOffset) > _state.countInArgs(slotAtTailOffset) // we don't already have enough of it in args + ) + { + // bring up offset slot if necessary + if (offset != StackOffset{_stack.size() - 1}) + _stack.swap(offset); + // swap offset slot down into tail + _stack.swap(tailOffset); + return true; + } + } + // find the lowest swappable slot in tail that can be popped but is no literal, swap + for (StackOffset tailOffset: _state.stackTailRange()) + if ( + _stack.swapReachable(tailOffset) && + _stack.canBeFreelyGenerated(_stack[tailOffset]) && + !_stack[tailOffset].isLiteralValueID() + ) + { + // bring up offset slot if necessary + if (offset != StackOffset{_stack.size() - 1}) + _stack.swap(offset); + // swap offset slot down into tail + _stack.swap(tailOffset); + return true; + } + // find the lowest swappable slot in tail that is a literal, swap + for (StackOffset tailOffset: _state.stackTailRange()) + if ( + _stack.swapReachable(tailOffset) && + _stack[tailOffset].isLiteralValueID() + ) + { + // bring up offset slot if necessary + if (offset != StackOffset{_stack.size() - 1}) + _stack.swap(offset); + // swap offset slot down into tail + _stack.swap(tailOffset); + return true; + } + // we needed to bring the slot into tail but couldn't, not enough stack target space -> spill to memory + yulAssert(false, "stack too deep: couldn't swap args slot into tail without moving something else out that is required there"); + } + } + + if (_stack.size() < _state.target().tailSize) + { + // if something is on the verge of going out of scope by duping something, dup that first + if (dupDeepSlotIfRequired(_stack, _state)) + return true; + + // dup up the deepest slot that needs to go into args so we avoid having to fish it back up later + if (dupDeepestRelevantTailSlot(_stack, _state)) + return true; + + // Try to dup the optimal slot based on liveness analysis + if (auto slotToDup = selectOptimalSlotToDup(_stack, _state)) + _stack.dup(*slotToDup); + else + // If no suitable slot found, push junk + _stack.push(Slot::makeJunk()); + return true; + } + return false; + } + + /// Tries to compress the stack + static bool shrinkStack(Stack& _stack, detail::State const& _state) + { + yulAssert(!_stack.empty(), "Stack is empty, can't shrink"); + + StackOffset const stackTop{_stack.size() - 1}; + // pop top if it is junk (ie actual junk, not in args, not in live out) + if ( + _stack[stackTop].isJunk() || + (!_state.requiredInArgs(_stack[stackTop]) && !_state.requiredInTail(_stack[stackTop])) + ) + { + _stack.pop(); + return true; + } + + // swap top to suitable position, prioritizing args region + { + if (_state.requiredInArgs(_stack[stackTop])) + { + for (StackOffset argsOffset: _state.stackArgsRange()) + if ( + _stack[argsOffset] != _stack[stackTop] && // don't swap identical values (no-op) + _stack.swapReachable(argsOffset) && + _state.isArgsCompatible(stackTop, argsOffset) && + !_state.isArgsCompatible(argsOffset, argsOffset) + ) + { + _stack.swap(argsOffset); + return true; + } + } + // we don't need it in args but in tail + if (!_state.requiredInArgs(_stack[stackTop]) && _state.requiredInTail(_stack[stackTop])) + { + // pop when at least one of the two conditions is fulfilled + // - the top slot is contained in tail, and we're in args or excess region + // - there's more than one in tail + if ( + ( + _state.countInTail(_stack[stackTop]) >= 1 && + (_state.offsetInTargetArgsRegion(stackTop) || _stack.size() > _state.target().size) + ) || _state.countInTail(_stack[stackTop]) > 1 + ) + { + _stack.pop(); + return true; + } + + // if we need it down there, try to swap down + for (StackOffset tailOffset: _state.stackTailRange() | ranges::views::reverse) + if ( + _stack[tailOffset] != _stack[stackTop] && // don't swap identical values (no-op) + _stack.swapReachable(tailOffset) && // we can reach the offset + !(_state.requiredInTail(_stack[tailOffset]) && _state.countInTail(_stack[tailOffset]) <= 1) // it's okay to swap the tail offset out + ) + { + _stack.swap(tailOffset); + return true; + } + } + } + // pop junk (but not if JUNK is exactly what's needed at that position) + for (StackOffset offset: _state.stackSwapReachableRange()) + if (_stack[offset].isJunk() && !_state.isArgsCompatible(offset, offset)) + { + if (offset != stackTop && _stack[offset] != _stack[stackTop]) + _stack.swap(offset); + _stack.pop(); + return true; + } + + // pop something that can be freely generated except for literals + // (but not if it's already in a compatible position) + for (StackOffset offset: _state.stackSwapReachableRange()) + if ( + _stack.canBeFreelyGenerated(_stack[offset]) && + !_stack[offset].isLiteralValueID() && + !_state.isArgsCompatible(offset, offset) + ) + { + if (offset != stackTop && _stack[offset] != _stack[stackTop]) + _stack.swap(offset); + _stack.pop(); + return true; + } + + // pop anything that isn't in position and we have more than one of + for (StackOffset offset: _state.stackSwapReachableRange()) + if (_state.count(_stack[offset]) > _state.targetMinCount(_stack[offset])) + { + if (offset != stackTop && _stack[offset] != _stack[stackTop]) + _stack.swap(offset); + _stack.pop(); + return true; + } + // pop anything that can be freely generated + for (StackOffset offset: _state.stackSwapReachableRange()) + if (_stack.canBeFreelyGenerated(_stack[offset])) + { + if (offset != stackTop && _stack[offset] != _stack[stackTop]) + _stack.swap(offset); + _stack.pop(); + return true; + } + return false; + } + + /// Checks if all current slots are either in a position that is compatible with the target or, if not, are dup-reachable. + static std::optional allNecessarySlotsReachableOrFinal(Stack const& _stack, detail::State const& _state) + { + // check that args are either in position or reachable + for (StackOffset offset{_state.target().tailSize}; offset < _state.target().size; ++offset.value) + if ( + offset < _state.size() && + !_state.isArgsCompatible(offset, offset) + ) + { + // find first occurrence of the slot + std::optional depth = _stack.findSlotDepth(_state.targetArg(offset)); + + if (!depth) + { + // if there is no occurrence of the slot anywhere, we must be able to freely generate it + yulAssert(_stack.canBeFreelyGenerated(_state.targetArg(offset))); + } + else + { + if (!_stack.swapReachable(*depth)) + return _stack.depthToOffset(*depth); + } + } + // distribution check: all we have to dup can be duped + for (StackOffset const offset: _state.stackRange()) + { + auto const& slotAtOffset = _stack[offset]; + // we don't have enough of the slot + if ( + _state.count(slotAtOffset) < _state.targetMinCount(slotAtOffset) && + !_stack.dupReachable(offset) + ) + { + // find first occurrence of the slot + std::optional depth = _stack.findSlotDepth(slotAtOffset); + // it must exist + yulAssert(depth); + if (!_stack.dupReachable(*depth)) + return _stack.depthToOffset(*depth); + } + } + + return std::nullopt; + } +}; + +} From b2cb2af6f21841f3cfe52abaf3484bcce7afff05 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 2 Feb 2026 11:51:16 +0100 Subject: [PATCH 51/73] Add stack shuffler test --- test/CMakeLists.txt | 2 + test/InteractiveTests.h | 3 + test/libyul/ssa/StackShufflerTest.cpp | 453 ++++++++++++++++++++++++++ test/libyul/ssa/StackShufflerTest.h | 36 ++ test/tools/CMakeLists.txt | 2 + 5 files changed, 496 insertions(+) create mode 100644 test/libyul/ssa/StackShufflerTest.cpp create mode 100644 test/libyul/ssa/StackShufflerTest.h diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index b0cd991f7313..f36ae414764e 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -173,6 +173,8 @@ set(libyul_sources libyul/YulOptimizerTest.h libyul/YulOptimizerTestCommon.cpp libyul/YulOptimizerTestCommon.h + libyul/ssa/StackShufflerTest.cpp + libyul/ssa/StackShufflerTest.h ) detect_stray_source_files("${libyul_sources}" "libyul/") diff --git a/test/InteractiveTests.h b/test/InteractiveTests.h index 107a6aae0bef..ff2725471c7e 100644 --- a/test/InteractiveTests.h +++ b/test/InteractiveTests.h @@ -30,6 +30,8 @@ #include #include #include + +#include #include #include #include @@ -72,6 +74,7 @@ Testsuite const g_interactiveTestsuites[] = { {"Yul Object Compiler", "libyul", "objectCompiler", false, false, &yul::test::ObjectCompilerTest::create}, {"Yul Control Flow Graph", "libyul", "yulControlFlowGraph", false, false, &yul::test::ControlFlowGraphTest::create}, {"Yul SSA Control Flow Graph", "libyul", "yulSSAControlFlowGraph", false, false, &yul::test::SSAControlFlowGraphTest::create}, + {"Yul SSA StackShuffling", "libyul", "ssa/stackShuffler", false, false, &yul::ssa::test::ShufflingTest::create}, {"Yul Stack Layout", "libyul", "yulStackLayout", false, false, &yul::test::StackLayoutGeneratorTest::create}, {"Yul Stack Shuffling", "libyul", "yulStackShuffling", false, false, &yul::test::StackShufflingTest::create}, {"Control Flow Side Effects", "libyul", "controlFlowSideEffects", false, false, &yul::test::ControlFlowSideEffectsTest::create}, diff --git a/test/libyul/ssa/StackShufflerTest.cpp b/test/libyul/ssa/StackShufflerTest.cpp new file mode 100644 index 000000000000..3c8c964e7ef1 --- /dev/null +++ b/test/libyul/ssa/StackShufflerTest.cpp @@ -0,0 +1,453 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#include + +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace solidity; +using namespace solidity::yul::ssa; +using namespace solidity::yul::ssa::test; + +namespace +{ +std::string_view constexpr parserKeyInitialStack {"initial"}; +std::string_view constexpr parserKeyStackTop {"targetStackTop"}; +std::string_view constexpr parserKeyTailSet {"targetStackTailSet"}; +std::string_view constexpr parserKeyStackSize {"targetStackSize"}; + +using Liveness = LivenessAnalysis::LivenessData; +using Slot = StackSlot; +using ValueId = SSACFG::ValueId; +struct StackManipulationCallbacks +{ + void swap(size_t _depth) const + { + if (hook) + (*hook)(fmt::format("SWAP{}", _depth)); + } + void dup(size_t const _depth) const + { + if (hook) + (*hook)(fmt::format("DUP{}", _depth)); + } + void push(Slot const& _slot) const + { + if (hook) + (*hook)(fmt::format("PUSH {}", slotToString(_slot))); + } + void pop() const + { + if (hook) + (*hook)("POP"); + } + + std::optional> hook = std::nullopt; +}; +using TestStack = Stack; + +/// removes leading and trailing whitespace from a string view +std::string_view trim(std::string_view s) +{ + s.remove_prefix(std::min(s.find_first_not_of(" \t\r\v\n"), s.size())); + s.remove_suffix(std::min(s.size() - s.find_last_not_of(" \t\r\v\n") - 1, s.size())); + return s; +} + +/// Parse a value ID token like "v172", "phi109", "lit7", or "JUNK". +Slot parseSlot(std::string_view token) +{ + if (token == "JUNK") + return Slot::makeJunk(); + + if (token.starts_with("v")) + { + if (auto const num = util::parseArithmetic(token.substr(1))) + return Slot::makeValueID(ValueId::makeVariable(*num)); + throw std::runtime_error(fmt::format("Couldn't parse variable token: {}", token)); + } + + if (token.starts_with("phi")) + { + if (auto const num = util::parseArithmetic(token.substr(3))) + return Slot::makeValueID(ValueId::makePhi(*num)); + throw std::runtime_error(fmt::format("Couldn't parse phi token: {}", token)); + } + + if (token.starts_with("lit")) + { + if (auto const num = util::parseArithmetic(token.substr(3))) + return Slot::makeValueID(ValueId::makeLiteral(*num)); + throw std::runtime_error(fmt::format("Couldn't parse literal token: {}", token)); + } + throw std::runtime_error(fmt::format("Unknown token: {}", token)); +} + +/// Parse a string like "[v172, phi109, lit7, JUNK]" into Stack::Data +TestStack::Data parseSlots(std::string_view _input, char const brackBegin = '[', char const brackEnd = ']') +{ + TestStack::Data result; + + // trim and remove brackets + { + _input = trim(_input); + yulAssert(_input.starts_with(brackBegin)); + _input.remove_prefix(1); + yulAssert(_input.ends_with(brackEnd)); + _input.remove_suffix(1); + } + + for (auto&& slotToken: ranges::views::split(_input, ',')) + { + auto const slotTokenBegin = ranges::begin(slotToken); + auto const slotTokenEnd = ranges::end(slotToken); + + std::string_view token; + if(slotTokenBegin != slotTokenEnd) + token = {&*slotTokenBegin, static_cast(ranges::distance(slotTokenBegin, slotTokenEnd))}; + token = trim(token); + yulAssert(!token.empty(), "Empty token."); + result.push_back(parseSlot(token)); + } + return result; +} + +/// Parse liveness like "{phi109, phi150, v172}" +/// Returns Liveness with reference count 1 for each value +Liveness parseLiveness(std::string_view _input) +{ + auto const slots = parseSlots(_input, '{', '}'); + std::vector> liveCounts; + liveCounts.reserve(slots.size()); + for (auto const& slot: slots) + { + yulAssert(slot.isValueID(), "Only value IDs are permitted in liveness definition."); + liveCounts.emplace_back(slot.valueID(), 1); + } + return {liveCounts.begin(), liveCounts.end()}; +} + +struct ShuffleTestInput +{ + std::optional initial; + std::optional targetStackTop; + std::optional targetStackTailSet; + std::optional targetStackSize; + + bool valid() const + { + return initial.has_value() && + targetStackTop.has_value() && + targetStackTailSet.has_value() && + targetStackSize.has_value(); + } + + static ShuffleTestInput parse(std::string_view _source) + { + ShuffleTestInput result; + + auto const stripComment = [](std::string_view sv) -> std::string_view + { + auto const pos = sv.find("//"); + if (pos != std::string_view::npos) + return sv.substr(0, pos); + return sv; + }; + + for (auto&& lineRange: ranges::views::split(_source, '\n')) + { + auto lineBegin = ranges::begin(lineRange); + auto lineEnd = ranges::end(lineRange); + if (lineBegin == lineEnd) + continue; + + std::string_view line{&*lineBegin, static_cast(ranges::distance(lineBegin, lineEnd))}; + line = trim(stripComment(line)); + if (line.empty()) + continue; + + auto const colonPos = line.find(':'); + if (colonPos == std::string_view::npos) + continue; + + auto const key = trim(line.substr(0, colonPos)); + auto const value = trim(line.substr(colonPos + 1)); + + if (key == parserKeyInitialStack) + result.initial = parseSlots(value, '[', ']'); + else if (key == parserKeyStackTop) + result.targetStackTop = parseSlots(value, '[', ']'); + else if (key == parserKeyTailSet) + result.targetStackTailSet = parseLiveness(value); + else if (key == parserKeyStackSize) + { + if (auto num = util::parseArithmetic(value)) + result.targetStackSize = *num; + else + throw std::runtime_error(fmt::format("Couldn't parse targetStackSize: {}", value)); + } + + } + return result; + } +}; + +/// Records a shuffling trace and produces formatted output into some ostream when going out of scope +class TraceRecorder +{ + static size_t constexpr operationColumnWidth = 12; + static size_t constexpr slotColumnWidth = 7; + static char constexpr junkSymbol = '*'; + +public: + TraceRecorder(std::ostream& _out, TestStack::Data const& _targetArgs, Liveness const& _targetTail, size_t _targetStackSize): + m_out(_out), + m_targetArgs(_targetArgs), + m_targetTail(_targetTail), + m_targetStackSize(_targetStackSize), + m_targetTailSize( + [&] { + yulAssert(_targetStackSize >= m_targetArgs.size()); + return _targetStackSize - m_targetArgs.size(); + }() + ) + {} + + void record(std::string const& _operation, TestStack::Data const& _stack) + { + m_entries.push_back(TraceEntry{_operation, _stack}); + } + + ~TraceRecorder() + { + if (m_entries.empty()) + return; + + size_t maxStackDepth = 0; + for (const auto& [operation, stackAfter]: m_entries) + maxStackDepth = std::max(maxStackDepth, stackAfter.size()); + + if (maxStackDepth == 0) + return; + + bool const hasExcess = maxStackDepth > m_targetStackSize; + + emitHeader(maxStackDepth, hasExcess); + emitSeparatorLine(maxStackDepth, hasExcess); + for (auto const& entry: m_entries) + emitDataRow(entry, hasExcess); + emitSeparatorLine(maxStackDepth, hasExcess); + emitTargetRow(hasExcess); + } + +private: + struct TraceEntry { + std::string operation; + TestStack::Data stackAfter; + }; + + std::ostream& m_out; + std::vector m_entries; + TestStack::Data const& m_targetArgs; + Liveness const& m_targetTail; + size_t const m_targetStackSize; + size_t const m_targetTailSize; + + void emitSeparator(size_t const _index, bool const _hasExcess, char const _junction) const + { + bool const endOfTargetTail = _index == m_targetTailSize && !m_targetArgs.empty() && m_targetTailSize > 0; + bool const endOfTargetStackWithExcess = _hasExcess && _index == m_targetTailSize + m_targetArgs.size(); + if (endOfTargetTail || endOfTargetStackWithExcess) + m_out << ' ' << _junction; + } + + void emitHeader(size_t const _maxStackDepth, bool const _hasExcess) const + { + m_out << fmt::format("{:>{}}", "", operationColumnWidth) << "|"; + for (size_t i = 0; i < _maxStackDepth; ++i) + { + emitSeparator(i, _hasExcess, '|'); + m_out << fmt::format("{:>{}}", i, slotColumnWidth); + } + m_out << "\n"; + } + + void emitSeparatorLine(size_t const _maxStackDepth, bool const _hasExcess) const + { + m_out << fmt::format("{:>{}}", "", operationColumnWidth) << '+'; + for (size_t i = 0; i < _maxStackDepth; ++i) + { + emitSeparator(i, _hasExcess, '+'); + m_out << std::string(slotColumnWidth, '-'); + } + m_out << '\n'; + } + + void emitDataRow(TraceEntry const& _entry, bool const _hasExcess) const + { + m_out << fmt::format("{:>{}}", _entry.operation, operationColumnWidth) << "|"; + for (size_t i = 0; i < _entry.stackAfter.size(); ++i) + { + emitSeparator(i, _hasExcess, '|'); + auto const& slot = _entry.stackAfter[i]; + std::string slotStr = slot.isJunk() ? std::string(1, junkSymbol) : slotToString(slot); + m_out << fmt::format("{:>{}}", slotStr, slotColumnWidth); + } + m_out << '\n'; + } + + void emitTargetRow(bool const _hasExcess) const + { + m_out << fmt::format("{:>{}}", "(target)", operationColumnWidth) << "|"; + + // Print tail region with set notation + if (m_targetTailSize > 0 && !(m_targetTail.empty() && m_targetArgs.empty())) + { + std::string const tailSetStr = fmt::format( + "{{{}}}", + fmt::join( + m_targetTail | ranges::views::keys | ranges::views::transform( + [](auto const& id) { return slotToString(Slot::makeValueID(id)); } + ), + ", " + ) + ); + m_out << fmt::format("{:>{}}", tailSetStr, m_targetTailSize * slotColumnWidth); + } + + // Args separator + if (!m_targetArgs.empty() && m_targetTailSize > 0) + m_out << " |"; + + // Print args region + for (auto const& slot: m_targetArgs) + { + std::string slotStr = slot.isJunk() ? std::string(1, junkSymbol) : slotToString(slot); + m_out << fmt::format("{:>{}}", slotStr, slotColumnWidth); + } + + // Excess separator + if (_hasExcess) + m_out << " |"; + + m_out << '\n'; + } +}; +} + +std::unique_ptr ShufflingTest::create(Config const& _config) +{ + return std::make_unique(_config.filename); +} + +ShufflingTest::ShufflingTest(std::string const& _filename): TestCase(_filename) +{ + m_source = m_reader.source(); + auto dialectName = m_reader.stringSetting("dialect", "evm"); + soltestAssert(dialectName == "evm"); + m_expectation = m_reader.simpleExpectations(); +} + +ShufflingTest::TestResult ShufflingTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted) +{ + auto const testConfig = ShuffleTestInput::parse(m_source); + if (!testConfig.valid()) + { + static constexpr std::string_view formatHelp = R"(initial: [, ...] +targetStackTop: [, ...] +targetStackTailSet: {, ...} +targetStackSize: + +Where is one of: + v - variable + phi - phi node + lit - literal + JUNK - junk slot + +Lines starting with // are comments. Comments at the end of lines are supported, too.)"; + util::AnsiColorized out(_stream, _formatted, {util::formatting::BOLD, util::formatting::RED}); + out << _linePrefix << fmt::format("Error parsing source. Expected format:") << '\n'; + + for (auto const line: ranges::views::split(formatHelp, '\n')) + { + auto const lineSVBegin = ranges::begin(line); + auto const lineSVEnd = ranges::end(line); + std::string_view lineSV; + if (lineSVBegin != lineSVEnd) + lineSV = {&*lineSVBegin, static_cast(ranges::distance(lineSVBegin, lineSVEnd))}; + out << _linePrefix << " " << lineSV << '\n'; + } + return TestResult::FatalError; + } + + auto stackData = *testConfig.initial; + std::ostringstream oss; + { + TraceRecorder trace(oss, *testConfig.targetStackTop, *testConfig.targetStackTailSet, *testConfig.targetStackSize); + trace.record("(initial)", *testConfig.initial); + TestStack stack(stackData, {.hook = [&](std::string const& op){ trace.record(op, stackData); }}); + StackShuffler::shuffle( + stack, + *testConfig.targetStackTop, + *testConfig.targetStackTailSet, + *testConfig.targetStackSize + ); + } + // check stack data + { + yulAssert(*testConfig.targetStackSize >= testConfig.targetStackTop->size()); + auto const tailSize = *testConfig.targetStackSize - testConfig.targetStackTop->size(); + yulAssert(stackData.size() == *testConfig.targetStackSize); + for (const auto& valueID: *testConfig.targetStackTailSet | ranges::views::keys) + { + auto const findIt = ranges::find( + stackData.begin(), + stackData.begin() + static_cast(tailSize), + StackSlot::makeValueID(valueID) + ); + yulAssert(findIt != ranges::end(stackData)); + } + for (std::size_t offset = tailSize; offset < *testConfig.targetStackSize; ++offset) + { + auto const& targetSlot = testConfig.targetStackTop->at(offset - tailSize); + yulAssert(targetSlot.isJunk() || stackData[offset] == targetSlot); + } + } + m_obtainedResult = oss.str(); + + + return checkResult(_stream, _linePrefix, _formatted); +} diff --git a/test/libyul/ssa/StackShufflerTest.h b/test/libyul/ssa/StackShufflerTest.h new file mode 100644 index 000000000000..14b0d98f6859 --- /dev/null +++ b/test/libyul/ssa/StackShufflerTest.h @@ -0,0 +1,36 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include + +#include + +namespace solidity::yul::ssa::test +{ + +class ShufflingTest: public frontend::test::TestCase +{ +public: + static std::unique_ptr create(Config const& _config); + explicit ShufflingTest(std::string const& _filename); + TestResult run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) override; +}; + +} diff --git a/test/tools/CMakeLists.txt b/test/tools/CMakeLists.txt index 31bdf34ee4f9..7b7331c77f09 100644 --- a/test/tools/CMakeLists.txt +++ b/test/tools/CMakeLists.txt @@ -53,6 +53,8 @@ add_executable(isoltest ../libyul/YulOptimizerTest.cpp ../libyul/YulOptimizerTestCommon.cpp ../libyul/YulInterpreterTest.cpp + ../libyul/ssa/StackShufflerTest.cpp + ../libyul/ssa/StackShufflerTest.h ) target_compile_definitions(isoltest PRIVATE ISOLTEST) target_link_libraries(isoltest PRIVATE evmc libsolc solidity yulInterpreter evmasm Boost::boost Boost::program_options Boost::unit_test_framework Threads::Threads) From 70d774f70ac92a22cacc3b8b038f6f8034c3a960 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 2 Feb 2026 12:14:43 +0100 Subject: [PATCH 52/73] Add stack shuffler tests --- .../deep_argument_dup_order.stack | 14 ++ .../stackShuffler/deep_argument_shrink.stack | 20 +++ .../ssa/stackShuffler/dup_up_args.stack | 18 +++ test/libyul/ssa/stackShuffler/empty.stack | 14 ++ test/libyul/ssa/stackShuffler/grow.stack | 12 ++ .../ssa/stackShuffler/introduce_junk.stack | 17 +++ .../ssa/stackShuffler/reduce_size.stack | 13 ++ .../satisfy_tail_requirements.stack | 30 +++++ .../stackShuffler/shrink_and_grow_a_lot.stack | 122 ++++++++++++++++++ .../stackShuffler/superfluous_top_slots.stack | 18 +++ .../stackShuffler/swap_junk_over_pop.stack | 14 ++ 11 files changed, 292 insertions(+) create mode 100644 test/libyul/ssa/stackShuffler/deep_argument_dup_order.stack create mode 100644 test/libyul/ssa/stackShuffler/deep_argument_shrink.stack create mode 100644 test/libyul/ssa/stackShuffler/dup_up_args.stack create mode 100644 test/libyul/ssa/stackShuffler/empty.stack create mode 100644 test/libyul/ssa/stackShuffler/grow.stack create mode 100644 test/libyul/ssa/stackShuffler/introduce_junk.stack create mode 100644 test/libyul/ssa/stackShuffler/reduce_size.stack create mode 100644 test/libyul/ssa/stackShuffler/satisfy_tail_requirements.stack create mode 100644 test/libyul/ssa/stackShuffler/shrink_and_grow_a_lot.stack create mode 100644 test/libyul/ssa/stackShuffler/superfluous_top_slots.stack create mode 100644 test/libyul/ssa/stackShuffler/swap_junk_over_pop.stack diff --git a/test/libyul/ssa/stackShuffler/deep_argument_dup_order.stack b/test/libyul/ssa/stackShuffler/deep_argument_dup_order.stack new file mode 100644 index 000000000000..3dbbcf438d5d --- /dev/null +++ b/test/libyul/ssa/stackShuffler/deep_argument_dup_order.stack @@ -0,0 +1,14 @@ +// if lit0 is pushed first, v129 can no longer be duped up +initial: [v129, v43, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, v101, JUNK, v130, v131] +targetStackTop: [v43, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, lit0, v129] +targetStackTailSet: {v129} +targetStackSize: 18 +// ---- +// | 0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 +// +------- +----------------------------------------------------------------------------------------------------------------------- +// (initial)| v129 | v43 * * * * * * * * * * v101 * v130 v131 +// DUP16| v129 | v43 * * * * * * * * * * v101 * v130 v131 v129 +// PUSH lit0| v129 | v43 * * * * * * * * * * v101 * v130 v131 v129 lit0 +// SWAP1| v129 | v43 * * * * * * * * * * v101 * v130 v131 lit0 v129 +// +------- +----------------------------------------------------------------------------------------------------------------------- +// (target)| {v129} | v43 * * * * * * * * * * * * * * lit0 v129 diff --git a/test/libyul/ssa/stackShuffler/deep_argument_shrink.stack b/test/libyul/ssa/stackShuffler/deep_argument_shrink.stack new file mode 100644 index 000000000000..b7fdbcbafeda --- /dev/null +++ b/test/libyul/ssa/stackShuffler/deep_argument_shrink.stack @@ -0,0 +1,20 @@ +// the shuffler has to first shrink the stack to reach v12 for args +initial: [v12, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, v68, JUNK, phi111, v84, v86] +targetStackTop: [v12, v86] +targetStackTailSet: {v68, v84, phi111} +targetStackSize: 19 +// ---- +// | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 17 18 +// +----------------------------------------------------------------------------------------------------------------------- +-------------- +// (initial)| v12 * * * * * * * * * * * * v68 * phi111 v84 | v86 +// SWAP3| v12 * * * * * * * * * * * * v68 v86 phi111 v84 | * +// POP| v12 * * * * * * * * * * * * v68 v86 phi111 v84 +// SWAP2| v12 * * * * * * * * * * * * v68 v84 phi111 v86 +// SWAP4| v12 * * * * * * * * * * * v86 v68 v84 phi111 * +// POP| v12 * * * * * * * * * * * v86 v68 v84 phi111 +// SWAP15| phi111 * * * * * * * * * * * v86 v68 v84 v12 +// DUP4| phi111 * * * * * * * * * * * v86 v68 v84 v12 v86 +// DUP2| phi111 * * * * * * * * * * * v86 v68 v84 v12 v86 | v12 +// DUP2| phi111 * * * * * * * * * * * v86 v68 v84 v12 v86 | v12 v86 +// +----------------------------------------------------------------------------------------------------------------------- +-------------- +// (target)| {v68, v84, phi111} | v12 v86 diff --git a/test/libyul/ssa/stackShuffler/dup_up_args.stack b/test/libyul/ssa/stackShuffler/dup_up_args.stack new file mode 100644 index 000000000000..f3be04a8954d --- /dev/null +++ b/test/libyul/ssa/stackShuffler/dup_up_args.stack @@ -0,0 +1,18 @@ +// populate args by a sequence of dups +initial: [JUNK, v12, phi9, phi13, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, v65, v67] +targetStackTop: [lit27, phi13, phi9, v12, v67] +targetStackTailSet: {phi9, v12, phi13, v65} +targetStackSize: 21 +// ---- +// | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 16 17 18 19 20 +// +---------------------------------------------------------------------------------------------------------------- +----------------------------------- +// (initial)| * v12 phi9 phi13 * * * * * * * * v65 v67 +// DUP13| * v12 phi9 phi13 * * * * * * * * v65 v67 v12 +// DUP13| * v12 phi9 phi13 * * * * * * * * v65 v67 v12 phi9 +// PUSH lit27| * v12 phi9 phi13 * * * * * * * * v65 v67 v12 phi9 | lit27 +// DUP14| * v12 phi9 phi13 * * * * * * * * v65 v67 v12 phi9 | lit27 phi13 +// DUP3| * v12 phi9 phi13 * * * * * * * * v65 v67 v12 phi9 | lit27 phi13 phi9 +// DUP5| * v12 phi9 phi13 * * * * * * * * v65 v67 v12 phi9 | lit27 phi13 phi9 v12 +// DUP7| * v12 phi9 phi13 * * * * * * * * v65 v67 v12 phi9 | lit27 phi13 phi9 v12 v67 +// +---------------------------------------------------------------------------------------------------------------- +----------------------------------- +// (target)| {phi9, v12, phi13, v65} | lit27 phi13 phi9 v12 v67 diff --git a/test/libyul/ssa/stackShuffler/empty.stack b/test/libyul/ssa/stackShuffler/empty.stack new file mode 100644 index 000000000000..077660d6f741 --- /dev/null +++ b/test/libyul/ssa/stackShuffler/empty.stack @@ -0,0 +1,14 @@ +// populate an empty stack with junk +initial: [] +targetStackTop: [] +targetStackTailSet: {} +targetStackSize: 3 +// ---- +// | 0 1 2 +// +--------------------- +// (initial)| +// PUSH JUNK| * +// PUSH JUNK| * * +// PUSH JUNK| * * * +// +--------------------- +// (target)| diff --git a/test/libyul/ssa/stackShuffler/grow.stack b/test/libyul/ssa/stackShuffler/grow.stack new file mode 100644 index 000000000000..4c07f8e36f6e --- /dev/null +++ b/test/libyul/ssa/stackShuffler/grow.stack @@ -0,0 +1,12 @@ +// need to grow the stack to reach target stack size but still fulfill args requirements +initial: [JUNK, JUNK, JUNK, v15] +targetStackTop: [JUNK, JUNK, JUNK, JUNK, v15] +targetStackTailSet: {} +targetStackSize: 5 +// ---- +// | 0 1 2 3 4 +// +----------------------------------- +// (initial)| * * * v15 +// DUP1| * * * v15 v15 +// +----------------------------------- +// (target)| * * * * v15 diff --git a/test/libyul/ssa/stackShuffler/introduce_junk.stack b/test/libyul/ssa/stackShuffler/introduce_junk.stack new file mode 100644 index 000000000000..54b29a9a319b --- /dev/null +++ b/test/libyul/ssa/stackShuffler/introduce_junk.stack @@ -0,0 +1,17 @@ +// some of the slots in the initial stack no longer appear in the target / are junk +initial: [v189, phi112, JUNK, v204, JUNK, JUNK, JUNK, v185, JUNK, v188, v190, v191, JUNK, v199, phi112, phi112, v205, v206] +targetStackTop: [v199, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, v185, JUNK, v188, v190, v191, JUNK, v189, JUNK, v206, v205, v204] +targetStackTailSet: {} +targetStackSize: 18 +// ---- +// | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 +// +------------------------------------------------------------------------------------------------------------------------------ +// (initial)| v189 phi112 * v204 * * * v185 * v188 v190 v191 * v199 phi112 phi112 v205 v206 +// SWAP2| v189 phi112 * v204 * * * v185 * v188 v190 v191 * v199 phi112 v206 v205 phi112 +// POP| v189 phi112 * v204 * * * v185 * v188 v190 v191 * v199 phi112 v206 v205 +// SWAP16| v205 phi112 * v204 * * * v185 * v188 v190 v191 * v199 phi112 v206 v189 +// SWAP3| v205 phi112 * v204 * * * v185 * v188 v190 v191 * v189 phi112 v206 v199 +// SWAP16| v199 phi112 * v204 * * * v185 * v188 v190 v191 * v189 phi112 v206 v205 +// DUP14| v199 phi112 * v204 * * * v185 * v188 v190 v191 * v189 phi112 v206 v205 v204 +// +------------------------------------------------------------------------------------------------------------------------------ +// (target)| v199 * * * * * * v185 * v188 v190 v191 * v189 * v206 v205 v204 diff --git a/test/libyul/ssa/stackShuffler/reduce_size.stack b/test/libyul/ssa/stackShuffler/reduce_size.stack new file mode 100644 index 000000000000..d6a6706193f3 --- /dev/null +++ b/test/libyul/ssa/stackShuffler/reduce_size.stack @@ -0,0 +1,13 @@ +// v199 can be popped as it's already contained in the tail +initial: [JUNK, v189, phi112, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, v185, phi115, v188, v190, v191, phi113, v199, phi112, v199, v202] +targetStackTop: [v202] +targetStackTailSet: {phi112, phi113, phi115, v185, v188, v189, v190, v191, v199} +targetStackSize: 19 +// ---- +// | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 18 | 19 +// +------------------------------------------------------------------------------------------------------------------------------ +------- +------- +// (initial)| * v189 phi112 * * * * * * * v185 phi115 v188 v190 v191 phi113 v199 phi112 | v199 | v202 +// SWAP1| * v189 phi112 * * * * * * * v185 phi115 v188 v190 v191 phi113 v199 phi112 | v202 | v199 +// POP| * v189 phi112 * * * * * * * v185 phi115 v188 v190 v191 phi113 v199 phi112 | v202 +// +------------------------------------------------------------------------------------------------------------------------------ +------- +------- +// (target)| {phi112, phi113, phi115, v185, v188, v189, v190, v191, v199} | v202 | diff --git a/test/libyul/ssa/stackShuffler/satisfy_tail_requirements.stack b/test/libyul/ssa/stackShuffler/satisfy_tail_requirements.stack new file mode 100644 index 000000000000..e685f06607a0 --- /dev/null +++ b/test/libyul/ssa/stackShuffler/satisfy_tail_requirements.stack @@ -0,0 +1,30 @@ +// here, we have to create one more instance of v10 to be able to satisfy the tail requirements +initial: [v2, v3, v4, v5, v6, v7, v8, v9, v10] +targetStackTop: [lit3, v9, v8, v7, v6, v5, v4, v3, v2, v10] +targetStackTailSet: {v10} +targetStackSize: 17 +// ---- +// | 0 1 2 3 4 5 6 | 7 8 9 10 11 12 13 14 15 16 +// +------------------------------------------------- +---------------------------------------------------------------------- +// (initial)| v2 v3 v4 v5 v6 v7 v8 | v9 v10 +// DUP1| v2 v3 v4 v5 v6 v7 v8 | v9 v10 v10 +// SWAP9| v10 v3 v4 v5 v6 v7 v8 | v9 v10 v2 +// SWAP2| v10 v3 v4 v5 v6 v7 v8 | v2 v10 v9 +// SWAP1| v10 v3 v4 v5 v6 v7 v8 | v2 v9 v10 +// PUSH lit3| v10 v3 v4 v5 v6 v7 v8 | v2 v9 v10 lit3 +// SWAP3| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v10 v2 +// DUP5| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v10 v2 v8 +// SWAP2| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v2 v10 +// DUP7| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v2 v10 v7 +// SWAP2| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v10 v2 +// DUP9| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v10 v2 v6 +// SWAP2| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v2 v10 +// DUP11| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v2 v10 v5 +// SWAP2| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v5 v10 v2 +// DUP13| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v5 v10 v2 v4 +// SWAP2| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v5 v4 v2 v10 +// DUP15| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v5 v4 v2 v10 v3 +// SWAP2| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v5 v4 v3 v10 v2 +// SWAP1| v10 v3 v4 v5 v6 v7 v8 | lit3 v9 v8 v7 v6 v5 v4 v3 v2 v10 +// +------------------------------------------------- +---------------------------------------------------------------------- +// (target)| {v10} | lit3 v9 v8 v7 v6 v5 v4 v3 v2 v10 diff --git a/test/libyul/ssa/stackShuffler/shrink_and_grow_a_lot.stack b/test/libyul/ssa/stackShuffler/shrink_and_grow_a_lot.stack new file mode 100644 index 000000000000..7d4f68a8a949 --- /dev/null +++ b/test/libyul/ssa/stackShuffler/shrink_and_grow_a_lot.stack @@ -0,0 +1,122 @@ +// the stack top needs a very deep slot +initial: [v55, v71, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, JUNK, v94] +targetStackTop: [lit11, v55] +targetStackTailSet: {v55, v71, v94} +targetStackSize: 54 +// todo: instead of alternating swap1 + pop, we should be (eg) doing swap16 and then a sequence of 16 pops +// ---- +// | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 52 53 +// +---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------- +// (initial)| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * * v94 +// SWAP1| v55 v71 * * * * * * * * * * * * * v94 * +// POP| v55 v71 * * * * * * * * * * * * * v94 +// DUP16| v55 v71 * * * * * * * * * * * * * v94 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// DUP1| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 +// PUSH lit11| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 | lit11 +// DUP2| v55 v71 * * * * * * * * * * * * * v94 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 v55 | lit11 v55 +// +---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------- +// (target)| {v55, v71, v94} | lit11 v55 diff --git a/test/libyul/ssa/stackShuffler/superfluous_top_slots.stack b/test/libyul/ssa/stackShuffler/superfluous_top_slots.stack new file mode 100644 index 000000000000..87d9ea9a81c3 --- /dev/null +++ b/test/libyul/ssa/stackShuffler/superfluous_top_slots.stack @@ -0,0 +1,18 @@ +// todo: The upper two junk slots should be popped immediately, they are completely superfluous. +initial: [JUNK, JUNK, v56, v57, JUNK, JUNK] +targetStackTop: [JUNK, JUNK, v56, v57, lit0, v56, lit11] +targetStackTailSet: {} +targetStackSize: 7 +// ---- +// | 0 1 2 3 4 5 6 | 7 +// +------------------------------------------------- +------- +// (initial)| * * v56 v57 * * +// PUSH lit11| * * v56 v57 * * lit11 +// DUP5| * * v56 v57 * * lit11 | v56 +// SWAP2| * * v56 v57 * v56 lit11 | * +// POP| * * v56 v57 * v56 lit11 +// PUSH lit0| * * v56 v57 * v56 lit11 | lit0 +// SWAP3| * * v56 v57 lit0 v56 lit11 | * +// POP| * * v56 v57 lit0 v56 lit11 +// +------------------------------------------------- +------- +// (target)| * * v56 v57 lit0 v56 lit11 | diff --git a/test/libyul/ssa/stackShuffler/swap_junk_over_pop.stack b/test/libyul/ssa/stackShuffler/swap_junk_over_pop.stack new file mode 100644 index 000000000000..56f623b75473 --- /dev/null +++ b/test/libyul/ssa/stackShuffler/swap_junk_over_pop.stack @@ -0,0 +1,14 @@ +// here, the algorithm should prefer a swap of junk into tail over pop and dup +initial: [v0, JUNK, v2] +targetStackTop: [lit2, v2, v0] +targetStackTailSet: {} +targetStackSize: 4 +// ---- +// | 0 | 1 2 3 +// +------- +--------------------- +// (initial)| v0 | * v2 +// PUSH lit2| v0 | * v2 lit2 +// SWAP2| v0 | lit2 v2 * +// SWAP3| * | lit2 v2 v0 +// +------- +--------------------- +// (target)| {} | lit2 v2 v0 From 8f643082c250abbebba5a4f81d88129041ca4e4a Mon Sep 17 00:00:00 2001 From: Tilak Madichetti Date: Sat, 29 Mar 2025 13:14:35 +0530 Subject: [PATCH 53/73] Update resources.rst --- docs/resources.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/resources.rst b/docs/resources.rst index 52df87fdd55c..3dac252ee159 100644 --- a/docs/resources.rst +++ b/docs/resources.rst @@ -107,7 +107,7 @@ Solidity Tools Tool to generate Solidity interface source from a given ABI JSON. * `Aderyn `_ - Rust-based solidity smart contract static analyzer designed to help find vulnerabilities in Solidity code bases. + Rust-based solidity smart contract static analyzer designed to help find vulnerabilities in Solidity code bases. Comes with `VS Code Extension ` for easy use. * `Doxity `_ Documentation Generator for Solidity. From 1a499f10f0fd4cfc0563bd1770627573c0086c5b Mon Sep 17 00:00:00 2001 From: Tilak Madichetti Date: Mon, 23 Jun 2025 08:22:18 +0000 Subject: [PATCH 54/73] fix --- docs/resources.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/resources.rst b/docs/resources.rst index 3dac252ee159..7fdb55367cbf 100644 --- a/docs/resources.rst +++ b/docs/resources.rst @@ -78,6 +78,9 @@ Editor Integrations * Visual Studio Code (VS Code) + * `Aderyn Visual Studio Code extension `_ + Solidity Smart contract analyzer designed to help find vulnerabilities. It supports projects built with Hardhat, Foundry, or any custom framework. + * `Ethereum Remix Visual Studio Code extension `_ Ethereum Remix extension pack for VS Code 💡 Note: As per the official repository, this extension has been removed from the VSCODE marketplace and will be replaced by a dedicated stand-alone desktop application. @@ -107,7 +110,7 @@ Solidity Tools Tool to generate Solidity interface source from a given ABI JSON. * `Aderyn `_ - Rust-based solidity smart contract static analyzer designed to help find vulnerabilities in Solidity code bases. Comes with `VS Code Extension ` for easy use. + Command Line Tool that helps find vulnerabilities in Solidity smart contracts. It supports projects built with Hardhat, Foundry, or any custom framework. * `Doxity `_ Documentation Generator for Solidity. From 7e2fb2d4739e135a9622df778e50af52a05cc134 Mon Sep 17 00:00:00 2001 From: rodiazet Date: Wed, 4 Feb 2026 10:30:36 +0100 Subject: [PATCH 55/73] Fix `check_style.sh`. Replace `\s` to `[[:space:]]` --- scripts/check_style.sh | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/scripts/check_style.sh b/scripts/check_style.sh index 7188f84f2b33..5a744de78e1f 100755 --- a/scripts/check_style.sh +++ b/scripts/check_style.sh @@ -47,19 +47,19 @@ FORMATERROR=$( ( preparedGrep "#include \"" | grep -E -v -e "license.h" -e "BuildInfo.h" # Use include with <> characters preparedGrep "\<(if|for|while|switch)\(" # no space after "if", "for", "while" or "switch" - preparedGrep "\\s*\([^=]*\>\s:\s.*\)" # no space before range based for-loop - preparedGrep "\\s*\(.*\)\s*\{\s*$" # "{\n" on same line as "if" + preparedGrep "\[[:space:]]*\([^=]*\>[[:space:]]:[[:space:]].*\)" # no space before range based for-loop + preparedGrep "\[[:space:]]*\(.*\)[[:space:]]*\{[[:space:]]*$" # "{\n" on same line as "if" preparedGrep "namespace .*\{" - preparedGrep "[,\(<]\s*const " # const on left side of type - preparedGrep "^\s*(static)?\s*const " # const on left side of type (beginning of line) + preparedGrep "[,\(<][[:space:]]*const " # const on left side of type + preparedGrep "^[[:space:]]*(static)?[[:space:]]*const " # const on left side of type (beginning of line) preparedGrep "^ [^*]|[^*] | [^*]" # uses spaces for indentation or mixes spaces and tabs - preparedGrep "[a-zA-Z0-9_]\s*[&][a-zA-Z_]" | grep -E -v "return [&]" # right-aligned reference ampersand (needs to exclude return) + preparedGrep "[a-zA-Z0-9_][[:space:]]*[&][a-zA-Z_]" | grep -E -v "return [&]" # right-aligned reference ampersand (needs to exclude return) # right-aligned reference pointer star (needs to exclude return and comments) - preparedGrep "[a-zA-Z0-9_]\s*[*][a-zA-Z_]" | grep -E -v -e "return [*]" -e ":[0-9]+:\s*\*\s" -e "//" + preparedGrep "[a-zA-Z0-9_][[:space:]]*[*][a-zA-Z_]" | grep -E -v -e "return [*]" -e ":[0-9]+:[[:space:]]*\*[[:space:]]" -e "//" # unqualified move()/forward() checks, i.e. make sure that std::move() and std::forward() are used instead of move() and forward() preparedGrep "move\(.+\)" | grep -v "std::move" | grep -E "[^a-z]move" preparedGrep "forward\(.+\)" | grep -v "std::forward" | grep -E "[^a-z]forward" -) | grep -E -v -e "^[a-zA-Z./]*:[0-9]*:\s*/[/*]" -e "^test/" || true +) | grep -E -v -e "^[a-zA-Z./]*:[0-9]*:[[:space:]]*/[/*]" -e "^test/" || true ) # Special error handling for `using namespace std;` exclusion, since said statement can be present in the test directory From 64f26d919034c0e9060a90386bcd76d434f13129 Mon Sep 17 00:00:00 2001 From: davidekete Date: Sat, 7 Feb 2026 15:27:12 +0100 Subject: [PATCH 56/73] update information about using Remix offline --- docs/installing-solidity.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/installing-solidity.rst b/docs/installing-solidity.rst index f061829ecf32..7e372ea4e3bf 100644 --- a/docs/installing-solidity.rst +++ b/docs/installing-solidity.rst @@ -31,8 +31,7 @@ Remix *We recommend Remix for small contracts and for quickly learning Solidity.* `Access Remix online `_, you do not need to install anything. -If you want to use it without connection to the Internet, go to -https://github.com/ethereum/remix-live/tree/gh-pages#readme and follow the instructions on that page. +If you want to use it without connection to the Internet, download Remix Desktop from `the releases page `_. Remix is also a convenient option for testing nightly builds without installing multiple Solidity versions. From 39bf0830b80fd5de8dbac5312d78c0e4eec8f0ad Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 9 Feb 2026 11:18:53 +0100 Subject: [PATCH 57/73] move SSACFGTopologicalSort -> traversal/ForwardTopologicalSort --- libyul/CMakeLists.txt | 4 ++-- .../backends/evm/ssa/JunkAdmittingBlocksFinder.cpp | 2 +- libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.h | 4 ++-- libyul/backends/evm/ssa/LivenessAnalysis.h | 6 +++--- libyul/backends/evm/ssa/SSACFGLoopNestingForest.cpp | 2 +- libyul/backends/evm/ssa/SSACFGLoopNestingForest.h | 6 +++--- .../ForwardTopologicalSort.cpp} | 12 ++++++------ .../ForwardTopologicalSort.h} | 6 +++--- 8 files changed, 21 insertions(+), 21 deletions(-) rename libyul/backends/evm/ssa/{SSACFGTopologicalSort.cpp => traversal/ForwardTopologicalSort.cpp} (83%) rename libyul/backends/evm/ssa/{SSACFGTopologicalSort.h => traversal/ForwardTopologicalSort.h} (94%) diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index 9d0bfe1e2e53..2e62f6d94696 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -82,8 +82,6 @@ add_library(yul backends/evm/ssa/LivenessAnalysis.h backends/evm/ssa/SSACFGLoopNestingForest.cpp backends/evm/ssa/SSACFGLoopNestingForest.h - backends/evm/ssa/SSACFGTopologicalSort.cpp - backends/evm/ssa/SSACFGTopologicalSort.h backends/evm/ssa/SSACFG.cpp backends/evm/ssa/SSACFG.h backends/evm/ssa/SSACFGBuilder.cpp @@ -94,6 +92,8 @@ add_library(yul backends/evm/ssa/Stack.h backends/evm/ssa/StackShuffler.cpp backends/evm/ssa/StackShuffler.h + backends/evm/ssa/traversal/ForwardTopologicalSort.cpp + backends/evm/ssa/traversal/ForwardTopologicalSort.h optimiser/ASTCopier.cpp optimiser/ASTCopier.h optimiser/ASTWalker.cpp diff --git a/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.cpp b/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.cpp index d7c9202ef484..e0519db61420 100644 --- a/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.cpp +++ b/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.cpp @@ -23,7 +23,7 @@ namespace solidity::yul::ssa { -JunkAdmittingBlocksFinder::JunkAdmittingBlocksFinder(SSACFG const& _cfg, ForwardSSACFGTopologicalSort const& _topologicalSort): +JunkAdmittingBlocksFinder::JunkAdmittingBlocksFinder(SSACFG const& _cfg, traversal::ForwardTopologicalSort const& _topologicalSort): m_blockAllowsJunk(_cfg.numBlocks(), false) { // special case: only one block here, we mark it as junkable in case it's not a function return diff --git a/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.h b/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.h index e567603dd31b..6d2104b03fc0 100644 --- a/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.h +++ b/libyul/backends/evm/ssa/JunkAdmittingBlocksFinder.h @@ -18,7 +18,7 @@ #pragma once -#include +#include #include #include @@ -37,7 +37,7 @@ namespace solidity::yul::ssa class JunkAdmittingBlocksFinder { public: - explicit JunkAdmittingBlocksFinder(SSACFG const& _cfg, ForwardSSACFGTopologicalSort const& _topologicalSort); + explicit JunkAdmittingBlocksFinder(SSACFG const& _cfg, traversal::ForwardTopologicalSort const& _topologicalSort); bool allowsAdditionOfJunk(SSACFG::BlockId const& _blockId) const; private: std::vector m_blockAllowsJunk; diff --git a/libyul/backends/evm/ssa/LivenessAnalysis.h b/libyul/backends/evm/ssa/LivenessAnalysis.h index b34a790bf1be..5a19cb0bd32d 100644 --- a/libyul/backends/evm/ssa/LivenessAnalysis.h +++ b/libyul/backends/evm/ssa/LivenessAnalysis.h @@ -18,7 +18,7 @@ #pragma once -#include +#include #include #include @@ -107,7 +107,7 @@ class LivenessAnalysis LivenessData const& liveOut(SSACFG::BlockId const _blockId) const { return m_liveOuts[_blockId.value]; } LivenessData used(SSACFG::BlockId _blockId) const; std::vector const& operationsLiveOut(SSACFG::BlockId _blockId) const { return m_operationLiveOuts[_blockId.value]; } - ForwardSSACFGTopologicalSort const& topologicalSort() const { return m_topologicalSort; } + traversal::ForwardTopologicalSort const& topologicalSort() const { return m_topologicalSort; } SSACFG const& cfg() const { return m_cfg; } private: @@ -117,7 +117,7 @@ class LivenessAnalysis LivenessData blockExitValues(SSACFG::BlockId const& _blockId) const; SSACFG const& m_cfg; - ForwardSSACFGTopologicalSort m_topologicalSort; + traversal::ForwardTopologicalSort m_topologicalSort; SSACFGLoopNestingForest m_loopNestingForest; std::vector m_liveIns; std::vector m_liveOuts; diff --git a/libyul/backends/evm/ssa/SSACFGLoopNestingForest.cpp b/libyul/backends/evm/ssa/SSACFGLoopNestingForest.cpp index c5c422a46728..6adff4023bd6 100644 --- a/libyul/backends/evm/ssa/SSACFGLoopNestingForest.cpp +++ b/libyul/backends/evm/ssa/SSACFGLoopNestingForest.cpp @@ -22,7 +22,7 @@ using namespace solidity::yul::ssa; -SSACFGLoopNestingForest::SSACFGLoopNestingForest(ForwardSSACFGTopologicalSort const& _sort): +SSACFGLoopNestingForest::SSACFGLoopNestingForest(traversal::ForwardTopologicalSort const& _sort): m_sort(_sort), m_cfg(_sort.cfg()), m_vertexPartition(m_cfg.numBlocks()), diff --git a/libyul/backends/evm/ssa/SSACFGLoopNestingForest.h b/libyul/backends/evm/ssa/SSACFGLoopNestingForest.h index 4654cbf135aa..2ee833335690 100644 --- a/libyul/backends/evm/ssa/SSACFGLoopNestingForest.h +++ b/libyul/backends/evm/ssa/SSACFGLoopNestingForest.h @@ -18,7 +18,7 @@ #pragma once -#include +#include #include #include @@ -39,7 +39,7 @@ class SSACFGLoopNestingForest using BlockIdValue = SSACFG::BlockId::ValueType; public: - explicit SSACFGLoopNestingForest(ForwardSSACFGTopologicalSort const& _sort); + explicit SSACFGLoopNestingForest(traversal::ForwardTopologicalSort const& _sort); /// blocks which are not contained in a loop get assigned the loop parent numeric_limit::max() std::vector const& loopParents() const { return m_loopParents; } @@ -51,7 +51,7 @@ class SSACFGLoopNestingForest void findLoop(BlockIdValue _potentialHeader); void collapse(std::set const& _loopBody, BlockIdValue _loopHeader); - ForwardSSACFGTopologicalSort const& m_sort; + traversal::ForwardTopologicalSort const& m_sort; SSACFG const& m_cfg; util::ContiguousDisjointSet m_vertexPartition; diff --git a/libyul/backends/evm/ssa/SSACFGTopologicalSort.cpp b/libyul/backends/evm/ssa/traversal/ForwardTopologicalSort.cpp similarity index 83% rename from libyul/backends/evm/ssa/SSACFGTopologicalSort.cpp rename to libyul/backends/evm/ssa/traversal/ForwardTopologicalSort.cpp index 3a1ca43c5716..f880954ab16d 100644 --- a/libyul/backends/evm/ssa/SSACFGTopologicalSort.cpp +++ b/libyul/backends/evm/ssa/traversal/ForwardTopologicalSort.cpp @@ -16,11 +16,11 @@ */ // SPDX-License-Identifier: GPL-3.0 -#include +#include -using namespace solidity::yul::ssa; +using namespace solidity::yul::ssa::traversal; -ForwardSSACFGTopologicalSort::ForwardSSACFGTopologicalSort(SSACFG const& _cfg): +ForwardTopologicalSort::ForwardTopologicalSort(SSACFG const& _cfg): m_cfg(_cfg), m_explored(m_cfg.numBlocks(), false), m_blockWisePreOrder(m_cfg.numBlocks(), 0), m_blockWiseMaxSubtreePreOrder(m_cfg.numBlocks(), 0) @@ -35,7 +35,7 @@ ForwardSSACFGTopologicalSort::ForwardSSACFGTopologicalSort(SSACFG const& _cfg): m_backEdgeTargets.insert(v2); } -void ForwardSSACFGTopologicalSort::dfs(SSACFG::BlockId::ValueType const _vertex) { +void ForwardTopologicalSort::dfs(SSACFG::BlockId::ValueType const _vertex) { yulAssert(!m_explored[_vertex]); m_explored[_vertex] = true; m_blockWisePreOrder[_vertex] = static_cast(m_preOrder.size()); @@ -55,7 +55,7 @@ void ForwardSSACFGTopologicalSort::dfs(SSACFG::BlockId::ValueType const _vertex) m_postOrder.push_back(_vertex); } -bool ForwardSSACFGTopologicalSort::ancestor(SSACFG::BlockId::ValueType const _block1, SSACFG::BlockId::ValueType const _block2) const { +bool ForwardTopologicalSort::ancestor(SSACFG::BlockId::ValueType const _block1, SSACFG::BlockId::ValueType const _block2) const { yulAssert(_block1 < m_blockWisePreOrder.size()); yulAssert(_block2 < m_blockWisePreOrder.size()); @@ -67,7 +67,7 @@ bool ForwardSSACFGTopologicalSort::ancestor(SSACFG::BlockId::ValueType const _bl return node1VisitedBeforeNode2 && node2InSubtreeOfNode1; } -bool ForwardSSACFGTopologicalSort::backEdge(SSACFG::BlockId const& _block1, SSACFG::BlockId const& _block2) const +bool ForwardTopologicalSort::backEdge(SSACFG::BlockId const& _block1, SSACFG::BlockId const& _block2) const { if (ancestor(_block2.value, _block1.value)) { diff --git a/libyul/backends/evm/ssa/SSACFGTopologicalSort.h b/libyul/backends/evm/ssa/traversal/ForwardTopologicalSort.h similarity index 94% rename from libyul/backends/evm/ssa/SSACFGTopologicalSort.h rename to libyul/backends/evm/ssa/traversal/ForwardTopologicalSort.h index 39c2eebc35a0..b116635975b8 100644 --- a/libyul/backends/evm/ssa/SSACFGTopologicalSort.h +++ b/libyul/backends/evm/ssa/traversal/ForwardTopologicalSort.h @@ -24,14 +24,14 @@ #include #include -namespace solidity::yul::ssa +namespace solidity::yul::ssa::traversal { /// Performs a topological sort on the forward CFG (no back/cross edges) -class ForwardSSACFGTopologicalSort +class ForwardTopologicalSort { public: - explicit ForwardSSACFGTopologicalSort(SSACFG const& _cfg); + explicit ForwardTopologicalSort(SSACFG const& _cfg); std::vector const& preOrder() const { return m_preOrder; } std::vector const& postOrder() const { return m_postOrder; } From d783ff9813bf5243355b882fb1901b1f94c899a7 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 9 Feb 2026 11:22:31 +0100 Subject: [PATCH 58/73] move SSA CFG json exporter into io subdirectory and namespace --- libyul/CMakeLists.txt | 4 ++-- libyul/YulStack.cpp | 4 ++-- .../{SSACFGJsonExporter.cpp => io/JSONExporter.cpp} | 10 ++++------ .../ssa/{SSACFGJsonExporter.h => io/JSONExporter.h} | 2 +- 4 files changed, 9 insertions(+), 11 deletions(-) rename libyul/backends/evm/ssa/{SSACFGJsonExporter.cpp => io/JSONExporter.cpp} (95%) rename libyul/backends/evm/ssa/{SSACFGJsonExporter.h => io/JSONExporter.h} (95%) diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index 2e62f6d94696..d425283b6969 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -86,12 +86,12 @@ add_library(yul backends/evm/ssa/SSACFG.h backends/evm/ssa/SSACFGBuilder.cpp backends/evm/ssa/SSACFGBuilder.h - backends/evm/ssa/SSACFGJsonExporter.cpp - backends/evm/ssa/SSACFGJsonExporter.h backends/evm/ssa/Stack.cpp backends/evm/ssa/Stack.h backends/evm/ssa/StackShuffler.cpp backends/evm/ssa/StackShuffler.h + backends/evm/ssa/io/JSONExporter.cpp + backends/evm/ssa/io/JSONExporter.h backends/evm/ssa/traversal/ForwardTopologicalSort.cpp backends/evm/ssa/traversal/ForwardTopologicalSort.h optimiser/ASTCopier.cpp diff --git a/libyul/YulStack.cpp b/libyul/YulStack.cpp index 34de47b929ac..ae32c0f25b75 100644 --- a/libyul/YulStack.cpp +++ b/libyul/YulStack.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include #include @@ -405,7 +405,7 @@ Json YulStack::cfgJson() const keepLiteralAssignments ); std::unique_ptr liveness = std::make_unique(*controlFlow); - return ssa::json::exportControlFlow(*controlFlow, liveness.get()); + return ssa::io::json::exportControlFlow(*controlFlow, liveness.get()); }; std::function>)> exportCFGFromSubObjects; diff --git a/libyul/backends/evm/ssa/SSACFGJsonExporter.cpp b/libyul/backends/evm/ssa/io/JSONExporter.cpp similarity index 95% rename from libyul/backends/evm/ssa/SSACFGJsonExporter.cpp rename to libyul/backends/evm/ssa/io/JSONExporter.cpp index 9b03c13c95c1..df4e4d8148e8 100644 --- a/libyul/backends/evm/ssa/SSACFGJsonExporter.cpp +++ b/libyul/backends/evm/ssa/io/JSONExporter.cpp @@ -16,7 +16,7 @@ */ // SPDX-License-Identifier: GPL-3.0 -#include +#include #include @@ -31,7 +31,7 @@ using namespace solidity; using namespace solidity::yul; using namespace solidity::yul::ssa; -using namespace solidity::yul::ssa::json; +using namespace solidity::yul::ssa::io::json; namespace { @@ -134,8 +134,6 @@ Json exportBlock(SSACFG const& _cfg, SSACFG::BlockId _entryId, LivenessAnalysis Json blocksJson = Json::array(); util::BreadthFirstSearch bfs{{{_entryId}}}; bfs.run([&](SSACFG::BlockId _blockId, auto _addChild) { - auto const& block = _cfg.block(_blockId); - // Convert current block to JSON Json blockJson = toJson(_cfg, _blockId, _liveness); Json exitBlockJson = Json::object(); @@ -166,7 +164,7 @@ Json exportBlock(SSACFG const& _cfg, SSACFG::BlockId _entryId, LivenessAnalysis [&](SSACFG::BasicBlock::JumpTable const&) { yulAssert(false); } - }, block.exit); + }, _cfg.block(_blockId).exit); blockJson["exit"] = exitBlockJson; blocksJson.emplace_back(blockJson); }); @@ -188,7 +186,7 @@ Json exportFunction(SSACFG const& _cfg, LivenessAnalysis const* _liveness) } -Json json::exportControlFlow(ControlFlow const& _controlFlow, ControlFlowLiveness const* _liveness) +Json io::json::exportControlFlow(ControlFlow const& _controlFlow, ControlFlowLiveness const* _liveness) { if (_liveness) yulAssert(&_liveness->controlFlow.get() == &_controlFlow); diff --git a/libyul/backends/evm/ssa/SSACFGJsonExporter.h b/libyul/backends/evm/ssa/io/JSONExporter.h similarity index 95% rename from libyul/backends/evm/ssa/SSACFGJsonExporter.h rename to libyul/backends/evm/ssa/io/JSONExporter.h index 08f846fc5eda..5cca634aa339 100644 --- a/libyul/backends/evm/ssa/SSACFGJsonExporter.h +++ b/libyul/backends/evm/ssa/io/JSONExporter.h @@ -21,7 +21,7 @@ #include #include -namespace solidity::yul::ssa::json +namespace solidity::yul::ssa::io::json { Json exportControlFlow(ControlFlow const& _controlFlow, ControlFlowLiveness const* _liveness); From 05457c1f171abe383500d9646d2ee0a860d525d5 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 9 Feb 2026 13:36:34 +0100 Subject: [PATCH 59/73] Add SSA CFG Dot exporter base --- libyul/CMakeLists.txt | 2 + .../backends/evm/ssa/io/DotExporterBase.cpp | 220 ++++++++++++++++++ libyul/backends/evm/ssa/io/DotExporterBase.h | 93 ++++++++ 3 files changed, 315 insertions(+) create mode 100644 libyul/backends/evm/ssa/io/DotExporterBase.cpp create mode 100644 libyul/backends/evm/ssa/io/DotExporterBase.h diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index d425283b6969..d07b25a507f7 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -90,6 +90,8 @@ add_library(yul backends/evm/ssa/Stack.h backends/evm/ssa/StackShuffler.cpp backends/evm/ssa/StackShuffler.h + backends/evm/ssa/io/DotExporterBase.cpp + backends/evm/ssa/io/DotExporterBase.h backends/evm/ssa/io/JSONExporter.cpp backends/evm/ssa/io/JSONExporter.h backends/evm/ssa/traversal/ForwardTopologicalSort.cpp diff --git a/libyul/backends/evm/ssa/io/DotExporterBase.cpp b/libyul/backends/evm/ssa/io/DotExporterBase.cpp new file mode 100644 index 000000000000..23541422a57e --- /dev/null +++ b/libyul/backends/evm/ssa/io/DotExporterBase.cpp @@ -0,0 +1,220 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#include + +#include +#include + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtautological-compare" +#include +#pragma GCC diagnostic pop + +#include +#include + +using namespace solidity; +using namespace solidity::util; +using namespace solidity::yul; +using namespace solidity::yul::ssa; +using namespace solidity::yul::ssa::io; + +DotExporterBase::DotExporterBase(SSACFG const& _cfg, size_t const _functionIndex, RankDir const _rankDir): + m_cfg(_cfg), + m_functionIndex(_functionIndex), + m_rankDir(_rankDir) +{ +} + +std::string DotExporterBase::escapeId(std::string_view const _str) +{ + std::string result; + result.reserve(_str.size()); + for (auto const c: _str) + { + if (std::isalnum(static_cast(c)) || c == '_') + result += c; + else + result += '_'; + } + return result; +} + +std::string DotExporterBase::escapeLabel(std::string_view const _str) +{ + std::string result; + result.reserve(_str.size()); + for (auto const c: _str) + { + if (c == '"' || c == '\\') + result += '\\'; + result += c; + } + return result; +} + +std::string DotExporterBase::formatBlockHandle(SSACFG::BlockId _id) const +{ + return fmt::format("Block{}_{}", m_functionIndex, _id.value); +} + +std::string DotExporterBase::formatEdge(SSACFG::BlockId _source, SSACFG::BlockId _target, std::optional const& _exitPort) +{ + std::string const style = edgeStyle(_source, _target) == EdgeStyle::Dashed ? "dashed" : "solid"; + if (_exitPort) + return fmt::format("{}Exit:{} -> {} [style=\"{}\"];\n", formatBlockHandle(_source), *_exitPort, formatBlockHandle(_target), style); + else + return fmt::format("{}Exit -> {} [style=\"{}\"];\n", formatBlockHandle(_source), formatBlockHandle(_target), style); +} + +void DotExporterBase::writeBlock(std::ostream& _out, SSACFG::BlockId const _id) +{ + auto const& block = m_cfg.block(_id); + + auto const attributes = blockNodeAttributes(_id); + std::string attrStr; + for (auto const& [name, value]: attributes) + attrStr += fmt::format("{}={}, ", name, value); + _out << fmt::format("{} [{}label=\"", formatBlockHandle(_id), attrStr); + writeBlockLabel(_out, _id); + _out << "\"];\n"; + + std::visit(GenericVisitor{ + [&](SSACFG::BasicBlock::MainExit const&) + { + _out << fmt::format("{}Exit [label=\"MainExit\"];\n", formatBlockHandle(_id)); + _out << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); + }, + [&](SSACFG::BasicBlock::Jump const& _jump) + { + _out << fmt::format("{} -> {}Exit [arrowhead=none];\n", formatBlockHandle(_id), formatBlockHandle(_id)); + _out << fmt::format("{}Exit [label=\"Jump\" shape=oval];\n", formatBlockHandle(_id)); + _out << formatEdge(_id, _jump.target); + }, + [&](SSACFG::BasicBlock::ConditionalJump const& _conditionalJump) + { + _out << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); + _out << fmt::format( + "{}Exit [label=\"{{ If {} | {{ <0> Zero | <1> NonZero }}}}\" shape=Mrecord];\n", + formatBlockHandle(_id), _conditionalJump.condition.str(m_cfg) + ); + _out << formatEdge(_id, _conditionalJump.zero, "0"); + _out << formatEdge(_id, _conditionalJump.nonZero, "1"); + }, + [&](SSACFG::BasicBlock::JumpTable const& jt) + { + _out << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); + std::string options; + for (auto const& jumpCase: jt.cases) + { + if (!options.empty()) + options += " | "; + options += fmt::format("<{0}> {0}", formatNumber(jumpCase.first)); + } + if (!options.empty()) + options += " | "; + options += " default"; + _out << fmt::format("{}Exit [label=\"{{ JT | {{ {} }} }}\" shape=Mrecord];\n", formatBlockHandle(_id), options); + for (auto const& jumpCase: jt.cases) + _out << formatEdge(_id, jumpCase.second, formatNumber(jumpCase.first)); + _out << formatEdge(_id, jt.defaultCase, "default"); + }, + [&](SSACFG::BasicBlock::FunctionReturn const& fr) + { + auto const valueToString = [&](SSACFG::ValueId const& valueId) { return valueId.str(m_cfg); }; + _out << fmt::format("{}Exit [label=\"FunctionReturn[{}]\"];\n", + formatBlockHandle(_id), + fmt::join(fr.returnValues | ranges::views::transform(valueToString), ", ") + ); + _out << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); + }, + [&](SSACFG::BasicBlock::Terminated const&) + { + _out << fmt::format("{}Exit [label=\"Terminated\"];\n", formatBlockHandle(_id)); + _out << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); + } + }, block.exit); +} + +void DotExporterBase::traverse(std::ostream& _out, SSACFG::BlockId _entry) +{ + std::vector explored(m_cfg.numBlocks(), false); + explored[_entry.value] = true; + + std::deque toVisit{}; + toVisit.emplace_back(_entry); + + while (!toVisit.empty()) + { + auto const id = toVisit.front(); + toVisit.pop_front(); + writeBlock(_out, id); + m_cfg.block(id).forEachExit( + [&](SSACFG::BlockId const& _exitBlock) + { + if (!explored[_exitBlock.value]) + { + explored[_exitBlock.value] = true; + toVisit.emplace_back(_exitBlock); + } + } + ); + } +} + +std::string DotExporterBase::exportBlocks(SSACFG::BlockId _entry, bool _wrapInDigraph) +{ + std::ostringstream out; + if (_wrapInDigraph) + out << fmt::format("digraph SSACFG {{\nnodesep=0.7;\ngraph[fontname=\"DejaVu Sans\", rankdir={}]\nnode[shape=box,fontname=\"DejaVu Sans\"];\n\n", m_rankDir); + out << fmt::format("Entry [label=\"Entry\"];\n"); + out << fmt::format("Entry -> {};\n", formatBlockHandle(_entry)); + traverse(out, _entry); + if (_wrapInDigraph) + out << "}\n"; + return out.str(); +} + +std::string DotExporterBase::exportFunction(Scope::Function const& _function, bool _wrapInDigraph) +{ + std::ostringstream out; + if (_wrapInDigraph) + out << fmt::format("digraph SSACFG {{\nnodesep=0.7;\ngraph[fontname=\"DejaVu Sans\", rankdir={}]\nnode[shape=box,fontname=\"DejaVu Sans\"];\n\n", m_rankDir); + + static auto constexpr returnsTransform = [](auto const& functionReturnValue) { return escapeLabel(functionReturnValue.get().name.str()); }; + static auto constexpr argsTransform = [](auto const& arg) { return fmt::format("v{}", std::get<1>(arg).value()); }; + auto const entryHandle = fmt::format("FunctionEntry_{}_{}", escapeId(_function.name.str()), m_cfg.entry.value); + if (!m_cfg.returns.empty()) + out << fmt::format("{} [label=\"function {}:\n {} := {}({})\"];\n", + entryHandle, escapeLabel(_function.name.str()), + fmt::join(m_cfg.returns | ranges::views::transform(returnsTransform), ", "), + escapeLabel(_function.name.str()), + fmt::join(m_cfg.arguments | ranges::views::transform(argsTransform), ", ")); + else + out << fmt::format("{} [label=\"function {}:\n {}({})\"];\n", + entryHandle, escapeLabel(_function.name.str()), + escapeLabel(_function.name.str()), + fmt::join(m_cfg.arguments | ranges::views::transform(argsTransform), ", ")); + out << fmt::format("{} -> {};\n", entryHandle, formatBlockHandle(m_cfg.entry)); + traverse(out, m_cfg.entry); + + if (_wrapInDigraph) + out << "}\n"; + return out.str(); +} diff --git a/libyul/backends/evm/ssa/io/DotExporterBase.h b/libyul/backends/evm/ssa/io/DotExporterBase.h new file mode 100644 index 000000000000..f7fcdcda21af --- /dev/null +++ b/libyul/backends/evm/ssa/io/DotExporterBase.h @@ -0,0 +1,93 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include + +#include + +#include +#include +#include +#include + +namespace solidity::yul::ssa::io +{ + +/// Base class for exporting an SSACFG to Graphviz dot format. +/// Handles graph structure (BFS traversal, edges, exit nodes, entry nodes) and +/// delegates block content rendering to derived classes via writeBlockLabel(). +class DotExporterBase +{ +public: + enum class EdgeStyle { Solid, Dashed }; + enum class RankDir { TB, BT, LR, RL }; + + DotExporterBase(SSACFG const& _cfg, size_t _functionIndex, RankDir _rankDir = RankDir::LR); + virtual ~DotExporterBase() = default; + + std::string exportBlocks(SSACFG::BlockId _entry, bool _wrapInDigraph = true); + std::string exportFunction(Scope::Function const& _function, bool _wrapInDigraph = true); + +protected: + /// Override to write the content inside a block's dot label. + /// Everything between the opening `label="` and the closing `"` is the responsibility of this method. + virtual void writeBlockLabel(std::ostream& _out, SSACFG::BlockId _blockId) = 0; + + /// Override to provide extra node attributes (e.g., fillcolor). + virtual std::vector> blockNodeAttributes(SSACFG::BlockId) { return {}; } + + /// Override to customize edge style (e.g., dashed for back edges). + virtual EdgeStyle edgeStyle(SSACFG::BlockId, SSACFG::BlockId) { return EdgeStyle::Solid; } + + std::string formatBlockHandle(SSACFG::BlockId _id) const; + /// Escapes a string for use in dot node IDs (replaces non-alphanumeric characters with underscores). + static std::string escapeId(std::string_view _str); + /// Escapes a string for use inside dot label text (escapes quotes and backslashes). + static std::string escapeLabel(std::string_view _str); + + SSACFG const& m_cfg; + size_t m_functionIndex; + RankDir m_rankDir; + +private: + void writeBlock(std::ostream& _out, SSACFG::BlockId _id); + std::string formatEdge(SSACFG::BlockId _source, SSACFG::BlockId _target, std::optional const& _exitPort = std::nullopt); + void traverse(std::ostream& _out, SSACFG::BlockId _entry); +}; + +} + +template<> +struct fmt::formatter: fmt::formatter +{ + auto format(solidity::yul::ssa::io::DotExporterBase::RankDir _rankDir, fmt::format_context& _ctx) const + { + using RankDir = solidity::yul::ssa::io::DotExporterBase::RankDir; + std::string_view name; + switch (_rankDir) + { + case RankDir::TB: name = "TB"; break; + case RankDir::BT: name = "BT"; break; + case RankDir::LR: name = "LR"; break; + case RankDir::RL: name = "RL"; break; + } + return fmt::formatter::format(name, _ctx); + } +}; From e3c73c208717c11612b62f6ca5c137465bd23b9b Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 9 Feb 2026 13:37:02 +0100 Subject: [PATCH 60/73] Use Dot Exporter Base in `toDot` of SSACFG --- libyul/backends/evm/ssa/SSACFG.cpp | 319 +++++------------- .../libyul/yulSSAControlFlowGraph/complex.yul | 4 +- .../yulSSAControlFlowGraph/complex2.yul | 4 +- .../default_initialized_variable.yul | 4 +- .../yulSSAControlFlowGraph/function.yul | 4 +- test/libyul/yulSSAControlFlowGraph/if.yul | 4 +- .../yulSSAControlFlowGraph/if_const.yul | 4 +- .../yulSSAControlFlowGraph/nested_for.yul | 4 +- .../nested_function.yul | 4 +- test/libyul/yulSSAControlFlowGraph/switch.yul | 4 +- .../yulSSAControlFlowGraph/switch_const.yul | 4 +- 11 files changed, 109 insertions(+), 250 deletions(-) diff --git a/libyul/backends/evm/ssa/SSACFG.cpp b/libyul/backends/evm/ssa/SSACFG.cpp index a785c51aa276..24cc77091e07 100644 --- a/libyul/backends/evm/ssa/SSACFG.cpp +++ b/libyul/backends/evm/ssa/SSACFG.cpp @@ -19,6 +19,8 @@ #include #include +#include +#include #include #include @@ -28,8 +30,6 @@ #include #pragma GCC diagnostic pop -#include - #include using namespace solidity; @@ -39,256 +39,120 @@ using namespace solidity::yul::ssa; namespace { -class SSACFGPrinter + +std::string formatPhi(SSACFG const& _cfg, SSACFG::PhiValue const& _phiValue) +{ + auto const transform = [&](SSACFG::ValueId const& valueId) { return valueId.str(_cfg); }; + std::vector formattedArgs; + formattedArgs.reserve(_phiValue.arguments.size()); + for (auto const& [arg, entry]: ranges::zip_view(_phiValue.arguments | ranges::views::transform(transform), _cfg.block(_phiValue.block).entries)) + formattedArgs.push_back(fmt::format("Block {} => {}", entry.value, arg)); + if (!formattedArgs.empty()) + return fmt::format("φ(\\l\\\n\t{}\\l\\\n)", fmt::join(formattedArgs, ",\\l\\\n\t")); + else + return "φ()"; +} + +class SSACFGDotExporter: public io::DotExporterBase { public: - SSACFGPrinter(SSACFG const& _cfg, SSACFG::BlockId _blockId, LivenessAnalysis const* _liveness): - m_cfg(_cfg), m_functionIndex(0), m_liveness(_liveness) + SSACFGDotExporter(SSACFG const& _cfg, size_t _functionIndex, LivenessAnalysis const* _liveness): + DotExporterBase(_cfg, _functionIndex), + m_liveness(_liveness) { if (_liveness) m_junkAdmittingBlocks = std::make_unique(_cfg, _liveness->topologicalSort()); - printBlock(_blockId); - } - SSACFGPrinter(SSACFG const& _cfg, size_t _functionIndex, Scope::Function const& _function, LivenessAnalysis const* _liveness): - m_cfg(_cfg), m_functionIndex(_functionIndex), m_liveness(_liveness) - { - if (_liveness) - m_junkAdmittingBlocks = std::make_unique(_cfg, _liveness->topologicalSort()); - printFunction(_function); - } - friend std::ostream& operator<<(std::ostream& stream, SSACFGPrinter const& printer) { - stream << printer.m_result.str(); - return stream; } -private: - static std::string escape(std::string_view const str) +protected: + void writeBlockLabel(std::ostream& _out, SSACFG::BlockId _blockId) override { - using namespace std::literals; - static constexpr auto replacements = std::array{std::make_tuple('$', "_d_")}; - std::stringstream ss; - for (auto const c: str) + auto const& block = m_cfg.block(_blockId); + auto const valueToString = [&](SSACFG::ValueId const& valueId) { return valueId.str(m_cfg); }; + + if (m_liveness) { - auto const it = std::find_if(replacements.begin(), replacements.end(), [c](auto const& replacement) - { - return std::get<0>(replacement) == c; - }); - if (it != replacements.end()) - ss << std::get<1>(*it); - else - ss << c; + _out << fmt::format( + "\\\nBlock {}; ({}, max {})\\n", + _blockId.value, + m_liveness->topologicalSort().preOrderIndexOf(_blockId.value), + m_liveness->topologicalSort().maxSubtreePreOrderIndexOf(_blockId.value) + ); + _out << fmt::format( + "LiveIn: {}\\l\\\n", + fmt::join(m_liveness->liveIn(_blockId) | ranges::views::transform([&](auto const& liveIn) { return valueToString(SSACFG::ValueId{liveIn.first}) + fmt::format("[{}]", liveIn.second); }), ", ") + ); + _out << fmt::format( + "LiveOut: {}\\l\\n", + fmt::join(m_liveness->liveOut(_blockId) | ranges::views::transform([&](auto const& liveOut) { return valueToString(SSACFG::ValueId{liveOut.first}) + fmt::format("[{}]", liveOut.second); }), ", ") + ); + auto const usedVariables = m_liveness->used(_blockId); + _out << fmt::format( + "Used: {}\\l\\n", + fmt::join(usedVariables | ranges::views::transform([&](auto const& used) { return valueToString(SSACFG::ValueId{used.first}) + fmt::format("[{}]", used.second); }), ", ") + ); } - return ss.str(); - } - - std::string formatBlockHandle(SSACFG::BlockId const& _id) const - { - return fmt::format("Block{}_{}", m_functionIndex, _id.value); - } - - std::string formatEdge(SSACFG::BlockId const& _v, SSACFG::BlockId const& _w, std::optional const& _vPort = std::nullopt) - { - std::string const style = m_liveness && m_liveness->topologicalSort().backEdge(_v, _w) ? "dashed" : "solid"; - if (_vPort) - return fmt::format("{}Exit:{} -> {} [style=\"{}\"];\n", formatBlockHandle(_v), *_vPort, formatBlockHandle(_w), style); - else - return fmt::format("{}Exit -> {} [style=\"{}\"];\n", formatBlockHandle(_v), formatBlockHandle(_w), style); - } - - static std::string formatPhi(SSACFG const& _cfg, SSACFG::PhiValue const& _phiValue) - { - auto const transform = [&](SSACFG::ValueId const& valueId) { return valueId.str(_cfg); }; - std::vector formattedArgs; - formattedArgs.reserve(_phiValue.arguments.size()); - for (auto const& [arg, entry]: ranges::zip_view(_phiValue.arguments | ranges::views::transform(transform), _cfg.block(_phiValue.block).entries)) - formattedArgs.push_back(fmt::format("Block {} => {}", entry.value, arg)); - if (!formattedArgs.empty()) - return fmt::format("φ(\\l\\\n\t{}\\l\\\n)", fmt::join(formattedArgs, ",\\l\\\n\t")); else - return "φ()"; - } + _out << fmt::format("\\\nBlock {}\\n", _blockId.value); - void writeBlock(SSACFG::BlockId const& _id, SSACFG::BasicBlock const& _block) - { - auto const valueToString = [&](SSACFG::ValueId const& valueId) { return valueId.str(m_cfg); }; - bool entryBlock = _id.value == 0 && m_functionIndex == 0; - if (entryBlock) + for (auto const& phi: block.phis) { - m_result << fmt::format("Entry{} [label=\"Entry\"];\n", m_functionIndex); - m_result << fmt::format("Entry{} -> {};\n", m_functionIndex, formatBlockHandle(_id)); + auto const& phiInfo = m_cfg.phiInfo(phi); + _out << fmt::format("phi{} := {}\\l\\\n", phi.value(), formatPhi(m_cfg, phiInfo)); } + for (auto const& operation: block.operations) { - std::string revertPathInfo; - if (m_junkAdmittingBlocks) - revertPathInfo = m_junkAdmittingBlocks->allowsAdditionOfJunk(_id) ? "fillcolor=\"#FF746C\", style=filled, " : ""; - if (m_liveness) - { - m_result << fmt::format( - "{} [{}label=\"\\\nBlock {}; ({}, max {})\\n", - formatBlockHandle(_id), - revertPathInfo, - _id.value, - m_liveness->topologicalSort().preOrderIndexOf(_id.value), - m_liveness->topologicalSort().maxSubtreePreOrderIndexOf(_id.value) - ); - m_result << fmt::format( - "LiveIn: {}\\l\\\n", - fmt::join(m_liveness->liveIn(_id) | ranges::views::transform([&](auto const& liveIn) { return valueToString(SSACFG::ValueId{liveIn.first}) + fmt::format("[{}]", liveIn.second); }), ", ") - ); - m_result << fmt::format( - "LiveOut: {}\\l\\n", - fmt::join(m_liveness->liveOut(_id) | ranges::views::transform([&](auto const& liveOut) { return valueToString(SSACFG::ValueId{liveOut.first}) + fmt::format("[{}]", liveOut.second); }), ", ") - ); - auto const usedVariables = m_liveness->used(_id); - m_result << fmt::format( - "Used: {}\\l\\n", - fmt::join(usedVariables | ranges::views::transform([&](auto const& used) { return valueToString(SSACFG::ValueId{used.first}) + fmt::format("[{}]", used.second); }), ", ") - ); - } - else - m_result << fmt::format("{} [{}label=\"\\\nBlock {}\\n", formatBlockHandle(_id), revertPathInfo, _id.value); - - for (auto const& phi: _block.phis) - { - auto const& phiInfo = m_cfg.phiInfo(phi); - m_result << fmt::format("phi{} := {}\\l\\\n", phi.value(), formatPhi(m_cfg, phiInfo)); - } - for (auto const& operation: _block.operations) - { - std::string const label = std::visit(GenericVisitor{ - [&](SSACFG::Call const& _call) { - return _call.function.get().name.str(); - }, - [&](SSACFG::BuiltinCall const& _call) { - return _call.builtin.get().name; - }, - [&](SSACFG::LiteralAssignment const&) - { - yulAssert(operation.inputs.size() == 1); - return operation.inputs.back().str(m_cfg); - } - }, operation.kind); - if (!operation.outputs.empty()) - m_result << fmt::format( - "{} := ", - fmt::join(operation.outputs | ranges::views::transform(valueToString), ", ") - ); - if (std::holds_alternative(operation.kind)) - m_result << fmt::format( - "{}\\l\\\n", - escape(label) - ); - else - m_result << fmt::format( - "{}({})\\l\\\n", - escape(label), - fmt::join(operation.inputs | ranges::views::transform(valueToString), ", ") - ); - } - m_result << "\"];\n"; - std::visit(GenericVisitor{ - [&](SSACFG::BasicBlock::MainExit const&) - { - m_result << fmt::format("{}Exit [label=\"MainExit\"];\n", formatBlockHandle(_id)); - m_result << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); - }, - [&](SSACFG::BasicBlock::Jump const& _jump) - { - m_result << fmt::format("{} -> {}Exit [arrowhead=none];\n", formatBlockHandle(_id), formatBlockHandle(_id)); - m_result << fmt::format("{}Exit [label=\"Jump\" shape=oval];\n", formatBlockHandle(_id)); - m_result << formatEdge(_id, _jump.target); - }, - [&](SSACFG::BasicBlock::ConditionalJump const& _conditionalJump) - { - m_result << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); - m_result << fmt::format( - "{}Exit [label=\"{{ If {} | {{ <0> Zero | <1> NonZero }}}}\" shape=Mrecord];\n", - formatBlockHandle(_id), _conditionalJump.condition.str(m_cfg) - ); - m_result << formatEdge(_id, _conditionalJump.zero, "0"); - m_result << formatEdge(_id, _conditionalJump.nonZero, "1"); - }, - [&](SSACFG::BasicBlock::JumpTable const& jt) - { - m_result << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id)); - std::string options; - for (auto const& jumpCase: jt.cases) - { - if (!options.empty()) - options += " | "; - options += fmt::format("<{0}> {0}", formatNumber(jumpCase.first)); - } - if (!options.empty()) - options += " | "; - options += " default"; - m_result << fmt::format("{}Exit [label=\"{{ JT | {{ {} }} }}\" shape=Mrecord];\n", formatBlockHandle(_id), options); - for (auto const& jumpCase: jt.cases) - m_result << formatEdge(_id, jumpCase.second, formatNumber(jumpCase.first)); - m_result << formatEdge(_id, jt.defaultCase, "default"); + std::string const label = std::visit(GenericVisitor{ + [&](SSACFG::Call const& _call) { + return _call.function.get().name.str(); }, - [&](SSACFG::BasicBlock::FunctionReturn const& fr) - { - m_result << formatBlockHandle(_id) << "Exit [label=\"FunctionReturn[" - << fmt::format("{}", fmt::join(fr.returnValues | ranges::views::transform(valueToString), ", ")) - << "]\"];\n"; - m_result << formatBlockHandle(_id) << " -> " << formatBlockHandle(_id) << "Exit;\n"; + [&](SSACFG::BuiltinCall const& _call) { + return _call.builtin.get().name; }, - [&](SSACFG::BasicBlock::Terminated const&) + [&](SSACFG::LiteralAssignment const&) { - m_result << formatBlockHandle(_id) << "Exit [label=\"Terminated\"];\n"; - m_result << formatBlockHandle(_id) << " -> " << formatBlockHandle(_id) << "Exit;\n"; + yulAssert(operation.inputs.size() == 1); + return operation.inputs.back().str(m_cfg); } - }, _block.exit); + }, operation.kind); + if (!operation.outputs.empty()) + _out << fmt::format( + "{} := ", + fmt::join(operation.outputs | ranges::views::transform(valueToString), ", ") + ); + if (std::holds_alternative(operation.kind)) + _out << fmt::format( + "{}\\l\\\n", + escapeLabel(label) + ); + else + _out << fmt::format( + "{}({})\\l\\\n", + escapeLabel(label), + fmt::join(operation.inputs | ranges::views::transform(valueToString), ", ") + ); } } - void printBlock(SSACFG::BlockId const& _rootId) + std::vector> blockNodeAttributes(SSACFG::BlockId _blockId) override { - std::set explored{}; - explored.insert(_rootId); - - std::deque toVisit{}; - toVisit.emplace_back(_rootId); - - while (!toVisit.empty()) - { - auto const id = toVisit.front(); - toVisit.pop_front(); - auto const& block = m_cfg.block(id); - writeBlock(id, block); - block.forEachExit( - [&](SSACFG::BlockId const& _exitBlock) - { - if (explored.count(_exitBlock) == 0) - { - explored.insert(_exitBlock); - toVisit.emplace_back(_exitBlock); - } - } - ); - } + if (m_junkAdmittingBlocks && m_junkAdmittingBlocks->allowsAdditionOfJunk(_blockId)) + return {{"fillcolor", "\"#FF746C\""}, {"style", "filled"}}; + return {}; } - void printFunction(Scope::Function const& _fun) + EdgeStyle edgeStyle(SSACFG::BlockId _source, SSACFG::BlockId _target) override { - static auto constexpr returnsTransform = [](auto const& functionReturnValue) { return escape(functionReturnValue.get().name.str()); }; - static auto constexpr argsTransform = [](auto const& arg) { return fmt::format("v{}", std::get<1>(arg).value()); }; - m_result << "FunctionEntry_" << escape(_fun.name.str()) << "_" << m_cfg.entry.value << " [label=\""; - if (!m_cfg.returns.empty()) - m_result << fmt::format("function {0}:\n {1} := {0}({2})", escape(_fun.name.str()), fmt::join(m_cfg.returns | ranges::views::transform(returnsTransform), ", "), fmt::join(m_cfg.arguments | ranges::views::transform(argsTransform), ", ")); - else - m_result << fmt::format("function {0}:\n {0}({1})", escape(_fun.name.str()), fmt::join(m_cfg.arguments | ranges::views::transform(argsTransform), ", ")); - m_result << "\"];\n"; - m_result << "FunctionEntry_" << escape(_fun.name.str()) << "_" << m_cfg.entry.value << " -> Block" << m_functionIndex << "_" << m_cfg.entry.value << ";\n"; - printBlock(m_cfg.entry); + if (m_liveness && m_liveness->topologicalSort().backEdge(_source, _target)) + return EdgeStyle::Dashed; + return EdgeStyle::Solid; } - SSACFG const& m_cfg; - std::unique_ptr m_junkAdmittingBlocks; - size_t m_functionIndex; +private: LivenessAnalysis const* m_liveness; - std::stringstream m_result{}; + std::unique_ptr m_junkAdmittingBlocks; }; + } std::string SSACFG::ValueId::str(SSACFG const& _cfg) const @@ -312,14 +176,9 @@ std::string SSACFG::toDot( LivenessAnalysis const* _liveness ) const { - std::ostringstream output; - if (_includeDiGraphDefinition) - output << "digraph SSACFG {\nnodesep=0.7;\ngraph[fontname=\"DejaVu Sans\", rankdir=LR]\nnode[shape=box,fontname=\"DejaVu Sans\"];\n\n"; + SSACFGDotExporter exporter(*this, _functionIndex.value_or(function ? 1 : 0), _liveness); if (function) - output << SSACFGPrinter(*this, _functionIndex ? *_functionIndex : static_cast(1), *function, _liveness); + return exporter.exportFunction(*function, _includeDiGraphDefinition); else - output << SSACFGPrinter(*this, entry, _liveness); - if (_includeDiGraphDefinition) - output << "}\n"; - return output.str(); + return exporter.exportBlocks(entry, _includeDiGraphDefinition); } diff --git a/test/libyul/yulSSAControlFlowGraph/complex.yul b/test/libyul/yulSSAControlFlowGraph/complex.yul index 24ab7af125cf..4f16122e3179 100644 --- a/test/libyul/yulSSAControlFlowGraph/complex.yul +++ b/test/libyul/yulSSAControlFlowGraph/complex.yul @@ -49,8 +49,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [fillcolor="#FF746C", style=filled, label="\ // Block 0; (0, max 0)\nLiveIn: \l\ // LiveOut: \l\nUsed: \l\nv0 := f(0x02, 0x01)\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/complex2.yul b/test/libyul/yulSSAControlFlowGraph/complex2.yul index 9910d8356b89..d82c400e8d7e 100644 --- a/test/libyul/yulSSAControlFlowGraph/complex2.yul +++ b/test/libyul/yulSSAControlFlowGraph/complex2.yul @@ -56,8 +56,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [fillcolor="#FF746C", style=filled, label="\ // Block 0; (0, max 0)\nLiveIn: \l\ // LiveOut: \l\nUsed: \l\nsstore(0x01, 0x01)\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/default_initialized_variable.yul b/test/libyul/yulSSAControlFlowGraph/default_initialized_variable.yul index 14a80dadc755..45893e8ac276 100644 --- a/test/libyul/yulSSAControlFlowGraph/default_initialized_variable.yul +++ b/test/libyul/yulSSAControlFlowGraph/default_initialized_variable.yul @@ -11,8 +11,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [label="\ // Block 0; (0, max 2)\nLiveIn: \l\ // LiveOut: v0[1]\l\nUsed: \l\nv0 := 0x00\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/function.yul b/test/libyul/yulSSAControlFlowGraph/function.yul index f5090b82655c..e2140d31690c 100644 --- a/test/libyul/yulSSAControlFlowGraph/function.yul +++ b/test/libyul/yulSSAControlFlowGraph/function.yul @@ -24,8 +24,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [fillcolor="#FF746C", style=filled, label="\ // Block 0; (0, max 0)\nLiveIn: \l\ // LiveOut: \l\nUsed: \l\nv0, v1 := i()\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/if.yul b/test/libyul/yulSSAControlFlowGraph/if.yul index 540947e18037..f884d3348606 100644 --- a/test/libyul/yulSSAControlFlowGraph/if.yul +++ b/test/libyul/yulSSAControlFlowGraph/if.yul @@ -12,8 +12,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [label="\ // Block 0; (0, max 2)\nLiveIn: \l\ // LiveOut: v0[1]\l\nUsed: \l\nv0 := calldataload(0x03)\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/if_const.yul b/test/libyul/yulSSAControlFlowGraph/if_const.yul index d8be1eaf2f99..f8bab3f48129 100644 --- a/test/libyul/yulSSAControlFlowGraph/if_const.yul +++ b/test/libyul/yulSSAControlFlowGraph/if_const.yul @@ -17,8 +17,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [fillcolor="#FF746C", style=filled, label="\ // Block 0; (0, max 0)\nLiveIn: \l\ // LiveOut: \l\nUsed: \l\nv0 := calldataload(0x03)\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/nested_for.yul b/test/libyul/yulSSAControlFlowGraph/nested_for.yul index e9e57514006a..55edb2ea67f4 100644 --- a/test/libyul/yulSSAControlFlowGraph/nested_for.yul +++ b/test/libyul/yulSSAControlFlowGraph/nested_for.yul @@ -23,8 +23,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [fillcolor="#FF746C", style=filled, label="\ // Block 0; (0, max 24)\nLiveIn: \l\ // LiveOut: v0[1]\l\nUsed: \l\nv0 := 0x00\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/nested_function.yul b/test/libyul/yulSSAControlFlowGraph/nested_function.yul index 2ae7f5522ba4..876768d66597 100644 --- a/test/libyul/yulSSAControlFlowGraph/nested_function.yul +++ b/test/libyul/yulSSAControlFlowGraph/nested_function.yul @@ -35,8 +35,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [fillcolor="#FF746C", style=filled, label="\ // Block 0; (0, max 0)\nLiveIn: \l\ // LiveOut: \l\nUsed: \l\n"]; diff --git a/test/libyul/yulSSAControlFlowGraph/switch.yul b/test/libyul/yulSSAControlFlowGraph/switch.yul index 56e50d562985..3114bbca36d0 100644 --- a/test/libyul/yulSSAControlFlowGraph/switch.yul +++ b/test/libyul/yulSSAControlFlowGraph/switch.yul @@ -19,8 +19,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [label="\ // Block 0; (0, max 5)\nLiveIn: \l\ // LiveOut: v1[1]\l\nUsed: \l\nv0 := calldataload(0x03)\l\ diff --git a/test/libyul/yulSSAControlFlowGraph/switch_const.yul b/test/libyul/yulSSAControlFlowGraph/switch_const.yul index 559061195a8f..56116eb3b151 100644 --- a/test/libyul/yulSSAControlFlowGraph/switch_const.yul +++ b/test/libyul/yulSSAControlFlowGraph/switch_const.yul @@ -41,8 +41,8 @@ // graph[fontname="DejaVu Sans"] // node[shape=box,fontname="DejaVu Sans"]; // -// Entry0 [label="Entry"]; -// Entry0 -> Block0_0; +// Entry [label="Entry"]; +// Entry -> Block0_0; // Block0_0 [fillcolor="#FF746C", style=filled, label="\ // Block 0; (0, max 0)\nLiveIn: \l\ // LiveOut: \l\nUsed: \l\nv0 := calldataload(0x03)\l\ From 025600fa4517bef01ed9e972f38137ff9dd5e38b Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Wed, 4 Feb 2026 13:56:08 +0100 Subject: [PATCH 61/73] Add phi inverse function for ssa-based cfgs --- libyul/CMakeLists.txt | 2 ++ libyul/backends/evm/ssa/PhiInverse.cpp | 46 ++++++++++++++++++++++++++ libyul/backends/evm/ssa/PhiInverse.h | 46 ++++++++++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 libyul/backends/evm/ssa/PhiInverse.cpp create mode 100644 libyul/backends/evm/ssa/PhiInverse.h diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index d07b25a507f7..2c0f6d4465d0 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -80,6 +80,8 @@ add_library(yul backends/evm/ssa/JunkAdmittingBlocksFinder.h backends/evm/ssa/LivenessAnalysis.cpp backends/evm/ssa/LivenessAnalysis.h + backends/evm/ssa/PhiInverse.cpp + backends/evm/ssa/PhiInverse.h backends/evm/ssa/SSACFGLoopNestingForest.cpp backends/evm/ssa/SSACFGLoopNestingForest.h backends/evm/ssa/SSACFG.cpp diff --git a/libyul/backends/evm/ssa/PhiInverse.cpp b/libyul/backends/evm/ssa/PhiInverse.cpp new file mode 100644 index 000000000000..c88b132adef6 --- /dev/null +++ b/libyul/backends/evm/ssa/PhiInverse.cpp @@ -0,0 +1,46 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#include + +using namespace solidity::yul::ssa; + +PhiInverse::PhiInverse(SSACFG const& _cfg, SSACFG::BlockId const& _from, SSACFG::BlockId const& _to) +{ + auto const argIndex = _cfg.phiArgumentIndex(_from, _to); + for (auto const& phiId: _cfg.block(_to).phis) + { + auto const& phiInfo = _cfg.phiInfo(phiId); + m_phiToPreImage[phiId] = phiInfo.arguments[argIndex]; + } +} + +bool PhiInverse::noOp() const +{ + return m_phiToPreImage.empty(); +} + +SSACFG::ValueId PhiInverse::operator()(SSACFG::ValueId _valueId) const +{ + return util::valueOrDefault(m_phiToPreImage, _valueId, _valueId); +} + +std::map const& PhiInverse::data() const +{ + return m_phiToPreImage; +} diff --git a/libyul/backends/evm/ssa/PhiInverse.h b/libyul/backends/evm/ssa/PhiInverse.h new file mode 100644 index 000000000000..3f29aae46806 --- /dev/null +++ b/libyul/backends/evm/ssa/PhiInverse.h @@ -0,0 +1,46 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include + +#include + +namespace solidity::yul::ssa +{ + +/// If Block `_from` -> Block `_to` and `_to` has phi functions `v_k := phi(..., _from => v_i, ...)`, this transform +/// pulls values `v_k` back to `v_i`. +class PhiInverse +{ +public: + PhiInverse() = default; + PhiInverse(SSACFG const& _cfg, SSACFG::BlockId const& _from, SSACFG::BlockId const& _to); + + /// whether the transform is guaranteed to be a no-op, ie, there is no phi function in `_to` + bool noOp() const; + SSACFG::ValueId operator()(SSACFG::ValueId _valueId) const; + + std::map const& data() const; + +private: + std::map m_phiToPreImage = {}; +}; + +} From b3a7948f07fec360c9841ee2237fe36823a23caa Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Wed, 4 Feb 2026 13:56:29 +0100 Subject: [PATCH 62/73] ssa-cfg stack abstraction can also declare junk based on offsets --- libyul/backends/evm/ssa/Stack.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libyul/backends/evm/ssa/Stack.h b/libyul/backends/evm/ssa/Stack.h index 95ff377e7db4..834e21078da7 100644 --- a/libyul/backends/evm/ssa/Stack.h +++ b/libyul/backends/evm/ssa/Stack.h @@ -250,7 +250,8 @@ class Stack bool swapReachable(Offset const& _offset) const noexcept { return swapReachable(offsetToDepth(_offset)); } bool swapReachable(Depth const& _depth) const noexcept { return _depth < size() && 1 <= _depth.value && _depth.value <= reachableStackDepth; } - void declareJunk(Depth const& _depth) { (*m_data)[depthToOffset(_depth).value] = Slot::makeJunk(); } + void declareJunk(Offset const& _offset) { (*m_data)[_offset.value] = Slot::makeJunk(); } + void declareJunk(Depth const& _depth) { declareJunk(depthToOffset(_depth)); } Slot const& slot(Depth const& _depth) const { return (*m_data)[depthToOffset(_depth).value]; } Slot const& slot(Offset const& _offset) const { return slot(offsetToDepth(_offset)); } From 746871abd44bbd8cf79882749f56b0d150386ee9 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Wed, 4 Feb 2026 13:57:07 +0100 Subject: [PATCH 63/73] Define what constitutes a stack layout for SSA-CFGs --- libyul/CMakeLists.txt | 1 + libyul/backends/evm/ssa/StackLayout.h | 60 +++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 libyul/backends/evm/ssa/StackLayout.h diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index 2c0f6d4465d0..893b32e94d6b 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -90,6 +90,7 @@ add_library(yul backends/evm/ssa/SSACFGBuilder.h backends/evm/ssa/Stack.cpp backends/evm/ssa/Stack.h + backends/evm/ssa/StackLayout.h backends/evm/ssa/StackShuffler.cpp backends/evm/ssa/StackShuffler.h backends/evm/ssa/io/DotExporterBase.cpp diff --git a/libyul/backends/evm/ssa/StackLayout.h b/libyul/backends/evm/ssa/StackLayout.h new file mode 100644 index 000000000000..d0cd819726d1 --- /dev/null +++ b/libyul/backends/evm/ssa/StackLayout.h @@ -0,0 +1,60 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include + +#include + +namespace solidity::yul::ssa +{ + +struct BlockLayout +{ + // stack layout required to enter the block + StackData stackIn; + // stack layout required to execute the i-th operation in the block + std::vector operationIn; + // stack after the block was executed + StackData stackOut; +}; + +/// For each (reachable) block in the SSACFG one block layout +class SSACFGStackLayout +{ +public: + SSACFGStackLayout(std::size_t const _numBlocks): m_blockLayouts(_numBlocks) {} + + std::optional& operator[](SSACFG::BlockId const& _blockId) + { + yulAssert(_blockId.hasValue() && _blockId.value < m_blockLayouts.size()); + return m_blockLayouts[_blockId.value]; + } + + std::optional const& operator[](SSACFG::BlockId const& _blockId) const + { + yulAssert(_blockId.hasValue() && _blockId.value < m_blockLayouts.size()); + return m_blockLayouts[_blockId.value]; + } + +private: + std::vector> m_blockLayouts; +}; + +} From d2de781babf0c32a6a24f46d4296b8ba558907f5 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Wed, 4 Feb 2026 13:57:27 +0100 Subject: [PATCH 64/73] Add SSA-CFG stack layout generator --- libyul/CMakeLists.txt | 2 + .../backends/evm/ssa/StackLayoutGenerator.cpp | 311 ++++++++++++++++++ .../backends/evm/ssa/StackLayoutGenerator.h | 51 +++ 3 files changed, 364 insertions(+) create mode 100644 libyul/backends/evm/ssa/StackLayoutGenerator.cpp create mode 100644 libyul/backends/evm/ssa/StackLayoutGenerator.h diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index 893b32e94d6b..dcc0f923a0d3 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -91,6 +91,8 @@ add_library(yul backends/evm/ssa/Stack.cpp backends/evm/ssa/Stack.h backends/evm/ssa/StackLayout.h + backends/evm/ssa/StackLayoutGenerator.cpp + backends/evm/ssa/StackLayoutGenerator.h backends/evm/ssa/StackShuffler.cpp backends/evm/ssa/StackShuffler.h backends/evm/ssa/io/DotExporterBase.cpp diff --git a/libyul/backends/evm/ssa/StackLayoutGenerator.cpp b/libyul/backends/evm/ssa/StackLayoutGenerator.cpp new file mode 100644 index 000000000000..04abd8b64466 --- /dev/null +++ b/libyul/backends/evm/ssa/StackLayoutGenerator.cpp @@ -0,0 +1,311 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +using namespace solidity::yul::ssa; + +namespace +{ +void handlePhiFunctions(StackData& _stackData, PhiInverse const& _phiInverse, LivenessAnalysis::LivenessData const& _liveness) +{ + // add any phi function values here that are not already contained in the stack + for (auto const& [phi, preImage]: _phiInverse.data()) + { + auto reversedStackData = _stackData | ranges::views::reverse; + auto it = ranges::find(reversedStackData, StackSlot::makeValueID(preImage)); + if (_liveness.contains(preImage)) + { + // Both the phi function and the preimage are part of the live-in set. + // If the preimage occurs more than once on the stack, one occurrence is + // symbolically replaced by the phi function; otherwise, we push the phi value. + if (ranges::count(_stackData, StackSlot::makeValueID(preImage)) > 1) + *it = StackSlot::makeValueID(phi); + else + _stackData.emplace_back(StackSlot::makeValueID(phi)); + } + else + { + // replace all occurrences of the preimage with the phi value + ranges::replace(_stackData, StackSlot::makeValueID(preImage), StackSlot::makeValueID(phi)); + // if it's not contained, push it (could be derived from a literal) + if (it == ranges::end(reversedStackData)) + _stackData.emplace_back(StackSlot::makeValueID(phi)); + } + } +} + +using StackType = Stack; + +void declareJunk(StackType& _stack, LivenessAnalysis::LivenessData const& _live) +{ + for (StackOffset offset{0}; offset < _stack.size(); ++offset.value) + { + auto const& slot = _stack[offset]; + if (slot.isValueID() && !_live.contains(slot.valueID())) + _stack.declareJunk(offset); + } +} + +} + +SSACFGStackLayout StackLayoutGenerator::generate(LivenessAnalysis const& _liveness, CallSites const& _callSites) +{ + return StackLayoutGenerator(_liveness, _callSites).m_resultLayout; +} + +StackLayoutGenerator::StackLayoutGenerator(LivenessAnalysis const& _liveness, CallSites const& _callSites): + m_cfg(_liveness.cfg()), + m_liveness(_liveness), + m_callSites(_callSites), + m_junkAdmittingBlocksFinder(std::make_unique(_liveness.cfg(), _liveness.topologicalSort())), + m_resultLayout(m_cfg.numBlocks()) +{ + // traverse the cfg layer-wise using Kahn's algorithm: + // if a block is visited, the predecessors of that block have already their exit layouts defined + // with minor exceptions when dealing with back-edges + { + // Future optimization: it might be beneficial to revisit the loop heads (back edge targets) after the first iteration + std::vector inDegreesIgnoringBackedges(m_cfg.numBlocks(), 0); + + for (SSACFG::BlockId id{0}; id.value < m_cfg.numBlocks(); ++id.value) + for (auto const& entry: m_cfg.block(id).entries) + if (!m_liveness.topologicalSort().backEdge(entry, id)) + inDegreesIgnoringBackedges[id.value] += 1; + + std::queue traversalQueue; + traversalQueue.push(m_cfg.entry); + + std::size_t numVisited = 0; + while (!traversalQueue.empty()) + { + auto currentBlockId = traversalQueue.front(); + traversalQueue.pop(); + + visitBlock(currentBlockId); + + m_cfg.block(currentBlockId).forEachExit([&](SSACFG::BlockId const& _exit){ + if (--inDegreesIgnoringBackedges[_exit.value] == 0) + traversalQueue.push(_exit); + }); + ++numVisited; + } + yulAssert(numVisited == m_liveness.topologicalSort().preOrder().size()); + } +} + +void StackLayoutGenerator::defineStackIn(SSACFG::BlockId const& _blockId) +{ + // we already have an input layout defined, return + if (m_resultLayout[_blockId]) + return; + BlockLayout blockLayout{}; + + if (_blockId == m_cfg.entry) + { + if (m_cfg.function) + blockLayout.stackIn = + m_cfg.arguments | + ranges::views::reverse | + ranges::views::transform([](auto&& _variableAndValueId) -> Slot { return Slot::makeValueID(std::get<1>(_variableAndValueId)); }) | + ranges::to; + m_resultLayout[_blockId] = blockLayout; + return; + } + + auto const& block = m_cfg.block(_blockId); + + std::vector> parentExits; + for (auto const& entry: block.entries) + if (m_resultLayout[entry]) + parentExits.emplace_back(entry, &m_resultLayout[entry]->stackOut); + + yulAssert(!parentExits.empty(), fmt::format("None of the parents of block {} were generated", _blockId)); + + if (block.entries.size() == 1) + { + // pass through + yulAssert(parentExits.size() == 1); + blockLayout.stackIn = *parentExits[0].second; + + if (!block.phis.empty()) + handlePhiFunctions(blockLayout.stackIn, PhiInverse(m_cfg, parentExits[0].first, _blockId), m_liveness.liveIn(_blockId)); + } + else + { + // we have more than one entry and need to unify or at the very least apply phi fct. + auto const& liveIn = m_liveness.liveIn(_blockId); + std::vector cumulativeCosts(parentExits.size(), std::numeric_limits::max()); + for (std::size_t i = 0; i < parentExits.size(); ++i) + { + if (!parentExits[i].second) + continue; + std::size_t cumulativeCost = 0; + auto referenceStackIn = *parentExits[i].second; + { + StackType stack(referenceStackIn, {}); + declareJunk(stack, liveIn); + } + handlePhiFunctions(referenceStackIn, PhiInverse(m_cfg, parentExits[i].first, _blockId), liveIn); + for (std::size_t j = 0; j < parentExits.size(); ++j) + { + if (j != i) + { + if (parentExits[j].second != nullptr) + { + auto otherStackIn = *parentExits[j].second; + StackType stack(otherStackIn, {}); + StackShuffler::shuffle( + stack, + stackPreImage(referenceStackIn, PhiInverse(m_cfg, parentExits[j].first, _blockId)), + {}, + referenceStackIn.size() + ); + cumulativeCost += stack.callbacks().numOps; + } + } + } + cumulativeCosts[i] = cumulativeCost; + } + auto const argMin = static_cast( + std::distance(cumulativeCosts.begin(), ranges::min_element(cumulativeCosts)) + ); + yulAssert(parentExits[argMin].second); + blockLayout.stackIn = *parentExits[argMin].second; + StackType stack(blockLayout.stackIn, {}); + declareJunk(stack, liveIn); + handlePhiFunctions(blockLayout.stackIn, PhiInverse(m_cfg, parentExits[argMin].first, _blockId), liveIn); + } + m_resultLayout[_blockId] = blockLayout; +} + +void StackLayoutGenerator::visitBlock(SSACFG::BlockId const& _blockId) +{ + defineStackIn(_blockId); + yulAssert(m_resultLayout[_blockId]); + BlockLayout& blockLayout = *m_resultLayout[_blockId]; + + SSACFG::BasicBlock const& block = m_cfg.block(_blockId); + + StackData currentStackData = blockLayout.stackIn; + StackType stack(currentStackData, {}); + bool const junkCanBeAdded = m_junkAdmittingBlocksFinder->allowsAdditionOfJunk(_blockId); + + auto const& operationsLiveOut = m_liveness.operationsLiveOut(_blockId); + blockLayout.operationIn.reserve(block.operations.size()); + for (std::size_t operationIndex = 0; operationIndex < block.operations.size(); ++operationIndex) + { + SSACFG::Operation const& operation = block.operations[operationIndex]; + LivenessAnalysis::LivenessData opLiveOut = operationsLiveOut[operationIndex]; + auto opLiveOutWithoutOutputs = opLiveOut; + for (auto const& output: operation.outputs) + opLiveOutWithoutOutputs.erase(output); + + std::vector requiredStackTop; + if (auto const* call = std::get_if(&operation.kind)) + if (call->canContinue) + { + auto const callSiteID = m_callSites.callSiteID(&call->call.get()); + yulAssert(callSiteID.has_value()); + requiredStackTop.emplace_back(Slot::makeFunctionCallReturnLabel(*callSiteID)); + } + requiredStackTop += operation.inputs | ranges::views::transform(Slot::makeValueID); + + for (StackType::Depth depth{0}; depth < stack.size(); ++depth.value) + if ( + stack.slot(depth).isValueID() && + !opLiveOutWithoutOutputs.contains(stack.slot(depth).valueID()) && + ranges::find(requiredStackTop, stack.slot(depth)) == ranges::end(requiredStackTop) + ) + stack.declareJunk(depth); + + std::size_t const targetSize = findOptimalTargetSize(stack.data(), requiredStackTop, opLiveOutWithoutOutputs, junkCanBeAdded); + StackShuffler::shuffle( + stack, + requiredStackTop, + opLiveOutWithoutOutputs, + targetSize + ); + + blockLayout.operationIn.push_back(currentStackData); + for (std::size_t i = 0; i < requiredStackTop.size(); ++i) + stack.pop(); + for (auto const& val: operation.outputs) + stack.push(Slot::makeValueID(val)); + } + + if (auto const* cjump = std::get_if(&block.exit)) + { + auto const& zeroLiveIn = m_liveness.liveIn(cjump->zero); + auto const& blockLiveOut = m_liveness.liveOut(_blockId); + + // check if we have to do anything (dup the condition, bring it to the top etc) + bool const conditionSlotAlreadyFinal = + !blockLiveOut.contains(cjump->condition) && // if our live out does not contain the condition (ie we dont have to dup it) + !stack.empty() && // our stack is not empty + stack.top().isValueID() && stack.top().valueID() == cjump->condition; // and the condition is already on top + if (!conditionSlotAlreadyFinal) + { + auto const condition = Slot::makeValueID(cjump->condition); + auto const targetSize = findOptimalTargetSize(stack.data(), {condition}, blockLiveOut, false); + StackShuffler::shuffle( + stack, {condition}, blockLiveOut, targetSize + ); + } + + yulAssert(!stack.empty() && stack.top().isValueID() && stack.top().valueID() == cjump->condition); + yulAssert(m_cfg.block(cjump->nonZero).phis.empty()); + + // define zero and non-zero stack in layouts + { + std::optional& nonZeroLayout = m_resultLayout[cjump->nonZero]; + yulAssert(!nonZeroLayout, "There should be no way to reach this block other than by going through the parent."); + nonZeroLayout = BlockLayout{}; + nonZeroLayout->stackIn = currentStackData; + // Remove condition; consumed by JUMPI + nonZeroLayout->stackIn.pop_back(); + + if ( + std::optional& zeroLayout = m_resultLayout[cjump->zero]; + !zeroLayout + ) + { + // same as nonzero stack in initially + zeroLayout = nonZeroLayout; + handlePhiFunctions(zeroLayout->stackIn, PhiInverse(m_cfg, _blockId, cjump->zero), zeroLiveIn); + StackType zeroStack(zeroLayout->stackIn, {}); + declareJunk(zeroStack, zeroLiveIn); + } + } + } + + blockLayout.stackOut = currentStackData; +} diff --git a/libyul/backends/evm/ssa/StackLayoutGenerator.h b/libyul/backends/evm/ssa/StackLayoutGenerator.h new file mode 100644 index 000000000000..c9d45c72a2b8 --- /dev/null +++ b/libyul/backends/evm/ssa/StackLayoutGenerator.h @@ -0,0 +1,51 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include +#include + +#include + +namespace solidity::yul::ssa +{ + +class JunkAdmittingBlocksFinder; + +class StackLayoutGenerator +{ +public: + using Slot = StackSlot; + static SSACFGStackLayout generate(LivenessAnalysis const& _liveness, CallSites const& _callSites); + +private: + explicit StackLayoutGenerator(LivenessAnalysis const& _liveness, CallSites const& _callSites); + + void defineStackIn(SSACFG::BlockId const& _blockId); + void visitBlock(SSACFG::BlockId const& _blockId); + + SSACFG const& m_cfg; + LivenessAnalysis const& m_liveness; + CallSites const& m_callSites; + + std::unique_ptr m_junkAdmittingBlocksFinder; + SSACFGStackLayout m_resultLayout; +}; + +} From 22b1b120be84e072c63e380d0b442c18000b0efd Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Wed, 4 Feb 2026 22:47:46 +0100 Subject: [PATCH 65/73] Add SSA-CFG StackUtils --- libyul/CMakeLists.txt | 2 + libyul/backends/evm/ssa/StackUtils.cpp | 143 +++++++++++++++++++++++++ libyul/backends/evm/ssa/StackUtils.h | 43 ++++++++ 3 files changed, 188 insertions(+) create mode 100644 libyul/backends/evm/ssa/StackUtils.cpp create mode 100644 libyul/backends/evm/ssa/StackUtils.h diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index dcc0f923a0d3..d52dbba0dbb5 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -95,6 +95,8 @@ add_library(yul backends/evm/ssa/StackLayoutGenerator.h backends/evm/ssa/StackShuffler.cpp backends/evm/ssa/StackShuffler.h + backends/evm/ssa/StackUtils.cpp + backends/evm/ssa/StackUtils.h backends/evm/ssa/io/DotExporterBase.cpp backends/evm/ssa/io/DotExporterBase.h backends/evm/ssa/io/JSONExporter.cpp diff --git a/libyul/backends/evm/ssa/StackUtils.cpp b/libyul/backends/evm/ssa/StackUtils.cpp new file mode 100644 index 000000000000..3f2d28423822 --- /dev/null +++ b/libyul/backends/evm/ssa/StackUtils.cpp @@ -0,0 +1,143 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#include + +#include + +#include + +#include + +using namespace solidity::yul::ssa; + +StackData solidity::yul::ssa::stackPreImage(StackData _stack, PhiInverse const& _phiInverse) +{ + if (!_phiInverse.noOp()) + for (auto& slot: _stack) + if (slot.isValueID()) + slot = StackSlot::makeValueID(_phiInverse(slot.valueID())); + return _stack; +} + +std::size_t solidity::yul::ssa::findOptimalTargetSize +( + StackData const& _stackData, + StackData const& _targetArgs, + LivenessAnalysis::LivenessData const& _targetLiveOut, + bool const _canIntroduceJunk +) +{ + std::size_t const minSize = _targetLiveOut.size() + _targetArgs.size(); + boost::container::flat_map deficit; + for (auto const& v: _targetLiveOut | ranges::views::keys) + deficit[StackSlot::makeValueID(v)]++; + for (auto const& arg: _targetArgs) + deficit[arg]++; + for (auto const& slot: _stackData) + if (auto it = deficit.find(slot); it != deficit.end()) + it->second = it->second > 0 ? it->second - 1 : 0; + + std::size_t const pivot = _canIntroduceJunk ? _stackData.size() + _targetArgs.size() : _stackData.size() + ranges::accumulate(deficit | ranges::views::values, 0u); + std::size_t const startSize = std::max(pivot, minSize); + static std::size_t constexpr maxUpwardExpansion = 32; + + StackData data; + data.reserve(startSize + maxUpwardExpansion); + auto const evaluateCost = [&](std::size_t const _targetSize) -> std::size_t + { + data = _stackData; + Stack countOpsStack(data, {}); + StackShuffler::shuffle(countOpsStack, _targetArgs, _targetLiveOut, _targetSize); + yulAssert(countOpsStack.size() == _targetSize); + return countOpsStack.callbacks().numOps; + }; + + std::size_t bestCost = evaluateCost(startSize); + auto result = startSize; + + // On non-reverting paths, only search downward from pivot to avoid growing the stack. + // On reverting paths, search in both directions since stack cleanup doesn't matter. + static std::size_t constexpr stopAfter = 3; + std::size_t consecutiveIncreases = 0; + // search downward + { + std::size_t size = startSize; + while (size > minSize) + { + --size; + auto const cost = evaluateCost(size); + if (cost < bestCost) + { + bestCost = cost; + result = size; + consecutiveIncreases = 0; + } + else if (++consecutiveIncreases >= stopAfter) + break; + } + } + // search upward (only on reverting paths) + if (_canIntroduceJunk) + { + consecutiveIncreases = 0; + for (std::size_t size = startSize + 1; size <= startSize + maxUpwardExpansion; ++size) + { + auto const cost = evaluateCost(size); + if (cost < bestCost) + { + bestCost = cost; + result = size; + consecutiveIncreases = 0; + } + else if (++consecutiveIncreases >= stopAfter) + break; + } + } + return result; +} + +CallSites solidity::yul::ssa::gatherCallSites(SSACFG const& _cfg) +{ + CallSites result; + std::vector visited(_cfg.numBlocks(), false); + visited[_cfg.entry.value] = true; + std::vector toVisit; + toVisit.reserve(_cfg.numBlocks()); + toVisit.push_back(_cfg.entry); + + while (!toVisit.empty()) + { + auto const blockId = toVisit.back(); + toVisit.pop_back(); + auto const& block = _cfg.block(blockId); + block.forEachExit([&toVisit, &visited](SSACFG::BlockId const& _exitBlockId){ + if (!visited[_exitBlockId.value]) + { + visited[_exitBlockId.value] = true; + toVisit.push_back(_exitBlockId); + } + }); + + for (auto const& operation: block.operations) + if (auto const* call = std::get_if(&operation.kind)) + if (call->canContinue) + result.addCallSite(&call->call.get()); + } + return result; +} diff --git a/libyul/backends/evm/ssa/StackUtils.h b/libyul/backends/evm/ssa/StackUtils.h new file mode 100644 index 000000000000..6f5e991a09f2 --- /dev/null +++ b/libyul/backends/evm/ssa/StackUtils.h @@ -0,0 +1,43 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include +#include + +namespace solidity::yul::ssa +{ + +struct CountingInstructionsCallbacks +{ + std::size_t numOps = 0; + void swap(std::size_t) { ++numOps; } + void dup(std::size_t) { ++numOps; } + void push(StackSlot const&) { ++numOps; } + void pop() { ++numOps; } +}; + +/// Transform stack data by replacing all its phi variables with their respective preimages. +StackData stackPreImage(StackData _stack, PhiInverse const& _phiInverse); + +std::size_t findOptimalTargetSize(StackData const& _stackData, StackData const& _targetArgs, LivenessAnalysis::LivenessData const& _targetLiveOut, bool _canIntroduceJunk); + +CallSites gatherCallSites(SSACFG const& _cfg); + +} From 889679b01e23d439eddc5085101af92822753b7a Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Thu, 5 Feb 2026 14:46:54 +0100 Subject: [PATCH 66/73] Add SSA-CFG StackLayoutGenerator test --- test/CMakeLists.txt | 2 + test/InteractiveTests.h | 4 +- test/libyul/ssa/StackLayoutGeneratorTest.cpp | 216 +++++++++++++++++++ test/libyul/ssa/StackLayoutGeneratorTest.h | 37 ++++ test/libyul/ssa/StackShufflerTest.cpp | 4 +- test/libyul/ssa/StackShufflerTest.h | 2 +- test/tools/CMakeLists.txt | 2 + 7 files changed, 264 insertions(+), 3 deletions(-) create mode 100644 test/libyul/ssa/StackLayoutGeneratorTest.cpp create mode 100644 test/libyul/ssa/StackLayoutGeneratorTest.h diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index f36ae414764e..02a45088f935 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -173,6 +173,8 @@ set(libyul_sources libyul/YulOptimizerTest.h libyul/YulOptimizerTestCommon.cpp libyul/YulOptimizerTestCommon.h + libyul/ssa/StackLayoutGeneratorTest.cpp + libyul/ssa/StackLayoutGeneratorTest.h libyul/ssa/StackShufflerTest.cpp libyul/ssa/StackShufflerTest.h ) diff --git a/test/InteractiveTests.h b/test/InteractiveTests.h index ff2725471c7e..7930dc32d072 100644 --- a/test/InteractiveTests.h +++ b/test/InteractiveTests.h @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -74,7 +75,8 @@ Testsuite const g_interactiveTestsuites[] = { {"Yul Object Compiler", "libyul", "objectCompiler", false, false, &yul::test::ObjectCompilerTest::create}, {"Yul Control Flow Graph", "libyul", "yulControlFlowGraph", false, false, &yul::test::ControlFlowGraphTest::create}, {"Yul SSA Control Flow Graph", "libyul", "yulSSAControlFlowGraph", false, false, &yul::test::SSAControlFlowGraphTest::create}, - {"Yul SSA StackShuffling", "libyul", "ssa/stackShuffler", false, false, &yul::ssa::test::ShufflingTest::create}, + {"Yul SSA StackShuffling", "libyul", "ssa/stackShuffler", false, false, &yul::test::ssa::ShufflingTest::create}, + {"Yul SSA StackLayoutGenerator","libyul", "ssa/stackLayoutGenerator", false, false, &yul::test::ssa::StackLayoutGeneratorTest::create}, {"Yul Stack Layout", "libyul", "yulStackLayout", false, false, &yul::test::StackLayoutGeneratorTest::create}, {"Yul Stack Shuffling", "libyul", "yulStackShuffling", false, false, &yul::test::StackShufflingTest::create}, {"Control Flow Side Effects", "libyul", "controlFlowSideEffects", false, false, &yul::test::ControlFlowSideEffectsTest::create}, diff --git a/test/libyul/ssa/StackLayoutGeneratorTest.cpp b/test/libyul/ssa/StackLayoutGeneratorTest.cpp new file mode 100644 index 000000000000..a7ddad529cc1 --- /dev/null +++ b/test/libyul/ssa/StackLayoutGeneratorTest.cpp @@ -0,0 +1,216 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include + +#ifdef ISOLTEST +#include +#if (BOOST_VERSION < 108800) +#include +#else +#define BOOST_PROCESS_VERSION 1 +#include +#include +#include +#endif +#endif + +using namespace solidity; +using namespace solidity::util; +using namespace solidity::yul::ssa; +using namespace solidity::yul::test::ssa; + +namespace +{ + +class StackLayoutDotExporter: public io::DotExporterBase +{ +public: + StackLayoutDotExporter(SSACFG const& _cfg, std::size_t _functionIndex, SSACFGStackLayout const& _layout): + DotExporterBase(_cfg, _functionIndex), + m_layout(_layout) + { + } + +protected: + void writeBlockLabel(std::ostream& _out, SSACFG::BlockId _blockId) override + { + auto const& block = m_cfg.block(_blockId); + auto const& blockLayout = m_layout[_blockId]; + yulAssert(blockLayout.has_value()); + + _out << "\\\n"; + _out << "IN: " << stackToString(blockLayout->stackIn) << "\\l\\\n"; + + for (std::size_t i = 0; i < block.operations.size(); ++i) + { + auto const& operation = block.operations[i]; + yulAssert(i < blockLayout->operationIn.size()); + auto operationStack = blockLayout->operationIn[i]; + + _out << "\\l\\\n"; + _out << stackToString(operationStack) << "\\l\\\n"; + + std::visit(GenericVisitor{ + [&](SSACFG::Call const& _call) { + _out << escapeLabel(_call.function.get().name.str()); + }, + [&](SSACFG::BuiltinCall const& _call) { + _out << escapeLabel(_call.builtin.get().name); + }, + [&](SSACFG::LiteralAssignment const&) { + yulAssert(operation.inputs.size() == 1); + _out << escapeLabel(operation.inputs.back().str(m_cfg)); + } + }, operation.kind); + _out << "\\l\\\n"; + + yulAssert(operation.inputs.size() <= operationStack.size()); + for (std::size_t j = 0; j < operation.inputs.size(); ++j) + operationStack.pop_back(); + for (auto const& output: operation.outputs) + operationStack.push_back(StackSlot::makeValueID(output)); + _out << stackToString(operationStack) << "\\l\\\n"; + } + + _out << "\\l\\\n"; + _out << "OUT: " << stackToString(blockLayout->stackOut) << "\\l\\\n"; + } + +private: + SSACFGStackLayout const& m_layout; +}; + +} + +std::unique_ptr StackLayoutGeneratorTest::create(Config const& _config) +{ + return std::make_unique(_config.filename); +} + +StackLayoutGeneratorTest::StackLayoutGeneratorTest(std::string const& _filename): TestCase(_filename) +{ + m_source = m_reader.source(); + auto dialectName = m_reader.stringSetting("dialect", "evm"); + soltestAssert(dialectName == "evm"); + m_expectation = m_reader.simpleExpectations(); +} + +frontend::test::TestCase::TestResult StackLayoutGeneratorTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted) +{ + static std::string_view constexpr SUBOBJECT_GRAPH_SEPARATOR = "\n>>>>> GRAPH SEPARATOR\n"; + YulStack const yulStack = yul::test::parseYul(m_source); + if (yulStack.hasErrors()) + { + yul::test::printYulErrors(yulStack, _stream, _linePrefix, _formatted); + return TestResult::FatalError; + } + + std::set visited; + visited.insert(yulStack.parserResult().get()); + + std::vector toVisit{yulStack.parserResult().get()}; + while (!toVisit.empty()) + { + auto const& object = *toVisit.back(); + toVisit.pop_back(); + + std::unique_ptr const controlFlow = SSACFGBuilder::build( + *object.analysisInfo, + *object.dialect(), + object.code()->root(), + false + ); + // insert separator + if (!m_obtainedResult.empty()) + m_obtainedResult += SUBOBJECT_GRAPH_SEPARATOR; + + m_obtainedResult += "digraph SSACFG {\nnodesep=0.7;\ngraph[fontname=\"DejaVu Sans\", rankdir=LR]\nnode[shape=box,fontname=\"DejaVu Sans\"];\n\n"; + + for (std::size_t index = 0; index < controlFlow->functionGraphs.size(); ++index) + { + auto const& cfg = *controlFlow->functionGraphs[index]; + SSACFGStackLayout const layout = StackLayoutGenerator::generate( + LivenessAnalysis(cfg), + gatherCallSites(cfg) + ); + StackLayoutDotExporter exporter(cfg, index, layout); + if (cfg.function) + m_obtainedResult += exporter.exportFunction(*cfg.function, false); + else + m_obtainedResult += exporter.exportBlocks(cfg.entry, false); + } + + m_obtainedResult += "}\n"; + + for (auto const& subNode: object.subObjects) + if (auto subObject = std::dynamic_pointer_cast(subNode)) + if (!visited.contains(subObject.get())) + { + visited.insert(subObject.get()); + toVisit.push_back(subObject.get()); + } + } + + auto const result = checkResult(_stream, _linePrefix, _formatted); + +#ifdef ISOLTEST + char* graphDisplayer = nullptr; + if (result == TestResult::Failure) + graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_FAILURE"); + else if (result == TestResult::Success) + graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_SUCCESS"); + + if (graphDisplayer) + { + if (result == TestResult::Success) + std::cout << std::endl << m_source << std::endl; + for (auto const dotRange: ranges::views::split(m_obtainedResult, SUBOBJECT_GRAPH_SEPARATOR)) + { + std::string_view dot(&*dotRange.begin(), static_cast(ranges::distance(dotRange))); + boost::process::opstream pipe; + boost::process::child child(graphDisplayer, boost::process::std_in < pipe); + + pipe << dot; + pipe.flush(); + pipe.pipe().close(); + if (result == TestResult::Success) + child.wait(); + else + child.detach(); + } + } +#endif + + return result; +} diff --git a/test/libyul/ssa/StackLayoutGeneratorTest.h b/test/libyul/ssa/StackLayoutGeneratorTest.h new file mode 100644 index 000000000000..7b66363f3e48 --- /dev/null +++ b/test/libyul/ssa/StackLayoutGeneratorTest.h @@ -0,0 +1,37 @@ +/* + This file is part of solidity. + + solidity is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + solidity is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with solidity. If not, see . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + + +#include + +#include + +namespace solidity::yul::test::ssa +{ + +class StackLayoutGeneratorTest: public frontend::test::TestCase +{ +public: + static std::unique_ptr create(Config const& _config); + explicit StackLayoutGeneratorTest(std::string const& _filename); + TestResult run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) override; +}; + +} diff --git a/test/libyul/ssa/StackShufflerTest.cpp b/test/libyul/ssa/StackShufflerTest.cpp index 3c8c964e7ef1..cd24b3b5ec5c 100644 --- a/test/libyul/ssa/StackShufflerTest.cpp +++ b/test/libyul/ssa/StackShufflerTest.cpp @@ -39,8 +39,10 @@ #include using namespace solidity; +using namespace solidity::yul; using namespace solidity::yul::ssa; -using namespace solidity::yul::ssa::test; +using namespace solidity::yul::test; +using namespace solidity::yul::test::ssa; namespace { diff --git a/test/libyul/ssa/StackShufflerTest.h b/test/libyul/ssa/StackShufflerTest.h index 14b0d98f6859..37f9b61e58b1 100644 --- a/test/libyul/ssa/StackShufflerTest.h +++ b/test/libyul/ssa/StackShufflerTest.h @@ -22,7 +22,7 @@ #include -namespace solidity::yul::ssa::test +namespace solidity::yul::test::ssa { class ShufflingTest: public frontend::test::TestCase diff --git a/test/tools/CMakeLists.txt b/test/tools/CMakeLists.txt index 7b7331c77f09..0a1c33873595 100644 --- a/test/tools/CMakeLists.txt +++ b/test/tools/CMakeLists.txt @@ -53,6 +53,8 @@ add_executable(isoltest ../libyul/YulOptimizerTest.cpp ../libyul/YulOptimizerTestCommon.cpp ../libyul/YulInterpreterTest.cpp + ../libyul/ssa/StackLayoutGeneratorTest.cpp + ../libyul/ssa/StackLayoutGeneratorTest.h ../libyul/ssa/StackShufflerTest.cpp ../libyul/ssa/StackShufflerTest.h ) From b0d0ac1a212096ada177c3b875d22cdfdd511017 Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Mon, 9 Feb 2026 14:33:04 +0100 Subject: [PATCH 67/73] Add SSA CFG stack layout generation tests --- .../ssa/stackLayoutGenerator/dead_code.yul | 79 ++++++++++++ .../ssa/stackLayoutGenerator/function.yul | 106 ++++++++++++++++ .../ssa/stackLayoutGenerator/multi_return.yul | 59 +++++++++ .../ssa/stackLayoutGenerator/nested_for.yul | 119 ++++++++++++++++++ .../ssa/stackLayoutGenerator/recursion.yul | 71 +++++++++++ .../ssa/stackLayoutGenerator/simple_for.yul | 100 +++++++++++++++ .../ssa/stackLayoutGenerator/simple_if.yul | 76 +++++++++++ .../ssa/stackLayoutGenerator/switch.yul | 95 ++++++++++++++ 8 files changed, 705 insertions(+) create mode 100644 test/libyul/ssa/stackLayoutGenerator/dead_code.yul create mode 100644 test/libyul/ssa/stackLayoutGenerator/function.yul create mode 100644 test/libyul/ssa/stackLayoutGenerator/multi_return.yul create mode 100644 test/libyul/ssa/stackLayoutGenerator/nested_for.yul create mode 100644 test/libyul/ssa/stackLayoutGenerator/recursion.yul create mode 100644 test/libyul/ssa/stackLayoutGenerator/simple_for.yul create mode 100644 test/libyul/ssa/stackLayoutGenerator/simple_if.yul create mode 100644 test/libyul/ssa/stackLayoutGenerator/switch.yul diff --git a/test/libyul/ssa/stackLayoutGenerator/dead_code.yul b/test/libyul/ssa/stackLayoutGenerator/dead_code.yul new file mode 100644 index 000000000000..adba2a345a86 --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/dead_code.yul @@ -0,0 +1,79 @@ +{ + let x := calldataload(0) + if x { + revert(0, 0) + } + let y := calldataload(32) + if y { + revert(0, 0) + } + sstore(x, y) +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// [lit0]\l\ +// calldataload\l\ +// [v0]\l\ +// \l\ +// OUT: [v0, v0]\l\ +// "]; +// Block0_0 -> Block0_0Exit; +// Block0_0Exit [label="{ If v0 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_0Exit:0 -> Block0_2 [style="solid"]; +// Block0_0Exit:1 -> Block0_1 [style="solid"]; +// Block0_1 [label="\ +// IN: [v0]\l\ +// \l\ +// [JUNK, lit0, lit0]\l\ +// revert\l\ +// [JUNK]\l\ +// \l\ +// OUT: [JUNK]\l\ +// "]; +// Block0_1Exit [label="Terminated"]; +// Block0_1 -> Block0_1Exit; +// Block0_2 [label="\ +// IN: [v0]\l\ +// \l\ +// [v0, lit1]\l\ +// calldataload\l\ +// [v0, v1]\l\ +// \l\ +// OUT: [v0, v1, v1]\l\ +// "]; +// Block0_2 -> Block0_2Exit; +// Block0_2Exit [label="{ If v1 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_2Exit:0 -> Block0_5 [style="solid"]; +// Block0_2Exit:1 -> Block0_4 [style="solid"]; +// Block0_4 [label="\ +// IN: [v0, v1]\l\ +// \l\ +// [JUNK, JUNK, lit0, lit0]\l\ +// revert\l\ +// [JUNK, JUNK]\l\ +// \l\ +// OUT: [JUNK, JUNK]\l\ +// "]; +// Block0_4Exit [label="Terminated"]; +// Block0_4 -> Block0_4Exit; +// Block0_5 [label="\ +// IN: [v0, v1]\l\ +// \l\ +// [v0, v1, v0]\l\ +// sstore\l\ +// [v0]\l\ +// \l\ +// OUT: [v0]\l\ +// "]; +// Block0_5Exit [label="MainExit"]; +// Block0_5 -> Block0_5Exit; +// } diff --git a/test/libyul/ssa/stackLayoutGenerator/function.yul b/test/libyul/ssa/stackLayoutGenerator/function.yul new file mode 100644 index 000000000000..a134c36f8b35 --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/function.yul @@ -0,0 +1,106 @@ +{ + function f(a, b) -> r { + let x := add(a,b) + r := sub(x,a) + } + function g() { + sstore(0x01, 0x0101) + } + function h(x) { + h(f(x, 0)) + g() + } + function i() -> v, w { + v := 0x0202 + w := 0x0303 + } + let x, y := i() + h(x) + h(y) + // This call of g() is unreachable too as the one in h() but we wanna cover both cases. + g() +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// [FunctionCallReturnLabel[0]]\l\ +// i\l\ +// [FunctionCallReturnLabel[0], v0, v1]\l\ +// \l\ +// [v0, JUNK, v0]\l\ +// h\l\ +// [v0, JUNK]\l\ +// \l\ +// OUT: [v0, JUNK]\l\ +// "]; +// Block0_0Exit [label="Terminated"]; +// Block0_0 -> Block0_0Exit; +// FunctionEntry_f_0 [label="function f: +// r := f(v0, v1)"]; +// FunctionEntry_f_0 -> Block1_0; +// Block1_0 [label="\ +// IN: [v1, v0]\l\ +// \l\ +// [v0, v1, v0]\l\ +// add\l\ +// [v0, v2]\l\ +// \l\ +// [v0, v2]\l\ +// sub\l\ +// [v3]\l\ +// \l\ +// OUT: [v3]\l\ +// "]; +// Block1_0Exit [label="FunctionReturn[v3]"]; +// Block1_0 -> Block1_0Exit; +// FunctionEntry_g_0 [label="function g: +// g()"]; +// FunctionEntry_g_0 -> Block2_0; +// Block2_0 [label="\ +// IN: []\l\ +// \l\ +// [lit0, lit1]\l\ +// sstore\l\ +// []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block2_0Exit [label="FunctionReturn[]"]; +// Block2_0 -> Block2_0Exit; +// FunctionEntry_h_0 [label="function h: +// h(v0)"]; +// FunctionEntry_h_0 -> Block3_0; +// Block3_0 [label="\ +// IN: [v0]\l\ +// \l\ +// [v0, FunctionCallReturnLabel[0], lit0, v0]\l\ +// f\l\ +// [v0, FunctionCallReturnLabel[0], v1]\l\ +// \l\ +// [JUNK, v1]\l\ +// h\l\ +// [JUNK]\l\ +// \l\ +// OUT: [JUNK]\l\ +// "]; +// Block3_0Exit [label="Terminated"]; +// Block3_0 -> Block3_0Exit; +// FunctionEntry_i_0 [label="function i: +// v, w := i()"]; +// FunctionEntry_i_0 -> Block4_0; +// Block4_0 [label="\ +// IN: []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block4_0Exit [label="FunctionReturn[0x0202, 0x0303]"]; +// Block4_0 -> Block4_0Exit; +// } diff --git a/test/libyul/ssa/stackLayoutGenerator/multi_return.yul b/test/libyul/ssa/stackLayoutGenerator/multi_return.yul new file mode 100644 index 000000000000..c1f2b94d4b50 --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/multi_return.yul @@ -0,0 +1,59 @@ +{ + function pair(a) -> x, y { + x := add(a, 1) + y := add(a, 2) + } + let p, q := pair(42) + let r, s := pair(p) + sstore(q, add(r, s)) +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// [FunctionCallReturnLabel[0], lit0]\l\ +// pair\l\ +// [FunctionCallReturnLabel[0], v0, v1]\l\ +// \l\ +// [v0, v1, FunctionCallReturnLabel[1], v0]\l\ +// pair\l\ +// [v0, v1, FunctionCallReturnLabel[1], v2, v3]\l\ +// \l\ +// [JUNK, v1, v2, v3, v2]\l\ +// add\l\ +// [JUNK, v1, v2, v4]\l\ +// \l\ +// [JUNK, v1, JUNK, v4, v1]\l\ +// sstore\l\ +// [JUNK, v1, JUNK]\l\ +// \l\ +// OUT: [JUNK, v1, JUNK]\l\ +// "]; +// Block0_0Exit [label="MainExit"]; +// Block0_0 -> Block0_0Exit; +// FunctionEntry_pair_0 [label="function pair: +// x, y := pair(v0)"]; +// FunctionEntry_pair_0 -> Block1_0; +// Block1_0 [label="\ +// IN: [v0]\l\ +// \l\ +// [v0, lit1, v0]\l\ +// add\l\ +// [v0, v1]\l\ +// \l\ +// [v1, lit2, v0]\l\ +// add\l\ +// [v1, v2]\l\ +// \l\ +// OUT: [v1, v2]\l\ +// "]; +// Block1_0Exit [label="FunctionReturn[v1, v2]"]; +// Block1_0 -> Block1_0Exit; +// } diff --git a/test/libyul/ssa/stackLayoutGenerator/nested_for.yul b/test/libyul/ssa/stackLayoutGenerator/nested_for.yul new file mode 100644 index 000000000000..f595c19b2584 --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/nested_for.yul @@ -0,0 +1,119 @@ +{ + let s + for {let i := 0} lt(i, 10) {i := add(i, 1)} { + for {let j := 0} lt(j, 10) {j := add(j, 1)} { + s := add(s, mul(i, j)) + } + } + mstore(0, s) +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block0_0 -> Block0_0Exit [arrowhead=none]; +// Block0_0Exit [label="Jump" shape=oval]; +// Block0_0Exit -> Block0_1 [style="solid"]; +// Block0_1 [label="\ +// IN: [phi0, phi4]\l\ +// \l\ +// [phi0, phi4, lit1, phi0]\l\ +// lt\l\ +// [phi0, phi4, v0]\l\ +// \l\ +// OUT: [phi0, phi4, v0]\l\ +// "]; +// Block0_1 -> Block0_1Exit; +// Block0_1Exit [label="{ If v0 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_1Exit:0 -> Block0_4 [style="solid"]; +// Block0_1Exit:1 -> Block0_2 [style="solid"]; +// Block0_2 [label="\ +// IN: [phi0, phi4]\l\ +// \l\ +// OUT: [phi0, phi4]\l\ +// "]; +// Block0_2 -> Block0_2Exit [arrowhead=none]; +// Block0_2Exit [label="Jump" shape=oval]; +// Block0_2Exit -> Block0_5 [style="solid"]; +// Block0_4 [label="\ +// IN: [JUNK, phi4]\l\ +// \l\ +// [JUNK, phi4, lit0]\l\ +// mstore\l\ +// [JUNK]\l\ +// \l\ +// OUT: [JUNK]\l\ +// "]; +// Block0_4Exit [label="MainExit"]; +// Block0_4 -> Block0_4Exit; +// Block0_5 [label="\ +// IN: [phi0, JUNK, phi1, phi3]\l\ +// \l\ +// [phi0, JUNK, phi1, phi3, lit1, phi1]\l\ +// lt\l\ +// [phi0, JUNK, phi1, phi3, v1]\l\ +// \l\ +// OUT: [phi0, JUNK, phi1, phi3, v1]\l\ +// "]; +// Block0_5 -> Block0_5Exit; +// Block0_5Exit [label="{ If v1 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_5Exit:0 -> Block0_8 [style="solid"]; +// Block0_5Exit:1 -> Block0_6 [style="solid"]; +// Block0_6 [label="\ +// IN: [phi0, JUNK, phi1, phi3]\l\ +// \l\ +// [phi0, JUNK, phi1, phi3, phi1, phi0]\l\ +// mul\l\ +// [phi0, JUNK, phi1, phi3, v2]\l\ +// \l\ +// [phi0, JUNK, phi1, v2, phi3]\l\ +// add\l\ +// [phi0, JUNK, phi1, v3]\l\ +// \l\ +// OUT: [phi0, JUNK, phi1, v3]\l\ +// "]; +// Block0_6 -> Block0_6Exit [arrowhead=none]; +// Block0_6Exit [label="Jump" shape=oval]; +// Block0_6Exit -> Block0_7 [style="solid"]; +// Block0_8 [label="\ +// IN: [phi0, JUNK, JUNK, phi3]\l\ +// \l\ +// OUT: [phi0, JUNK, JUNK, phi3]\l\ +// "]; +// Block0_8 -> Block0_8Exit [arrowhead=none]; +// Block0_8Exit [label="Jump" shape=oval]; +// Block0_8Exit -> Block0_3 [style="solid"]; +// Block0_7 [label="\ +// IN: [phi0, JUNK, phi1, v3]\l\ +// \l\ +// [phi0, JUNK, v3, lit2, phi1]\l\ +// add\l\ +// [phi0, JUNK, v3, v4]\l\ +// \l\ +// OUT: [phi0, JUNK, v3, v4]\l\ +// "]; +// Block0_7 -> Block0_7Exit [arrowhead=none]; +// Block0_7Exit [label="Jump" shape=oval]; +// Block0_7Exit -> Block0_5 [style="solid"]; +// Block0_3 [label="\ +// IN: [phi0, JUNK, JUNK, phi3]\l\ +// \l\ +// [phi3, JUNK, JUNK, lit2, phi0]\l\ +// add\l\ +// [phi3, JUNK, JUNK, v5]\l\ +// \l\ +// OUT: [phi3, JUNK, JUNK, v5]\l\ +// "]; +// Block0_3 -> Block0_3Exit [arrowhead=none]; +// Block0_3Exit [label="Jump" shape=oval]; +// Block0_3Exit -> Block0_1 [style="solid"]; +// } diff --git a/test/libyul/ssa/stackLayoutGenerator/recursion.yul b/test/libyul/ssa/stackLayoutGenerator/recursion.yul new file mode 100644 index 000000000000..4a33f172d004 --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/recursion.yul @@ -0,0 +1,71 @@ +{ + function sum(n) -> s { + if n { + s := add(n, sum(sub(n, 1))) + } + } + mstore(0, sum(10)) +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// [FunctionCallReturnLabel[0], lit0]\l\ +// sum\l\ +// [FunctionCallReturnLabel[0], v0]\l\ +// \l\ +// [v0, lit1]\l\ +// mstore\l\ +// []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block0_0Exit [label="MainExit"]; +// Block0_0 -> Block0_0Exit; +// FunctionEntry_sum_0 [label="function sum: +// s := sum(v0)"]; +// FunctionEntry_sum_0 -> Block1_0; +// Block1_0 [label="\ +// IN: [v0]\l\ +// \l\ +// OUT: [v0, v0]\l\ +// "]; +// Block1_0 -> Block1_0Exit; +// Block1_0Exit [label="{ If v0 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block1_0Exit:0 -> Block1_2 [style="solid"]; +// Block1_0Exit:1 -> Block1_1 [style="solid"]; +// Block1_1 [label="\ +// IN: [v0]\l\ +// \l\ +// [v0, lit1, v0]\l\ +// sub\l\ +// [v0, v1]\l\ +// \l\ +// [v0, FunctionCallReturnLabel[0], v1]\l\ +// sum\l\ +// [v0, FunctionCallReturnLabel[0], v2]\l\ +// \l\ +// [v2, v0]\l\ +// add\l\ +// [v3]\l\ +// \l\ +// OUT: [v3]\l\ +// "]; +// Block1_1 -> Block1_1Exit [arrowhead=none]; +// Block1_1Exit [label="Jump" shape=oval]; +// Block1_1Exit -> Block1_2 [style="solid"]; +// Block1_2 [label="\ +// IN: [JUNK, phi0]\l\ +// \l\ +// OUT: [JUNK, phi0]\l\ +// "]; +// Block1_2Exit [label="FunctionReturn[phi0]"]; +// Block1_2 -> Block1_2Exit; +// } diff --git a/test/libyul/ssa/stackLayoutGenerator/simple_for.yul b/test/libyul/ssa/stackLayoutGenerator/simple_for.yul new file mode 100644 index 000000000000..f245c5f17014 --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/simple_for.yul @@ -0,0 +1,100 @@ +{ + let x + for {let i := 0} x {i := add(i, 1)} { + if mload(i) { + x := add(x, i) + x := add(x, mload(32)) + } + } + mstore(x, 33) +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block0_0 -> Block0_0Exit [arrowhead=none]; +// Block0_0Exit [label="Jump" shape=oval]; +// Block0_0Exit -> Block0_1 [style="solid"]; +// Block0_1 [label="\ +// IN: [phi0, phi1]\l\ +// \l\ +// OUT: [phi0, phi1, phi0]\l\ +// "]; +// Block0_1 -> Block0_1Exit; +// Block0_1Exit [label="{ If phi0 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_1Exit:0 -> Block0_4 [style="solid"]; +// Block0_1Exit:1 -> Block0_2 [style="solid"]; +// Block0_2 [label="\ +// IN: [phi0, phi1]\l\ +// \l\ +// [phi0, phi1, phi1]\l\ +// mload\l\ +// [phi0, phi1, v0]\l\ +// \l\ +// OUT: [phi0, phi1, v0]\l\ +// "]; +// Block0_2 -> Block0_2Exit; +// Block0_2Exit [label="{ If v0 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_2Exit:0 -> Block0_6 [style="solid"]; +// Block0_2Exit:1 -> Block0_5 [style="solid"]; +// Block0_4 [label="\ +// IN: [phi0, JUNK]\l\ +// \l\ +// [phi0, JUNK, lit3, phi0]\l\ +// mstore\l\ +// [phi0, JUNK]\l\ +// \l\ +// OUT: [phi0, JUNK]\l\ +// "]; +// Block0_4Exit [label="MainExit"]; +// Block0_4 -> Block0_4Exit; +// Block0_5 [label="\ +// IN: [phi0, phi1]\l\ +// \l\ +// [phi1, phi1, phi0]\l\ +// add\l\ +// [phi1, v1]\l\ +// \l\ +// [phi1, v1, lit1]\l\ +// mload\l\ +// [phi1, v1, v2]\l\ +// \l\ +// [phi1, v2, v1]\l\ +// add\l\ +// [phi1, v3]\l\ +// \l\ +// OUT: [phi1, v3]\l\ +// "]; +// Block0_5 -> Block0_5Exit [arrowhead=none]; +// Block0_5Exit [label="Jump" shape=oval]; +// Block0_5Exit -> Block0_6 [style="solid"]; +// Block0_6 [label="\ +// IN: [phi3, phi1]\l\ +// \l\ +// OUT: [phi3, phi1]\l\ +// "]; +// Block0_6 -> Block0_6Exit [arrowhead=none]; +// Block0_6Exit [label="Jump" shape=oval]; +// Block0_6Exit -> Block0_3 [style="solid"]; +// Block0_3 [label="\ +// IN: [phi3, phi1]\l\ +// \l\ +// [phi3, lit2, phi1]\l\ +// add\l\ +// [phi3, v4]\l\ +// \l\ +// OUT: [phi3, v4]\l\ +// "]; +// Block0_3 -> Block0_3Exit [arrowhead=none]; +// Block0_3Exit [label="Jump" shape=oval]; +// Block0_3Exit -> Block0_1 [style="solid"]; +// } diff --git a/test/libyul/ssa/stackLayoutGenerator/simple_if.yul b/test/libyul/ssa/stackLayoutGenerator/simple_if.yul new file mode 100644 index 000000000000..f9e0039e3362 --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/simple_if.yul @@ -0,0 +1,76 @@ +{ + function f(a, b) -> c { + if mload(a) { + a := add(a, 2) + revert(a, a) + } + c := add(a, b) + } + mstore(42, f(0, 1)) +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// [FunctionCallReturnLabel[0], lit0, lit1]\l\ +// f\l\ +// [FunctionCallReturnLabel[0], v0]\l\ +// \l\ +// [v0, lit2]\l\ +// mstore\l\ +// []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block0_0Exit [label="MainExit"]; +// Block0_0 -> Block0_0Exit; +// FunctionEntry_f_0 [label="function f: +// c := f(v0, v1)"]; +// FunctionEntry_f_0 -> Block1_0; +// Block1_0 [label="\ +// IN: [v1, v0]\l\ +// \l\ +// [v1, v0, v0]\l\ +// mload\l\ +// [v1, v0, v2]\l\ +// \l\ +// OUT: [v1, v0, v2]\l\ +// "]; +// Block1_0 -> Block1_0Exit; +// Block1_0Exit [label="{ If v2 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block1_0Exit:0 -> Block1_2 [style="solid"]; +// Block1_0Exit:1 -> Block1_1 [style="solid"]; +// Block1_1 [label="\ +// IN: [v1, v0]\l\ +// \l\ +// [JUNK, v0, lit1, v0]\l\ +// add\l\ +// [JUNK, v0, v3]\l\ +// \l\ +// [JUNK, JUNK, v3, v3]\l\ +// revert\l\ +// [JUNK, JUNK]\l\ +// \l\ +// OUT: [JUNK, JUNK]\l\ +// "]; +// Block1_1Exit [label="Terminated"]; +// Block1_1 -> Block1_1Exit; +// Block1_2 [label="\ +// IN: [v1, v0]\l\ +// \l\ +// [v1, v0]\l\ +// add\l\ +// [v4]\l\ +// \l\ +// OUT: [v4]\l\ +// "]; +// Block1_2Exit [label="FunctionReturn[v4]"]; +// Block1_2 -> Block1_2Exit; +// } diff --git a/test/libyul/ssa/stackLayoutGenerator/switch.yul b/test/libyul/ssa/stackLayoutGenerator/switch.yul new file mode 100644 index 000000000000..898944d3745e --- /dev/null +++ b/test/libyul/ssa/stackLayoutGenerator/switch.yul @@ -0,0 +1,95 @@ +{ + let x := 0x0101 + let y := 0x0202 + let z := 0x0303 + switch sload(x) + case 0 { + x := 0x42 + } + case 1 { + y := 0x42 + } + default { + sstore(z, z) + } + + sstore(0x0404, y) +} +// ---- +// digraph SSACFG { +// nodesep=0.7; +// graph[fontname="DejaVu Sans", rankdir=LR] +// node[shape=box,fontname="DejaVu Sans"]; +// +// Entry [label="Entry"]; +// Entry -> Block0_0; +// Block0_0 [label="\ +// IN: []\l\ +// \l\ +// [lit0]\l\ +// sload\l\ +// [v0]\l\ +// \l\ +// [v0, lit3, v0]\l\ +// eq\l\ +// [v0, v1]\l\ +// \l\ +// OUT: [v0, v1]\l\ +// "]; +// Block0_0 -> Block0_0Exit; +// Block0_0Exit [label="{ If v1 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_0Exit:0 -> Block0_3 [style="solid"]; +// Block0_0Exit:1 -> Block0_2 [style="solid"]; +// Block0_2 [label="\ +// IN: [v0]\l\ +// \l\ +// OUT: [v0]\l\ +// "]; +// Block0_2 -> Block0_2Exit [arrowhead=none]; +// Block0_2Exit [label="Jump" shape=oval]; +// Block0_2Exit -> Block0_1 [style="solid"]; +// Block0_3 [label="\ +// IN: [v0]\l\ +// \l\ +// [lit5, v0]\l\ +// eq\l\ +// [v2]\l\ +// \l\ +// OUT: [v2]\l\ +// "]; +// Block0_3 -> Block0_3Exit; +// Block0_3Exit [label="{ If v2 | { <0> Zero | <1> NonZero }}" shape=Mrecord]; +// Block0_3Exit:0 -> Block0_5 [style="solid"]; +// Block0_3Exit:1 -> Block0_4 [style="solid"]; +// Block0_1 [label="\ +// IN: [JUNK, phi0]\l\ +// \l\ +// [JUNK, phi0, lit6]\l\ +// sstore\l\ +// [JUNK]\l\ +// \l\ +// OUT: [JUNK]\l\ +// "]; +// Block0_1Exit [label="MainExit"]; +// Block0_1 -> Block0_1Exit; +// Block0_4 [label="\ +// IN: []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block0_4 -> Block0_4Exit [arrowhead=none]; +// Block0_4Exit [label="Jump" shape=oval]; +// Block0_4Exit -> Block0_1 [style="solid"]; +// Block0_5 [label="\ +// IN: []\l\ +// \l\ +// [lit2, lit2]\l\ +// sstore\l\ +// []\l\ +// \l\ +// OUT: []\l\ +// "]; +// Block0_5 -> Block0_5Exit [arrowhead=none]; +// Block0_5Exit [label="Jump" shape=oval]; +// Block0_5Exit -> Block0_1 [style="solid"]; +// } From 4b0ced45d4244abc392cfcb3caa6b3f39030dc6e Mon Sep 17 00:00:00 2001 From: clonker <1685266+clonker@users.noreply.github.com> Date: Tue, 17 Feb 2026 16:53:50 +0100 Subject: [PATCH 68/73] fix broken doc links --- docs/060-breaking-changes.rst | 2 +- docs/installing-solidity.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/060-breaking-changes.rst b/docs/060-breaking-changes.rst index c2a6ceb1ed54..030c59988b71 100644 --- a/docs/060-breaking-changes.rst +++ b/docs/060-breaking-changes.rst @@ -119,7 +119,7 @@ Metadata Hash Options The compiler now appends the `IPFS `_ hash of the metadata file to the end of the bytecode by default (for details, see documentation on :doc:`contract metadata `). Before 0.6.0, the compiler appended the -`Swarm `_ hash by default, and in order to still support this behavior, +`Swarm `_ hash by default, and in order to still support this behavior, the new command-line option ``--metadata-hash`` was introduced. It allows you to select the hash to be produced and appended, by passing either ``ipfs`` or ``swarm`` as value to the ``--metadata-hash`` command-line option. Passing the value ``none`` completely removes the hash. diff --git a/docs/installing-solidity.rst b/docs/installing-solidity.rst index 7e372ea4e3bf..a3a50a56e63a 100644 --- a/docs/installing-solidity.rst +++ b/docs/installing-solidity.rst @@ -142,7 +142,7 @@ available for some distributions: Exercise caution when using them. There is also a `snap package `_, however, it is **currently unmaintained**. -It is installable in all the `supported Linux distros `_. To +It is installable in all the `supported Linux distros `_. To install the latest stable version of solc: .. code-block:: bash From ffd11b3cf15118c5f99699eed497a12178165fb7 Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Thu, 12 Feb 2026 15:20:02 +0100 Subject: [PATCH 69/73] Test cases --- .../args | 1 + .../input.sol | 15 ++ .../output | 214 ++++++++++++++++++ ...fter_inherited_storage_same_value_type.sol | 26 +++ ...storage_mapping_delete_same_value_type.sol | 23 ++ ..._storage_struct_delete_same_value_type.sol | 28 +++ ...fore_inherited_storage_same_value_type.sol | 26 +++ ...storage_mapping_delete_same_value_type.sol | 23 ++ ..._storage_struct_delete_same_value_type.sol | 28 +++ ...storage_bool_array_transient_uint256_1.sol | 26 +++ ...storage_bool_array_transient_uint256_2.sol | 26 +++ .../delete_storage_u256_transient_u256_1.sol | 22 ++ .../delete_storage_u256_transient_u256_2.sol | 22 ++ 13 files changed, 480 insertions(+) create mode 100644 test/cmdlineTests/storage_transient_storage_collision_ir_output/args create mode 100644 test/cmdlineTests/storage_transient_storage_collision_ir_output/input.sol create mode 100644 test/cmdlineTests/storage_transient_storage_collision_ir_output/output create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_1.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_2.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_1.sol create mode 100644 test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_2.sol diff --git a/test/cmdlineTests/storage_transient_storage_collision_ir_output/args b/test/cmdlineTests/storage_transient_storage_collision_ir_output/args new file mode 100644 index 000000000000..b7ec904f1024 --- /dev/null +++ b/test/cmdlineTests/storage_transient_storage_collision_ir_output/args @@ -0,0 +1 @@ +--ir-optimized --evm-version cancun --debug-info none diff --git a/test/cmdlineTests/storage_transient_storage_collision_ir_output/input.sol b/test/cmdlineTests/storage_transient_storage_collision_ir_output/input.sol new file mode 100644 index 000000000000..e7d3930152fa --- /dev/null +++ b/test/cmdlineTests/storage_transient_storage_collision_ir_output/input.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0 +pragma solidity >=0.0; + +contract C { + uint256 transient varTransient; + uint256 public varStorage = 0xeeeeeeeeee; + + function foo() external returns (uint256) { + varTransient = 0xffffffff; + delete varTransient; + delete varStorage; + + return varStorage; + } +} diff --git a/test/cmdlineTests/storage_transient_storage_collision_ir_output/output b/test/cmdlineTests/storage_transient_storage_collision_ir_output/output new file mode 100644 index 000000000000..e3a251b2d8b0 --- /dev/null +++ b/test/cmdlineTests/storage_transient_storage_collision_ir_output/output @@ -0,0 +1,214 @@ +Optimized IR: +/// @use-src 0:"input.sol" +object "C_25" { + code { + { + mstore(64, memoryguard(0x80)) + if callvalue() + { + revert_error_ca66f745a3ce8ff40e2ccaf1ad45db7774001b90d25810abd9040049be7bf4bb() + } + constructor_C() + let _1 := allocate_unbounded() + codecopy(_1, dataoffset("C_25_deployed"), datasize("C_25_deployed")) + return(_1, datasize("C_25_deployed")) + } + function allocate_unbounded() -> memPtr + { memPtr := mload(64) } + function revert_error_ca66f745a3ce8ff40e2ccaf1ad45db7774001b90d25810abd9040049be7bf4bb() + { revert(0, 0) } + function shift_left(value) -> newValue + { newValue := shl(0, value) } + function update_byte_slice_shift(value, toInsert) -> result + { + let mask := not(0) + toInsert := shift_left(toInsert) + value := and(value, not(mask)) + result := or(value, and(toInsert, mask)) + } + function cleanup_rational_by(value) -> cleaned + { cleaned := value } + function cleanup_uint256(value) -> cleaned + { cleaned := value } + function identity(value) -> ret + { ret := value } + function convert_rational_by_to_uint256(value) -> converted + { + converted := cleanup_uint256(identity(cleanup_rational_by(value))) + } + function prepare_store_uint256(value) -> ret + { ret := value } + function update_storage_value_offset_rational_by_to_uint256(slot, value) + { + let convertedValue := convert_rational_by_to_uint256(value) + sstore(slot, update_byte_slice_shift(sload(slot), prepare_store_uint256(convertedValue))) + } + function constructor_C() + { + let expr := 0xeeeeeeeeee + update_storage_value_offset_rational_by_to_uint256(0x00, expr) + } + } + /// @use-src 0:"input.sol" + object "C_25_deployed" { + code { + { + mstore(64, memoryguard(0x80)) + if iszero(lt(calldatasize(), 4)) + { + let selector := shift_right_unsigned(calldataload(0)) + switch selector + case 0xc2985578 { external_fun_foo() } + case 0xff2558ff { external_fun_varStorage() } + default { } + } + revert_error_42b3090547df1d2001c96683413b8cf91c1b902ef5e3cb8d9f6f304cf7446f74() + } + function shift_right_unsigned(value) -> newValue + { newValue := shr(224, value) } + function allocate_unbounded() -> memPtr + { memPtr := mload(64) } + function revert_error_ca66f745a3ce8ff40e2ccaf1ad45db7774001b90d25810abd9040049be7bf4bb() + { revert(0, 0) } + function revert_error_dbdddcbe895c83990c08b3492a0e83918d802a52331272ac6fdb6a7c4aea3b1b() + { revert(0, 0) } + function abi_decode(headStart, dataEnd) + { + if slt(sub(dataEnd, headStart), 0) + { + revert_error_dbdddcbe895c83990c08b3492a0e83918d802a52331272ac6fdb6a7c4aea3b1b() + } + } + function cleanup_uint256(value) -> cleaned + { cleaned := value } + function abi_encode_uint256_to_uint256(value, pos) + { + mstore(pos, cleanup_uint256(value)) + } + function abi_encode_uint256(headStart, value0) -> tail + { + tail := add(headStart, 32) + abi_encode_uint256_to_uint256(value0, add(headStart, 0)) + } + function external_fun_foo() + { + if callvalue() + { + revert_error_ca66f745a3ce8ff40e2ccaf1ad45db7774001b90d25810abd9040049be7bf4bb() + } + abi_decode(4, calldatasize()) + let ret := fun_foo() + let memPos := allocate_unbounded() + let memEnd := abi_encode_uint256(memPos, ret) + return(memPos, sub(memEnd, memPos)) + } + function shift_right_unsigned_dynamic(bits, value) -> newValue + { newValue := shr(bits, value) } + function cleanup_from_storage_uint256(value) -> cleaned + { cleaned := value } + function extract_from_storage_value_dynamict_uint256(slot_value, offset) -> value + { + value := cleanup_from_storage_uint256(shift_right_unsigned_dynamic(mul(offset, 8), slot_value)) + } + function read_from_storage_split_dynamic_uint256(slot, offset) -> value + { + value := extract_from_storage_value_dynamict_uint256(sload(slot), offset) + } + function getter_fun_varStorage() -> ret + { + let slot := 0 + let offset := 0 + ret := read_from_storage_split_dynamic_uint256(slot, offset) + } + function external_fun_varStorage() + { + if callvalue() + { + revert_error_ca66f745a3ce8ff40e2ccaf1ad45db7774001b90d25810abd9040049be7bf4bb() + } + abi_decode(4, calldatasize()) + let ret := getter_fun_varStorage() + let memPos := allocate_unbounded() + let memEnd := abi_encode_uint256(memPos, ret) + return(memPos, sub(memEnd, memPos)) + } + function revert_error_42b3090547df1d2001c96683413b8cf91c1b902ef5e3cb8d9f6f304cf7446f74() + { revert(0, 0) } + function zero_value_for_split_uint256() -> ret + { ret := 0 } + function cleanup_rational_by(value) -> cleaned + { cleaned := value } + function identity(value) -> ret + { ret := value } + function convert_rational_by_to_uint256(value) -> converted + { + converted := cleanup_uint256(identity(cleanup_rational_by(value))) + } + function shift_left(value) -> newValue + { newValue := shl(0, value) } + function update_byte_slice_shift(value, toInsert) -> result + { + let mask := not(0) + toInsert := shift_left(toInsert) + value := and(value, not(mask)) + result := or(value, and(toInsert, mask)) + } + function convert_uint256_to_uint256(value) -> converted + { + converted := cleanup_uint256(identity(cleanup_uint256(value))) + } + function prepare_store_uint256(value) -> ret + { ret := value } + function update_transient_storage_value_offset_uint256_to_uint256(slot, value) + { + let convertedValue := convert_uint256_to_uint256(value) + tstore(slot, update_byte_slice_shift(tload(slot), prepare_store_uint256(convertedValue))) + } + function shift_left_dynamic(bits, value) -> newValue + { newValue := shl(bits, value) } + function update_byte_slice_dynamic32(value, shiftBytes, toInsert) -> result + { + let shiftBits := mul(shiftBytes, 8) + let mask := shift_left_dynamic(shiftBits, not(0)) + toInsert := shift_left_dynamic(shiftBits, toInsert) + value := and(value, not(mask)) + result := or(value, and(toInsert, mask)) + } + function update_transient_storage_value_uint256_to_uint256(slot, offset, value) + { + let convertedValue := convert_uint256_to_uint256(value) + tstore(slot, update_byte_slice_dynamic32(tload(slot), offset, prepare_store_uint256(convertedValue))) + } + function storage_set_to_zero_uint256(slot, offset) + { + let zero := zero_value_for_split_uint256() + update_transient_storage_value_uint256_to_uint256(slot, offset, zero) + } + function shift_right_0_unsigned(value) -> newValue + { newValue := shr(0, value) } + function extract_from_storage_value_offset_uint256(slot_value) -> value + { + value := cleanup_from_storage_uint256(shift_right_0_unsigned(slot_value)) + } + function read_from_storage_split_offset_uint256(slot) -> value + { + value := extract_from_storage_value_offset_uint256(sload(slot)) + } + function fun_foo() -> var + { + let zero_uint256 := zero_value_for_split_uint256() + var := zero_uint256 + let expr := 0xffffffff + let _1 := convert_rational_by_to_uint256(expr) + update_transient_storage_value_offset_uint256_to_uint256(0x00, _1) + storage_set_to_zero_uint256(0x00, 0) + storage_set_to_zero_uint256(0x00, 0) + let _2 := read_from_storage_split_offset_uint256(0x00) + let expr_1 := _2 + var := expr_1 + leave + } + } + data ".metadata" hex"" + } +} diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol new file mode 100644 index 000000000000..f4badbc98845 --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol @@ -0,0 +1,26 @@ +contract Base { + uint256 public x; + + function deleteX() internal { + delete x; + } +} + +contract C is Base { + uint256 transient t; + + function setAndClear() external { + x = 1; + t = 2; + deleteX(); + delete t; + assert(t == 0); + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// setAndClear() -> +// x() -> 1 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol new file mode 100644 index 000000000000..b1a38832158d --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol @@ -0,0 +1,23 @@ +contract C { + mapping(uint256 => uint256) m; + uint256 transient t; + + function setAndClear() external { + m[0] = 1; + t = 2; + delete m[0]; + delete t; + assert(t == 2); + } + + function getM() external view returns (uint256) { + return m[0]; + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// setAndClear() -> +// getM() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol new file mode 100644 index 000000000000..33a0dc2de46b --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol @@ -0,0 +1,28 @@ +contract C { + struct S { + uint256 a; + address b; + } + + S s; + uint256 transient t; + + function setAndDelete() external { + s.a = 1; + s.b = address(0x1234); + t = 2; + delete s; + delete t; + assert(t == 2); + } + + function getS() external view returns (uint256, address) { + return (s.a, s.b); + } +} +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// setAndDelete() -> +// getS() -> 0, 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol new file mode 100644 index 000000000000..8e40422a9019 --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol @@ -0,0 +1,26 @@ +contract Base { + uint256 public x; + + function deleteX() internal { + delete x; + } +} + +contract C is Base { + uint256 transient t; + + function setAndClear() external { + x = 1; + t = 2; + delete t; + assert(t == 0); + deleteX(); + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// setAndClear() -> +// x() -> 1 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol new file mode 100644 index 000000000000..129fafad7507 --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol @@ -0,0 +1,23 @@ +contract C { + mapping(uint256 => uint256) m; + uint256 transient t; + + function setAndClear() external { + m[0] = 1; + t = 2; + delete t; + assert(t == 0); + delete m[0]; + } + + function getM() external view returns (uint256) { + return m[0]; + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// setAndClear() -> +// getM() -> 1 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol new file mode 100644 index 000000000000..d499d0618374 --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol @@ -0,0 +1,28 @@ +contract C { + struct S { + uint256 a; + address b; + } + + S s; + uint256 transient t; + + function setAndDelete() external { + s.a = 1; + s.b = address(0x1234); + t = 2; + delete t; + assert(t == 0); + delete s; + } + + function getS() external view returns (uint256, address) { + return (s.a, s.b); + } +} +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// setAndDelete() -> +// getS() -> 1, 0 diff --git a/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_1.sol b/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_1.sol new file mode 100644 index 000000000000..4d84b23f70e7 --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_1.sol @@ -0,0 +1,26 @@ +pragma solidity >=0.0; + +contract C { + bool[3] flags = [true, true, true]; + uint256 transient temp; + + function f() external { + temp = 0xffffffff; + assert(temp == 0xffffffff); + delete temp; + delete flags; + } + + function getFlags() external returns(bool[3] memory) + { + return flags; + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// getFlags() -> true, true, true +// f() -> +// getFlags() -> true, true, true diff --git a/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_2.sol b/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_2.sol new file mode 100644 index 000000000000..f95b191c108c --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_2.sol @@ -0,0 +1,26 @@ +pragma solidity >=0.0; + +contract C { + bool[3] flags = [true, true, true]; + uint256 transient temp; + + function f() external { + temp = 0xffffffff; + assert(temp == 0xffffffff); + delete flags; + delete temp; + } + + function getFlags() external returns(bool[3] memory) + { + return flags; + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// getFlags() -> true, true, true +// f() -> +// getFlags() -> false, false, false diff --git a/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_1.sol b/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_1.sol new file mode 100644 index 000000000000..08f8120be0ce --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_1.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0 +pragma solidity >=0.0; + +contract C { + uint256 transient varTransient; + uint256 public varStorage = 0xeeeeeeeeee; + + function foo() external { + varTransient = 0xffffffff; + assert(varTransient == 0xffffffff); + delete varTransient; + delete varStorage; + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// varStorage() -> 0xeeeeeeeeee +// foo() -> +// varStorage() -> 0xeeeeeeeeee diff --git a/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_2.sol b/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_2.sol new file mode 100644 index 000000000000..03e06747af1a --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_2.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0 +pragma solidity >=0.0; + +contract C { + uint256 transient varTransient; + uint256 public varStorage = 0xeeeeeeeeee; + + function foo() external { + varTransient = 0xffffffff; + assert(varTransient == 0xffffffff); + delete varStorage; + delete varTransient; + } +} + +// ==== +// EVMVersion: >=cancun +// compileViaYul: true +// ---- +// varStorage() -> 0xeeeeeeeeee +// foo() -> +// varStorage() -> 0 From 580a72900dab63e14be7d171cf88f5cfce4d52a0 Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Thu, 12 Feb 2026 15:20:49 +0100 Subject: [PATCH 70/73] Changelog --- Changelog.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Changelog.md b/Changelog.md index d1bc022e3a23..9bf32bf2589c 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,8 @@ ### 0.8.34 (unreleased) +Important Bugfixes: +* Yul IR Code Generation: Fix a bug that could result in clearing a storage variable instead of a transient storage variable at the same position in the layout (and vice-versa). + Language Features: Compiler Features: From 12ede4f2650038b7f4c38ed1ef52b5d2da7d2dda Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Thu, 12 Feb 2026 15:22:09 +0100 Subject: [PATCH 71/73] Fix transient/storage collision when deleting --- libsolidity/codegen/YulUtilFunctions.cpp | 17 ++++++++++- .../output | 14 +++++++-- ...fter_inherited_storage_same_value_type.sol | 3 +- ...rage_array_delete_different_base_type.sol} | 9 ++---- ...after_storage_array_pop_same_base_type.sol | 30 +++++++++++++++++++ ..._after_storage_delete_same_value_type.sol} | 10 ++----- ...storage_mapping_delete_same_value_type.sol | 3 +- ..._storage_struct_delete_same_value_type.sol | 8 ++--- ...fore_inherited_storage_same_value_type.sol | 3 +- ...rage_array_delete_different_base_type.sol} | 11 +++---- ...rray_partial_assignment_same_base_type.sol | 27 +++++++++++++++++ ...before_storage_delete_same_value_type.sol} | 12 +++----- ...storage_mapping_delete_same_value_type.sol | 3 +- ..._storage_struct_delete_same_value_type.sol | 8 ++--- 14 files changed, 109 insertions(+), 49 deletions(-) rename test/libsolidity/semanticTests/storage/{delete_storage_bool_array_transient_uint256_2.sol => delete_overlapping_transient_after_storage_array_delete_different_base_type.sol} (75%) create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_array_pop_same_base_type.sol rename test/libsolidity/semanticTests/storage/{delete_storage_u256_transient_u256_2.sol => delete_overlapping_transient_after_storage_delete_same_value_type.sol} (63%) rename test/libsolidity/semanticTests/storage/{delete_storage_bool_array_transient_uint256_1.sol => delete_overlapping_transient_before_storage_array_delete_different_base_type.sol} (67%) create mode 100644 test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_array_partial_assignment_same_base_type.sol rename test/libsolidity/semanticTests/storage/{delete_storage_u256_transient_u256_1.sol => delete_overlapping_transient_before_storage_delete_same_value_type.sol} (57%) diff --git a/libsolidity/codegen/YulUtilFunctions.cpp b/libsolidity/codegen/YulUtilFunctions.cpp index 4c0a7026928a..bb18217f2f7c 100644 --- a/libsolidity/codegen/YulUtilFunctions.cpp +++ b/libsolidity/codegen/YulUtilFunctions.cpp @@ -4357,7 +4357,22 @@ std::string YulUtilFunctions::zeroValueFunction(Type const& _type, bool _splitFu std::string YulUtilFunctions::storageSetToZeroFunction(Type const& _type, VariableDeclaration::Location _location) { - std::string const functionName = "storage_set_to_zero_" + _type.identifier(); + solAssert( + _location == VariableDeclaration::Location::Transient || + _location == VariableDeclaration::Location::Unspecified, + "Invalid location for the storage_set_to_zero function" + ); + + if (dynamic_cast(&_type)) + solAssert( + _location == VariableDeclaration::Location::Unspecified && + _type.dataStoredIn(DataLocation::Storage) + ); + + std::string const functionName = + (_location == VariableDeclaration::Location::Transient ? "transient_"s : "") + + "storage_set_to_zero_" + + _type.identifier(); return m_functionCollector.createFunction(functionName, [&]() { if (_type.isValueType()) diff --git a/test/cmdlineTests/storage_transient_storage_collision_ir_output/output b/test/cmdlineTests/storage_transient_storage_collision_ir_output/output index e3a251b2d8b0..dd8abeb333b0 100644 --- a/test/cmdlineTests/storage_transient_storage_collision_ir_output/output +++ b/test/cmdlineTests/storage_transient_storage_collision_ir_output/output @@ -179,11 +179,21 @@ object "C_25" { let convertedValue := convert_uint256_to_uint256(value) tstore(slot, update_byte_slice_dynamic32(tload(slot), offset, prepare_store_uint256(convertedValue))) } - function storage_set_to_zero_uint256(slot, offset) + function transient_storage_set_to_zero_uint256(slot, offset) { let zero := zero_value_for_split_uint256() update_transient_storage_value_uint256_to_uint256(slot, offset, zero) } + function update_storage_value_uint256_to_uint256(slot, offset, value) + { + let convertedValue := convert_uint256_to_uint256(value) + sstore(slot, update_byte_slice_dynamic32(sload(slot), offset, prepare_store_uint256(convertedValue))) + } + function storage_set_to_zero_uint256(slot, offset) + { + let zero := zero_value_for_split_uint256() + update_storage_value_uint256_to_uint256(slot, offset, zero) + } function shift_right_0_unsigned(value) -> newValue { newValue := shr(0, value) } function extract_from_storage_value_offset_uint256(slot_value) -> value @@ -201,7 +211,7 @@ object "C_25" { let expr := 0xffffffff let _1 := convert_rational_by_to_uint256(expr) update_transient_storage_value_offset_uint256_to_uint256(0x00, _1) - storage_set_to_zero_uint256(0x00, 0) + transient_storage_set_to_zero_uint256(0x00, 0) storage_set_to_zero_uint256(0x00, 0) let _2 := read_from_storage_split_offset_uint256(0x00) let expr_1 := _2 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol index f4badbc98845..dae46cd32b51 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_inherited_storage_same_value_type.sol @@ -20,7 +20,6 @@ contract C is Base { // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // setAndClear() -> -// x() -> 1 +// x() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_2.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_array_delete_different_base_type.sol similarity index 75% rename from test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_2.sol rename to test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_array_delete_different_base_type.sol index f95b191c108c..d9a904f3caff 100644 --- a/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_2.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_array_delete_different_base_type.sol @@ -1,14 +1,12 @@ -pragma solidity >=0.0; - contract C { bool[3] flags = [true, true, true]; uint256 transient temp; - function f() external { + function setAndClear() external { temp = 0xffffffff; - assert(temp == 0xffffffff); delete flags; delete temp; + assert(temp == 0); } function getFlags() external returns(bool[3] memory) @@ -19,8 +17,7 @@ contract C { // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // getFlags() -> true, true, true -// f() -> +// setAndClear() -> // getFlags() -> false, false, false diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_array_pop_same_base_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_array_pop_same_base_type.sol new file mode 100644 index 000000000000..76dc10c43c11 --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_array_pop_same_base_type.sol @@ -0,0 +1,30 @@ +contract C { + uint256[] arr; + uint256 transient t; + + function pushArr() external { + arr.push(1); + } + + function setAndClear() external { + t = 2; + delete t; + assert(t == 0); + arr.pop(); + } + + // Get value at index 0, which should have been cleared after arr.pop() + function getArr() external returns (uint256 value) { + assembly { + mstore(0, arr.slot) + value := sload(keccak256(0x00, 0x20)) + } + } +} +// ==== +// EVMVersion: >=cancun +// ---- +// pushArr() -> +// getArr() -> 1 +// setAndClear() -> +// getArr() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_2.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_delete_same_value_type.sol similarity index 63% rename from test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_2.sol rename to test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_delete_same_value_type.sol index 03e06747af1a..ad206c6eeee0 100644 --- a/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_2.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_delete_same_value_type.sol @@ -1,22 +1,18 @@ -// SPDX-License-Identifier: GPL-2.0 -pragma solidity >=0.0; - contract C { uint256 transient varTransient; uint256 public varStorage = 0xeeeeeeeeee; - function foo() external { + function setAndClear() external { varTransient = 0xffffffff; - assert(varTransient == 0xffffffff); delete varStorage; delete varTransient; + assert(varTransient == 0); } } // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // varStorage() -> 0xeeeeeeeeee -// foo() -> +// setAndClear() -> // varStorage() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol index b1a38832158d..842cd47504b9 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_mapping_delete_same_value_type.sol @@ -7,7 +7,7 @@ contract C { t = 2; delete m[0]; delete t; - assert(t == 2); + assert(t == 0); } function getM() external view returns (uint256) { @@ -17,7 +17,6 @@ contract C { // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // setAndClear() -> // getM() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol index 33a0dc2de46b..703816296268 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol @@ -4,16 +4,14 @@ contract C { address b; } - S s; + S s = S(1, address(0x1234)); uint256 transient t; function setAndDelete() external { - s.a = 1; - s.b = address(0x1234); t = 2; delete s; delete t; - assert(t == 2); + assert(t == 0); } function getS() external view returns (uint256, address) { @@ -22,7 +20,7 @@ contract C { } // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- +// getS() -> 1, 4660 // setAndDelete() -> // getS() -> 0, 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol index 8e40422a9019..3af1b66e591c 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_inherited_storage_same_value_type.sol @@ -20,7 +20,6 @@ contract C is Base { // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // setAndClear() -> -// x() -> 1 +// x() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_1.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_array_delete_different_base_type.sol similarity index 67% rename from test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_1.sol rename to test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_array_delete_different_base_type.sol index 4d84b23f70e7..c2e1c1a241cc 100644 --- a/test/libsolidity/semanticTests/storage/delete_storage_bool_array_transient_uint256_1.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_array_delete_different_base_type.sol @@ -1,13 +1,11 @@ -pragma solidity >=0.0; - contract C { bool[3] flags = [true, true, true]; uint256 transient temp; - function f() external { + function setAndClear() external { temp = 0xffffffff; - assert(temp == 0xffffffff); delete temp; + assert(temp == 0); delete flags; } @@ -19,8 +17,7 @@ contract C { // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // getFlags() -> true, true, true -// f() -> -// getFlags() -> true, true, true +// setAndClear() -> +// getFlags() -> false, false, false diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_array_partial_assignment_same_base_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_array_partial_assignment_same_base_type.sol new file mode 100644 index 000000000000..a9d3e0ae7384 --- /dev/null +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_array_partial_assignment_same_base_type.sol @@ -0,0 +1,27 @@ +contract C { + uint256[2] small; + uint256[4] large; + uint256 transient t; + + function setAndClear() external { + large = [1,2,3,4]; + small = [10, 20]; + t = 99; + + delete t; + assert(t == 0); + large = small; + } + + function getLarge() external view returns (uint256[4] memory) { + return large; + } +} +// ==== +// EVMVersion: >=cancun +// ---- +// setAndClear() -> +// gas irOptimized: 124683 +// gas legacy: 127807 +// gas legacyOptimized: 124828 +// getLarge() -> 10, 20, 0, 0 diff --git a/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_1.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_delete_same_value_type.sol similarity index 57% rename from test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_1.sol rename to test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_delete_same_value_type.sol index 08f8120be0ce..26e34fc26a55 100644 --- a/test/libsolidity/semanticTests/storage/delete_storage_u256_transient_u256_1.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_delete_same_value_type.sol @@ -1,22 +1,18 @@ -// SPDX-License-Identifier: GPL-2.0 -pragma solidity >=0.0; - contract C { uint256 transient varTransient; uint256 public varStorage = 0xeeeeeeeeee; - function foo() external { + function setAndClear() external { varTransient = 0xffffffff; - assert(varTransient == 0xffffffff); delete varTransient; + assert(varTransient == 0); delete varStorage; } } // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // varStorage() -> 0xeeeeeeeeee -// foo() -> -// varStorage() -> 0xeeeeeeeeee +// setAndClear() -> +// varStorage() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol index 129fafad7507..6e262c8a6269 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_mapping_delete_same_value_type.sol @@ -17,7 +17,6 @@ contract C { // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- // setAndClear() -> -// getM() -> 1 +// getM() -> 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol index d499d0618374..c2127c9bad1f 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol @@ -4,12 +4,10 @@ contract C { address b; } - S s; + S s = S(1, address(0x1234)); uint256 transient t; function setAndDelete() external { - s.a = 1; - s.b = address(0x1234); t = 2; delete t; assert(t == 0); @@ -22,7 +20,7 @@ contract C { } // ==== // EVMVersion: >=cancun -// compileViaYul: true // ---- +// getS() -> 1, 4660 // setAndDelete() -> -// getS() -> 1, 0 +// getS() -> 0, 0 From 57e789309840a528eb868a6de25f56f27c52820e Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Fri, 13 Feb 2026 11:10:47 +0100 Subject: [PATCH 72/73] Bug list entry --- docs/bugs.json | 14 ++++++++++++++ docs/bugs_by_version.json | 12 ++++++++++-- ...after_storage_struct_delete_same_value_type.sol | 2 +- ...efore_storage_struct_delete_same_value_type.sol | 2 +- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/bugs.json b/docs/bugs.json index 0c0b0493d735..5f8d1a162732 100644 --- a/docs/bugs.json +++ b/docs/bugs.json @@ -1,4 +1,18 @@ [ + { + "uid": "SOL-2026-1", + "name": "TransientStorageClearingHelperCollision", + "summary": "Clearing both storage and transient storage variables in the same contract may result in only one of these locations being cleared.", + "description": "The IR-based code generator provides a set of Yul helper functions for basic operations, such as clearing, copying, encoding or type conversions. Not all functions are used by every contract. The codegen appends them to the generated sources individually, only when an operation that would invoke one of them is encountered. Utility functions are often specialized for different types and locations. Since Yul does not support generic functions, specialization is done by generating multiple versions of the same function, with the information distinguishing the variants embedded in their names. However, if not all the necessary bits of distinguishing information are properly accounted for, two helpers may end up with the same name, causing a collision. In this situation the codegen includes only one of them, with calls to both variants invoking it. This happened with the ``set_to_zero`` helper used when an area of transient or persistent storage needs to be cleared. The helper name was missing the location information, which resulted in a collision between the persistent and transient storage variants for the same type. This meant that contracts clearing both locations would actually clear only one, leaving the other untouched. Which location ended up being cleared depended on the order in which the code generator processed the input. The necessary condition to trigger the bug was the use of ``delete`` operator on a transient storage variable. This was due to value types being the only types supported in transient storage and ``delete`` being the only operation invoking the helper allowed on such types. The other necessary condition was clearing of persistent storage and in this case the range of affected operations was wider: operator ``delete``, array ``pop()`` or assignment that resulted in a longer array being overwritten with a shorter one. The cleared variable itself also did not necessarily have to be of the same type. It was enough that a matching value type was nested in it. It also did not always have to be the exact same value type - clearing operations on reference types are usually performed at slot granularity, treating every slot as ``uint256`` rather than clearing every value packed into it individually. To trigger the bug both operations had to be present within the same piece of bytecode. Independent contracts, not related through inheritance, would not affect each other this way. The presence of one operation only in creation code and the other only in deployed code would not trigger the bug either.", + "link": "https://blog.soliditylang.org/2026/02/18/transient-storage-clearing-helper-collision-bug/", + "introduced": "0.8.28", + "fixed": "0.8.34", + "severity": "high", + "conditions": { + "viaIR": true, + "evmVersion": ">=cancun" + } + }, { "uid": "SOL-2025-1", "name": "LostStorageArrayWriteOnSlotOverflow", diff --git a/docs/bugs_by_version.json b/docs/bugs_by_version.json index 8a4d2fe23b00..c76c6e7c17b6 100644 --- a/docs/bugs_by_version.json +++ b/docs/bugs_by_version.json @@ -2013,12 +2013,14 @@ }, "0.8.28": { "bugs": [ + "TransientStorageClearingHelperCollision", "LostStorageArrayWriteOnSlotOverflow" ], "released": "2024-10-09" }, "0.8.29": { "bugs": [ + "TransientStorageClearingHelperCollision", "LostStorageArrayWriteOnSlotOverflow" ], "released": "2025-03-12" @@ -2039,22 +2041,28 @@ }, "0.8.30": { "bugs": [ + "TransientStorageClearingHelperCollision", "LostStorageArrayWriteOnSlotOverflow" ], "released": "2025-05-07" }, "0.8.31": { "bugs": [ + "TransientStorageClearingHelperCollision", "LostStorageArrayWriteOnSlotOverflow" ], "released": "2025-12-03" }, "0.8.32": { - "bugs": [], + "bugs": [ + "TransientStorageClearingHelperCollision" + ], "released": "2025-12-18" }, "0.8.33": { - "bugs": [], + "bugs": [ + "TransientStorageClearingHelperCollision" + ], "released": "2025-12-18" }, "0.8.4": { diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol index 703816296268..04b8d47cfe3d 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_after_storage_struct_delete_same_value_type.sol @@ -21,6 +21,6 @@ contract C { // ==== // EVMVersion: >=cancun // ---- -// getS() -> 1, 4660 +// getS() -> 1, 0x1234 // setAndDelete() -> // getS() -> 0, 0 diff --git a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol index c2127c9bad1f..1c9cc49650bf 100644 --- a/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol +++ b/test/libsolidity/semanticTests/storage/delete_overlapping_transient_before_storage_struct_delete_same_value_type.sol @@ -21,6 +21,6 @@ contract C { // ==== // EVMVersion: >=cancun // ---- -// getS() -> 1, 4660 +// getS() -> 1, 0x1234 // setAndDelete() -> // getS() -> 0, 0 From e958997006159edca53cd25d6cbd2bc8869b0acd Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Wed, 18 Feb 2026 09:45:19 +0100 Subject: [PATCH 73/73] Changelog for 0.8.34 --- Changelog.md | 5 +---- docs/bugs_by_version.json | 4 ++++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Changelog.md b/Changelog.md index 9bf32bf2589c..e4b13172cf58 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,15 +1,12 @@ -### 0.8.34 (unreleased) +### 0.8.34 (2026-02-18) Important Bugfixes: * Yul IR Code Generation: Fix a bug that could result in clearing a storage variable instead of a transient storage variable at the same position in the layout (and vice-versa). -Language Features: Compiler Features: * Yul Optimizer: Remove redundant prerequisite steps from the default optimizer sequence. -Bugfixes: - ### 0.8.33 (2025-12-18) diff --git a/docs/bugs_by_version.json b/docs/bugs_by_version.json index c76c6e7c17b6..c5576d4b298e 100644 --- a/docs/bugs_by_version.json +++ b/docs/bugs_by_version.json @@ -2065,6 +2065,10 @@ ], "released": "2025-12-18" }, + "0.8.34": { + "bugs": [], + "released": "2026-02-18" + }, "0.8.4": { "bugs": [ "LostStorageArrayWriteOnSlotOverflow",