id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,302
|
CommandLineParser.h
|
ethereum_solidity/solc/CommandLineParser.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Validates and parses command-line options into an internal representation.
*/
#pragma once
#include <libsolidity/interface/CompilerStack.h>
#include <libsolidity/interface/DebugSettings.h>
#include <libsolidity/interface/FileReader.h>
#include <libsolidity/interface/ImportRemapper.h>
#include <libyul/YulStack.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/EVMVersion.h>
#include <libsolutil/JSON.h>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <map>
#include <memory>
#include <optional>
#include <ostream>
#include <set>
#include <string>
#include <vector>
namespace solidity::frontend
{
enum class InputMode
{
Help,
License,
Version,
Compiler,
CompilerWithASTImport,
StandardJson,
Linker,
Assembler,
LanguageServer,
EVMAssemblerJSON
};
struct CompilerOutputs
{
bool operator!=(CompilerOutputs const& _other) const noexcept { return !(*this == _other); }
bool operator==(CompilerOutputs const& _other) const noexcept;
friend std::ostream& operator<<(std::ostream& _out, CompilerOutputs const& _requests);
static std::string const& componentName(bool CompilerOutputs::* _component);
static auto const& componentMap()
{
static std::map<std::string, bool CompilerOutputs::*> const components = {
{"ast-compact-json", &CompilerOutputs::astCompactJson},
{"asm", &CompilerOutputs::asm_},
{"asm-json", &CompilerOutputs::asmJson},
{"opcodes", &CompilerOutputs::opcodes},
{"bin", &CompilerOutputs::binary},
{"bin-runtime", &CompilerOutputs::binaryRuntime},
{"abi", &CompilerOutputs::abi},
{"ir", &CompilerOutputs::ir},
{"ir-ast-json", &CompilerOutputs::irAstJson},
{"ir-optimized", &CompilerOutputs::irOptimized},
{"ir-optimized-ast-json", &CompilerOutputs::irOptimizedAstJson},
{"hashes", &CompilerOutputs::signatureHashes},
{"userdoc", &CompilerOutputs::natspecUser},
{"devdoc", &CompilerOutputs::natspecDev},
{"metadata", &CompilerOutputs::metadata},
{"storage-layout", &CompilerOutputs::storageLayout},
{"transient-storage-layout", &CompilerOutputs::transientStorageLayout},
{"yul-cfg-json", &CompilerOutputs::yulCFGJson},
};
return components;
}
bool astCompactJson = false;
bool asm_ = false;
bool asmJson = false;
bool opcodes = false;
bool binary = false;
bool binaryRuntime = false;
bool abi = false;
bool ir = false;
bool irAstJson = false;
bool yulCFGJson = false;
bool irOptimized = false;
bool irOptimizedAstJson = false;
bool signatureHashes = false;
bool natspecUser = false;
bool natspecDev = false;
bool metadata = false;
bool storageLayout = false;
bool transientStorageLayout = false;
};
struct CombinedJsonRequests
{
bool operator!=(CombinedJsonRequests const& _other) const noexcept { return !(*this == _other); }
bool operator==(CombinedJsonRequests const& _other) const noexcept;
friend std::ostream& operator<<(std::ostream& _out, CombinedJsonRequests const& _requests);
static std::string const& componentName(bool CombinedJsonRequests::* _component);
static auto const& componentMap()
{
static std::map<std::string, bool CombinedJsonRequests::*> const components = {
{"abi", &CombinedJsonRequests::abi},
{"metadata", &CombinedJsonRequests::metadata},
{"bin", &CombinedJsonRequests::binary},
{"bin-runtime", &CombinedJsonRequests::binaryRuntime},
{"opcodes", &CombinedJsonRequests::opcodes},
{"asm", &CombinedJsonRequests::asm_},
{"storage-layout", &CombinedJsonRequests::storageLayout},
{"transient-storage-layout", &CombinedJsonRequests::transientStorageLayout},
{"generated-sources", &CombinedJsonRequests::generatedSources},
{"generated-sources-runtime", &CombinedJsonRequests::generatedSourcesRuntime},
{"srcmap", &CombinedJsonRequests::srcMap},
{"srcmap-runtime", &CombinedJsonRequests::srcMapRuntime},
{"function-debug", &CombinedJsonRequests::funDebug},
{"function-debug-runtime", &CombinedJsonRequests::funDebugRuntime},
{"hashes", &CombinedJsonRequests::signatureHashes},
{"devdoc", &CombinedJsonRequests::natspecDev},
{"userdoc", &CombinedJsonRequests::natspecUser},
{"ast", &CombinedJsonRequests::ast},
};
return components;
}
bool abi = false;
bool metadata = false;
bool binary = false;
bool binaryRuntime = false;
bool opcodes = false;
bool asm_ = false;
bool storageLayout = false;
bool transientStorageLayout = false;
bool generatedSources = false;
bool generatedSourcesRuntime = false;
bool srcMap = false;
bool srcMapRuntime = false;
bool funDebug = false;
bool funDebugRuntime = false;
bool signatureHashes = false;
bool natspecDev = false;
bool natspecUser = false;
bool ast = false;
};
struct CommandLineOptions
{
bool operator==(CommandLineOptions const& _other) const noexcept;
bool operator!=(CommandLineOptions const& _other) const noexcept { return !(*this == _other); }
OptimiserSettings optimiserSettings() const;
struct
{
InputMode mode = InputMode::Compiler;
std::set<boost::filesystem::path> paths;
std::vector<ImportRemapper::Remapping> remappings;
bool addStdin = false;
boost::filesystem::path basePath = "";
std::vector<boost::filesystem::path> includePaths;
FileReader::FileSystemPathSet allowedDirectories;
bool ignoreMissingFiles = false;
bool noImportCallback = false;
} input;
struct
{
boost::filesystem::path dir;
bool overwriteFiles = false;
langutil::EVMVersion evmVersion;
bool viaIR = false;
RevertStrings revertStrings = RevertStrings::Default;
std::optional<langutil::DebugInfoSelection> debugInfoSelection;
CompilerStack::State stopAfter = CompilerStack::State::CompilationSuccessful;
std::optional<uint8_t> eofVersion;
} output;
struct
{
yul::YulStack::Machine targetMachine = yul::YulStack::Machine::EVM;
yul::YulStack::Language inputLanguage = yul::YulStack::Language::StrictAssembly;
} assembly;
struct
{
std::map<std::string, util::h160> libraries; // library name -> address
} linker;
struct
{
util::JsonFormat json;
std::optional<bool> coloredOutput;
bool withErrorIds = false;
} formatting;
struct
{
CompilerOutputs outputs;
bool estimateGas = false;
std::optional<CombinedJsonRequests> combinedJsonRequests;
} compiler;
struct
{
CompilerStack::MetadataFormat format = CompilerStack::defaultMetadataFormat();
CompilerStack::MetadataHash hash = CompilerStack::MetadataHash::IPFS;
bool literalSources = false;
} metadata;
struct
{
bool optimizeEvmasm = false;
bool optimizeYul = false;
std::optional<unsigned> expectedExecutionsPerDeployment;
std::optional<std::string> yulSteps;
} optimizer;
struct
{
bool initialize = false;
ModelCheckerSettings settings;
} modelChecker;
};
/// Parses the command-line arguments and produces a filled-out CommandLineOptions structure.
/// Validates provided values and reports errors by throwing @p CommandLineValidationErrors.
class CommandLineParser
{
public:
/// Parses the command-line arguments and fills out the internal CommandLineOptions structure.
/// @throws CommandLineValidationError if the arguments cannot be properly parsed or are invalid.
/// When an exception is thrown, the @p CommandLineOptions may be only partially filled out.
void parse(int _argc, char const* const* _argv);
CommandLineOptions const& options() const { return m_options; }
static void printHelp(std::ostream& _out) { _out << optionsDescription(true /* _forHelp */); }
private:
/// @returns a specification of all named command-line options accepted by the compiler.
/// The object can be used to parse command-line arguments or to generate the help screen.
static boost::program_options::options_description optionsDescription(bool _forHelp = false);
/// @returns a specification of all positional command-line arguments accepted by the compiler.
/// The object can be used to parse command-line arguments or to generate the help screen.
static boost::program_options::positional_options_description positionalOptionsDescription();
/// Uses boost::program_options to parse the command-line arguments and leaves the result in @a m_args.
/// Also handles the arguments that result in information being printed followed by immediate exit.
/// @returns false if parsing fails due to syntactical errors or the arguments not matching the description.
void parseArgs(int _argc, char const* const* _argv);
/// Validates parsed arguments stored in @a m_args and fills out the internal CommandLineOptions
/// structure.
/// @throws CommandLineValidationError in case of validation errors.
void processArgs();
/// Parses the value supplied to --combined-json.
/// @throws CommandLineValidationError in case of validation errors.
void parseCombinedJsonOption();
/// Parses the names of the input files, remappings. Does not check if the files actually exist.
/// @throws CommandLineValidationError in case of validation errors.
void parseInputPathsAndRemappings();
/// Tries to read from the file @a _input or interprets @a _input literally if that fails.
/// It then tries to parse the contents and appends to @a m_options.libraries.
/// @throws CommandLineValidationError in case of validation errors.
void parseLibraryOption(std::string const& _input);
void parseOutputSelection();
void checkMutuallyExclusive(std::vector<std::string> const& _optionNames);
size_t countEnabledOptions(std::vector<std::string> const& _optionNames) const;
static std::string joinOptionNames(std::vector<std::string> const& _optionNames, std::string _separator = ", ");
CommandLineOptions m_options;
/// Map of command-line arguments produced by boost::program_options.
/// Serves as input for filling out m_options.
boost::program_options::variables_map m_args;
};
} // namespace solidity::frontend
| 10,480
|
C++
|
.h
| 262
| 37.572519
| 113
| 0.770811
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,304
|
FilesystemUtils.h
|
ethereum_solidity/test/FilesystemUtils.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Helpers for common filesystem operations used in multiple tests.
*/
#pragma once
#include <boost/filesystem.hpp>
#include <set>
#include <string>
namespace solidity::test
{
/// Creates all the specified files and fills them with the specifiedcontent. Creates their parent
/// directories if they do not exist. Throws an exception if any part of the operation does not succeed.
void createFilesWithParentDirs(std::set<boost::filesystem::path> const& _paths, std::string const& _content = "");
/// Creates a file with the exact content specified in the second argument.
/// Throws an exception if the file already exists or if the parent directory of the file does not.
void createFileWithContent(boost::filesystem::path const& _path, std::string const& _content);
/// Creates a symlink between two paths.
/// The target does not have to exist.
/// If @p directorySymlink is true, indicate to the operating system that this is a directory
/// symlink. On some systems (e.g. Windows) it's possible to create a non-directory symlink pointing
/// at a directory, which makes such a symlinks unusable.
/// @returns true if the symlink has been successfully created, false if the filesystem does not
/// support symlinks.
/// Throws an exception of the operation fails for a different reason.
bool createSymlinkIfSupportedByFilesystem(
boost::filesystem::path _targetPath,
boost::filesystem::path const& _linkName,
bool _directorySymlink
);
}
| 2,140
|
C++
|
.h
| 43
| 48.139535
| 114
| 0.782838
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,309
|
EVMHost.h
|
ethereum_solidity/test/EVMHost.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* EVM execution host, i.e. component that implements a simulated Ethereum blockchain
* for testing purposes.
*/
#pragma once
#include <test/evmc/mocked_host.hpp>
#include <test/evmc/evmc.hpp>
#include <test/evmc/evmc.h>
#include <liblangutil/EVMVersion.h>
#include <libsolutil/FixedHash.h>
#include <boost/filesystem.hpp>
#include<unordered_set>
namespace solidity::test
{
using Address = util::h160;
using StorageMap = std::map<evmc::bytes32, evmc::StorageValue>;
struct EVMPrecompileOutput {
bytes const output;
int64_t gas_used;
};
class EVMHost: public evmc::MockedHost
{
public:
// Verbatim features of MockedHost.
using MockedHost::account_exists;
using MockedHost::get_storage;
using MockedHost::set_storage;
using MockedHost::get_balance;
using MockedHost::get_code_size;
using MockedHost::get_code_hash;
using MockedHost::copy_code;
using MockedHost::get_tx_context;
using MockedHost::emit_log;
using MockedHost::access_account;
using MockedHost::access_storage;
// Modified features of MockedHost.
bool selfdestruct(evmc::address const& _addr, evmc::address const& _beneficiary) noexcept final;
evmc::Result call(evmc_message const& _message) noexcept final;
evmc::bytes32 get_block_hash(int64_t number) const noexcept final;
// Solidity testing specific features.
/// Tries to dynamically load an evmc vm supporting evm1 and caches the loaded VM.
/// @returns vmc::VM(nullptr) on failure.
static evmc::VM& getVM(std::string const& _path = {});
/// Tries to load all defined evmc vm shared libraries.
/// @param _vmPaths paths to multiple evmc shared libraries.
/// @throw Exception if multiple evm1 vms where loaded.
/// @returns true, if an evmc vm supporting evm1 was loaded properly,
static bool checkVmPaths(std::vector<boost::filesystem::path> const& _vmPaths);
explicit EVMHost(langutil::EVMVersion _evmVersion, evmc::VM& _vm);
/// Reset entire state (including accounts).
void reset();
/// Start new block.
void newBlock()
{
tx_context.block_number++;
tx_context.block_timestamp += 15;
recorded_logs.clear();
newTransactionFrame();
}
/// @returns contents of storage at @param _addr.
StorageMap const& get_address_storage(evmc::address const& _addr);
u256 totalCodeDepositGas() const { return m_totalCodeDepositGas; }
static Address convertFromEVMC(evmc::address const& _addr);
static evmc::address convertToEVMC(Address const& _addr);
static util::h256 convertFromEVMC(evmc::bytes32 const& _data);
static evmc::bytes32 convertToEVMC(util::h256 const& _data);
private:
/// Transfer value between accounts. Checks for sufficient balance.
void transfer(evmc::MockedAccount& _sender, evmc::MockedAccount& _recipient, u256 const& _value) noexcept;
/// Start a new transaction frame.
/// This will perform selfdestructs, apply storage status changes across all accounts,
/// and clear account/storage access indicator for EIP-2929.
void newTransactionFrame();
/// Records calls made via @param _message.
void recordCalls(evmc_message const& _message) noexcept;
static evmc::Result precompileECRecover(evmc_message const& _message) noexcept;
static evmc::Result precompileSha256(evmc_message const& _message) noexcept;
static evmc::Result precompileRipeMD160(evmc_message const& _message) noexcept;
static evmc::Result precompileIdentity(evmc_message const& _message) noexcept;
static evmc::Result precompileModExp(evmc_message const& _message) noexcept;
template <evmc_revision Revision>
static evmc::Result precompileALTBN128G1Add(evmc_message const& _message) noexcept;
template <evmc_revision Revision>
static evmc::Result precompileALTBN128G1Mul(evmc_message const& _message) noexcept;
template <evmc_revision Revision>
static evmc::Result precompileALTBN128PairingProduct(evmc_message const& _message) noexcept;
static evmc::Result precompileBlake2f(evmc_message const& _message) noexcept;
static evmc::Result precompileGeneric(evmc_message const& _message, std::map<bytes, EVMPrecompileOutput> const& _inOut) noexcept;
/// @returns a result object with gas usage and result data taken from @a _data.
/// The outcome will be a failure if the limit < required.
/// @note The return value is only valid as long as @a _data is alive!
static evmc::Result resultWithGas(int64_t gas_limit, int64_t gas_required, bytes const& _data) noexcept;
static evmc::Result resultWithFailure() noexcept;
evmc::VM& m_vm;
/// EVM version requested by the testing tool
langutil::EVMVersion m_evmVersion;
/// EVM version requested from EVMC (matches the above)
evmc_revision m_evmRevision;
/// Store the accounts that have been created in the current transaction.
std::unordered_set<evmc::address> m_newlyCreatedAccounts;
/// The part of the total cost of the current transaction that paid for the code deposits.
/// I.e. GAS_CODE_DEPOSIT times the total size of deployed code of all newly created contracts,
/// including the current contract itself if it was a creation transaction.
u256 m_totalCodeDepositGas;
};
class EVMHostPrinter
{
public:
/// Constructs a host printer object for state at @param _address.
explicit EVMHostPrinter(EVMHost& _host, evmc::address _address):
m_host(_host),
m_account(_address)
{}
/// @returns state at account maintained by host.
std::string state();
private:
/// Outputs storage at account to stateStream.
void storage();
/// Outputs call records for account to stateStream.
void callRecords();
/// Outputs balance of account to stateStream.
void balance();
/// Outputs self-destruct record for account to stateStream.
void selfdestructRecords();
std::ostringstream m_stateStream;
EVMHost& m_host;
evmc::address m_account;
};
}
| 6,388
|
C++
|
.h
| 143
| 42.615385
| 130
| 0.778404
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,310
|
TestCaseReader.h
|
ethereum_solidity/test/TestCaseReader.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/libsolidity/util/SoltestErrors.h>
#include <libsolutil/StringUtils.h>
#include <range/v3/view/map.hpp>
#include <boost/filesystem.hpp>
#include <boost/throw_exception.hpp>
#include <fstream>
#include <map>
#include <string>
namespace solidity::frontend::test
{
/**
* A map for registering source names that also contains the main source name in a test case.
*/
struct SourceMap
{
std::map<std::string, std::string> sources;
std::map<std::string, boost::filesystem::path> externalSources;
std::string mainSourceFile;
};
/**
* A reader for test case data file, which parses source, settings and (optionally) simple expectations.
*/
class TestCaseReader
{
public:
TestCaseReader() = default;
explicit TestCaseReader(std::string const& _filename);
explicit TestCaseReader(std::istringstream const& _testCode);
SourceMap const& sources() const { return m_sources; }
std::string const& source() const;
std::size_t lineNumber() const { return m_lineNumber; }
std::map<std::string, std::string> const& settings() const { return m_settings; }
std::ifstream& stream() { return m_fileStream; }
std::string simpleExpectations();
bool boolSetting(std::string const& _name, bool _defaultValue);
size_t sizetSetting(std::string const& _name, size_t _defaultValue);
std::string stringSetting(std::string const& _name, std::string const& _defaultValue);
template <typename E>
E enumSetting(std::string const& _name, std::map<std::string, E> const& _choices, std::string const& _defaultChoice);
void ensureAllSettingsRead() const;
private:
std::pair<SourceMap, std::size_t> parseSourcesAndSettingsWithLineNumber(std::istream& _file);
static std::string parseSimpleExpectations(std::istream& _file);
std::ifstream m_fileStream;
boost::filesystem::path m_fileName;
SourceMap m_sources;
std::size_t m_lineNumber = 0;
std::map<std::string, std::string> m_settings;
std::map<std::string, std::string> m_unreadSettings; ///< tracks which settings are left unread
};
template <typename E>
E TestCaseReader::enumSetting(std::string const& _name, std::map<std::string, E> const& _choices, std::string const& _defaultChoice)
{
soltestAssert(_choices.count(_defaultChoice) > 0, "");
std::string value = stringSetting(_name, _defaultChoice);
if (_choices.count(value) == 0)
BOOST_THROW_EXCEPTION(std::runtime_error(
"Invalid Enum value: " + value + ". Available choices: " + util::joinHumanReadable(_choices | ranges::views::keys) + "."
));
return _choices.at(value);
}
}
| 3,217
|
C++
|
.h
| 77
| 39.792208
| 132
| 0.758665
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,311
|
InteractiveTests.h
|
ethereum_solidity/test/InteractiveTests.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/TestCase.h>
#include <test/libsolidity/ABIJsonTest.h>
#include <test/libsolidity/ASTJSONTest.h>
#include <test/libsolidity/ASTPropertyTest.h>
#include <libsolidity/FunctionDependencyGraphTest.h>
#include <test/libsolidity/GasTest.h>
#include <test/libsolidity/MemoryGuardTest.h>
#include <test/libsolidity/NatspecJSONTest.h>
#include <test/libsolidity/OptimizedIRCachingTest.h>
#include <test/libsolidity/SyntaxTest.h>
#include <test/libsolidity/SemanticTest.h>
#include <test/libsolidity/SMTCheckerTest.h>
#include <test/libyul/ControlFlowGraphTest.h>
#include <test/libyul/SSAControlFlowGraphTest.h>
#include <test/libyul/EVMCodeTransformTest.h>
#include <test/libyul/YulOptimizerTest.h>
#include <test/libyul/YulInterpreterTest.h>
#include <test/libyul/ObjectCompilerTest.h>
#include <test/libyul/ControlFlowSideEffectsTest.h>
#include <test/libyul/FunctionSideEffects.h>
#include <test/libyul/StackLayoutGeneratorTest.h>
#include <test/libyul/StackShufflingTest.h>
#include <test/libyul/SyntaxTest.h>
#include <boost/filesystem.hpp>
namespace solidity::frontend::test
{
/** Container for all information regarding a testsuite */
struct Testsuite
{
char const* title;
boost::filesystem::path const path;
boost::filesystem::path const subpath;
bool smt;
bool needsVM;
TestCase::TestCaseCreator testCaseCreator;
std::vector<std::string> labels{};
};
/// Array of testsuits that can be run interactively as well as automatically
Testsuite const g_interactiveTestsuites[] = {
/*
Title Path Subpath SMT NeedsVM Creator function */
{"Yul Optimizer", "libyul", "yulOptimizerTests", false, false, &yul::test::YulOptimizerTest::create},
{"Yul Interpreter", "libyul", "yulInterpreterTests", false, false, &yul::test::YulInterpreterTest::create},
{"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 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},
{"Function Side Effects", "libyul", "functionSideEffects", false, false, &yul::test::FunctionSideEffects::create},
{"Yul Syntax", "libyul", "yulSyntaxTests", false, false, &yul::test::SyntaxTest::create},
{"EVM Code Transform", "libyul", "evmCodeTransform", false, false, &yul::test::EVMCodeTransformTest::create, {"nooptions"}},
{"Syntax", "libsolidity", "syntaxTests", false, false, &SyntaxTest::create},
{"Semantic", "libsolidity", "semanticTests", false, true, &SemanticTest::create},
{"JSON AST", "libsolidity", "ASTJSON", false, false, &ASTJSONTest::create},
{"JSON ABI", "libsolidity", "ABIJson", false, false, &ABIJsonTest::create},
{"JSON Natspec", "libsolidity", "natspecJSON", false, false, &NatspecJSONTest::create},
{"SMT Checker", "libsolidity", "smtCheckerTests", true, false, &SMTCheckerTest::create},
{"Gas Estimates", "libsolidity", "gasTests", false, false, &GasTest::create},
{"Memory Guard", "libsolidity", "memoryGuardTests", false, false, &MemoryGuardTest::create},
{"AST Properties", "libsolidity", "astPropertyTests", false, false, &ASTPropertyTest::create},
{"Function Dependency Graph", "libsolidity", "functionDependencyGraphTests", false, false, &FunctionDependencyGraphTest::create},
{"Optimized IR Caching", "libsolidity", "optimizedIRCaching", false, false, &OptimizedIRCachingTest::create},
};
}
| 5,187
|
C++
|
.h
| 80
| 63.1875
| 152
| 0.672096
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,312
|
Common.h
|
ethereum_solidity/test/solc/Common.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/// Utilities shared by multiple tests for code in solc/.
#include <solc/CommandLineParser.h>
#include <boost/test/unit_test.hpp>
#include <optional>
#include <string>
#include <vector>
BOOST_TEST_DONT_PRINT_LOG_VALUE(solidity::frontend::CommandLineOptions)
BOOST_TEST_DONT_PRINT_LOG_VALUE(solidity::frontend::InputMode)
BOOST_TEST_DONT_PRINT_LOG_VALUE(solidity::frontend::OptimiserSettings)
namespace solidity::frontend::test
{
struct OptionsReaderAndMessages
{
bool success;
CommandLineOptions options;
FileReader reader;
std::optional<std::string> standardJsonInput;
std::string stdoutContent;
std::string stderrContent;
};
std::vector<char const*> makeArgv(std::vector<std::string> const& _commandLine);
/// Runs only command-line parsing, without compilation, assembling or any other input processing.
/// Lets through any @a CommandLineErrors throw by the CLI.
/// Note: This uses the @a CommandLineInterface class and does not actually spawn a new process.
/// @param _commandLine Arguments in the form of strings that would be specified on the command-line.
/// You must specify the program name as the first item.
/// @param _standardInputContent Content that the CLI will be able to read from its standard input.
OptionsReaderAndMessages parseCommandLineAndReadInputFiles(
std::vector<std::string> const& _commandLine,
std::string const& _standardInputContent = ""
);
/// Runs all stages of command-line interface processing, including error handling.
/// Never throws @a CommandLineError - validation errors are included in the returned stderr content.
/// Note: This uses the @a CommandLineInterface class and does not actually spawn a new process.
/// @param _commandLine Arguments in the form of strings that would be specified on the command-line.
/// You must specify the program name as the first item.
/// @param _standardInputContent Content that the CLI will be able to read from its standard input.
OptionsReaderAndMessages runCLI(
std::vector<std::string> const& _commandLine,
std::string const& _standardInputContent = ""
);
} // namespace solidity::frontend::test
| 2,834
|
C++
|
.h
| 56
| 48.982143
| 101
| 0.781838
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,313
|
fuzzer_common.h
|
ethereum_solidity/test/tools/fuzzer_common.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolutil/Common.h>
#include <map>
#include <string>
/**
* Functions to be used for fuzz-testing of various components.
* They throw exceptions or error.
*/
struct FuzzerUtil
{
static void runCompiler(std::string const& _input, bool _quiet);
static void testCompilerJsonInterface(std::string const& _input, bool _optimize, bool _quiet);
static void testConstantOptimizer(std::string const& _input, bool _quiet);
static void testStandardCompiler(std::string const& _input, bool _quiet);
/// Compiles @param _input which is a map of input file name to source code
/// string with optimisation turned on if @param _optimize is true
/// (off otherwise), a pseudo-random @param _rand that selects the EVM
/// version to be compiled for, and bool @param _forceSMT that, if true,
/// adds the experimental SMTChecker pragma to each source file in the
/// source map.
static void testCompiler(
solidity::StringMap& _input,
bool _optimize,
unsigned _rand,
bool _forceSMT,
bool _compileViaYul
);
/// Adds the experimental SMTChecker pragma to each source file in the
/// source map.
static void forceSMT(solidity::StringMap& _input);
};
| 1,854
|
C++
|
.h
| 44
| 40.113636
| 95
| 0.767184
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,314
|
IsolTestOptions.h
|
ethereum_solidity/test/tools/IsolTestOptions.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/** @file IsolTestOptions.h
*/
#pragma once
#include <liblangutil/EVMVersion.h>
#include <test/Common.h>
namespace solidity::test
{
struct IsolTestOptions: CommonOptions
{
bool showHelp = false;
bool noColor = false;
bool acceptUpdates = false;
std::string testFilter = std::string{};
std::string editor = std::string{};
explicit IsolTestOptions();
void addOptions() override;
bool parse(int _argc, char const* const* _argv) override;
void validate() const override;
};
}
| 1,174
|
C++
|
.h
| 34
| 32.617647
| 69
| 0.776991
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,316
|
SolidityGenerator.h
|
ethereum_solidity/test/tools/ossfuzz/SolidityGenerator.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Implements generators for synthesizing mostly syntactically valid
* Solidity test programs.
*/
#pragma once
#include <test/tools/ossfuzz/Generators.h>
#include <liblangutil/Exceptions.h>
#include <memory>
#include <random>
#include <set>
#include <variant>
namespace solidity::test::fuzzer::mutator
{
/// Forward declarations
class SolidityGenerator;
/// Type declarations
#define SEMICOLON() ;
#define FORWARDDECLAREGENERATORS(G) class G
GENERATORLIST(FORWARDDECLAREGENERATORS, SEMICOLON(), SEMICOLON())
#undef FORWARDDECLAREGENERATORS
#undef SEMICOLON
#define COMMA() ,
using GeneratorPtr = std::variant<
#define VARIANTOFSHARED(G) std::shared_ptr<G>
GENERATORLIST(VARIANTOFSHARED, COMMA(), )
>;
#undef VARIANTOFSHARED
using Generator = std::variant<
#define VARIANTOFGENERATOR(G) G
GENERATORLIST(VARIANTOFGENERATOR, COMMA(), )
>;
#undef VARIANTOFGENERATOR
#undef COMMA
using RandomEngine = std::mt19937_64;
using Distribution = std::uniform_int_distribution<size_t>;
struct UniformRandomDistribution
{
explicit UniformRandomDistribution(std::unique_ptr<RandomEngine> _randomEngine):
randomEngine(std::move(_randomEngine))
{}
/// @returns an unsigned integer in the range [1, @param _n] chosen
/// uniformly at random.
[[nodiscard]] size_t distributionOneToN(size_t _n) const
{
return Distribution(1, _n)(*randomEngine);
}
/// @returns true with a probability of 1/(@param _n), false otherwise.
/// @param _n must be non zero.
[[nodiscard]] bool probable(size_t _n) const
{
solAssert(_n > 0, "");
return distributionOneToN(_n) == 1;
}
std::unique_ptr<RandomEngine> randomEngine;
};
struct TestState
{
explicit TestState(std::shared_ptr<UniformRandomDistribution> _urd):
sourceUnitPaths({}),
currentSourceUnitPath({}),
uRandDist(std::move(_urd))
{}
/// Adds @param _path to @name sourceUnitPaths updates
/// @name currentSourceUnitPath.
void addSourceUnit(std::string const& _path)
{
sourceUnitPaths.insert(_path);
currentSourceUnitPath = _path;
}
/// @returns true if @name sourceUnitPaths is empty,
/// false otherwise.
[[nodiscard]] bool empty() const
{
return sourceUnitPaths.empty();
}
/// @returns the number of items in @name sourceUnitPaths.
[[nodiscard]] size_t size() const
{
return sourceUnitPaths.size();
}
/// Prints test state to @param _os.
void print(std::ostream& _os) const;
/// @returns a randomly chosen path from @param _sourceUnitPaths.
[[nodiscard]] std::string randomPath(std::set<std::string> const& _sourceUnitPaths) const;
/// @returns a randomly chosen path from @name sourceUnitPaths.
[[nodiscard]] std::string randomPath() const;
/// @returns a randomly chosen non current source unit path.
[[nodiscard]] std::string randomNonCurrentPath() const;
/// List of source paths in test input.
std::set<std::string> sourceUnitPaths;
/// Source path being currently visited.
std::string currentSourceUnitPath;
/// Uniform random distribution.
std::shared_ptr<UniformRandomDistribution> uRandDist;
};
struct GeneratorBase
{
explicit GeneratorBase(std::shared_ptr<SolidityGenerator> _mutator);
template <typename T>
std::shared_ptr<T> generator()
{
for (auto& g: generators)
if (std::holds_alternative<std::shared_ptr<T>>(g))
return std::get<std::shared_ptr<T>>(g);
solAssert(false, "");
}
/// @returns test fragment created by this generator.
std::string generate()
{
std::string generatedCode = visit();
endVisit();
return generatedCode;
}
/// @returns a string representing the generation of
/// the Solidity grammar element.
virtual std::string visit() = 0;
/// Method called after visiting this generator. Used
/// for clearing state if necessary.
virtual void endVisit() {}
/// Visitor that invokes child grammar elements of
/// this grammar element returning their string
/// representations.
std::string visitChildren();
/// Adds generators for child grammar elements of
/// this grammar element.
void addGenerators(std::set<GeneratorPtr> _generators)
{
generators += _generators;
}
/// Virtual method to obtain string name of generator.
virtual std::string name() = 0;
/// Virtual method to add generators that this grammar
/// element depends on. If not overridden, there are
/// no dependencies.
virtual void setup() {}
virtual ~GeneratorBase()
{
generators.clear();
}
/// Shared pointer to the mutator instance
std::shared_ptr<SolidityGenerator> mutator;
/// Set of generators used by this generator.
std::set<GeneratorPtr> generators;
/// Shared ptr to global test state.
std::shared_ptr<TestState> state;
/// Uniform random distribution
std::shared_ptr<UniformRandomDistribution> uRandDist;
};
class TestCaseGenerator: public GeneratorBase
{
public:
explicit TestCaseGenerator(std::shared_ptr<SolidityGenerator> _mutator):
GeneratorBase(std::move(_mutator)),
m_numSourceUnits(0)
{}
void setup() override;
std::string visit() override;
std::string name() override
{
return "Test case generator";
}
private:
/// @returns a new source path name that is formed by concatenating
/// a static prefix @name m_sourceUnitNamePrefix, a monotonically
/// increasing counter starting from 0 and the postfix (extension)
/// ".sol".
[[nodiscard]] std::string path() const
{
return m_sourceUnitNamePrefix + std::to_string(m_numSourceUnits) + ".sol";
}
/// Adds @param _path to list of source paths in global test
/// state and increments @name m_numSourceUnits.
void updateSourcePath(std::string const& _path)
{
state->addSourceUnit(_path);
m_numSourceUnits++;
}
/// Number of source units in test input
size_t m_numSourceUnits;
/// String prefix of source unit names
std::string const m_sourceUnitNamePrefix = "su";
/// Maximum number of source units per test input
static constexpr unsigned s_maxSourceUnits = 3;
};
class SourceUnitGenerator: public GeneratorBase
{
public:
explicit SourceUnitGenerator(std::shared_ptr<SolidityGenerator> _mutator):
GeneratorBase(std::move(_mutator))
{}
void setup() override;
std::string visit() override;
std::string name() override { return "Source unit generator"; }
};
class PragmaGenerator: public GeneratorBase
{
public:
explicit PragmaGenerator(std::shared_ptr<SolidityGenerator> _mutator):
GeneratorBase(std::move(_mutator))
{}
std::string visit() override;
std::string name() override { return "Pragma generator"; }
};
class ImportGenerator: public GeneratorBase
{
public:
explicit ImportGenerator(std::shared_ptr<SolidityGenerator> _mutator):
GeneratorBase(std::move(_mutator))
{}
std::string visit() override;
std::string name() override { return "Import generator"; }
private:
/// Inverse probability with which a source unit
/// imports itself. Keeping this at 17 seems to
/// produce self imported source units with a
/// frequency small enough so that it does not
/// consume too many fuzzing cycles but large
/// enough so that the fuzzer generates self
/// import statements every once in a while.
static constexpr size_t s_selfImportInvProb = 17;
};
class SolidityGenerator: public std::enable_shared_from_this<SolidityGenerator>
{
public:
explicit SolidityGenerator(unsigned _seed);
/// @returns the generator of type @param T.
template <typename T>
std::shared_ptr<T> generator();
/// @returns a shared ptr to underlying random
/// number distribution.
std::shared_ptr<UniformRandomDistribution> uniformRandomDist()
{
return m_urd;
}
/// @returns a pseudo randomly generated test case.
std::string generateTestProgram();
/// @returns shared ptr to global test state.
std::shared_ptr<TestState> testState()
{
return m_state;
}
private:
template <typename T>
void createGenerator()
{
m_generators.insert(
std::make_shared<T>(shared_from_this())
);
}
template <std::size_t I = 0>
void createGenerators();
void destroyGenerators()
{
m_generators.clear();
}
/// Sub generators
std::set<GeneratorPtr> m_generators;
/// Shared global test state
std::shared_ptr<TestState> m_state;
/// Uniform random distribution
std::shared_ptr<UniformRandomDistribution> m_urd;
};
}
| 8,788
|
C++
|
.h
| 277
| 29.736462
| 91
| 0.757272
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,317
|
Generators.h
|
ethereum_solidity/test/tools/ossfuzz/Generators.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Convenience macros for Solidity generator type declarations.
*/
#pragma once
/*
* Alphabetically sorted Generator types.
* SEP must appear between two elements and ENDSEP must
* appear after the last element.
*
* This macro applies another macro (MACRO) that is
* passed as input to this macro on the list of Generator
* types. Example that uses forward declaration:
*
* #define MACRO(G) class G;
* #define SEMICOLON() ;
*
* GENERATORLIST(MACRO, SEMICOLON(), SEMICOLON())
*
* produces
*
* class PragmaGenerator;class SourceUnitGenerator;class TestCaseGenerator;
*
*/
#define GENERATORLIST(MACRO, SEP, ENDSEP) \
MACRO(ImportGenerator) SEP \
MACRO(PragmaGenerator) SEP \
MACRO(SourceUnitGenerator) SEP \
MACRO(TestCaseGenerator) ENDSEP
| 1,451
|
C++
|
.h
| 42
| 32.595238
| 75
| 0.777066
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,318
|
SolidityEvmoneInterface.h
|
ethereum_solidity/test/tools/ossfuzz/SolidityEvmoneInterface.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/EVMHost.h>
#include <libsolidity/interface/CompilerStack.h>
#include <libyul/YulStack.h>
#include <libsolutil/Keccak256.h>
#include <evmone/evmone.h>
namespace solidity::test::fuzzer
{
struct CompilerOutput
{
/// EVM bytecode returned by compiler
solidity::bytes byteCode;
/// Method identifiers in a contract
Json methodIdentifiersInContract;
};
struct CompilerInput
{
CompilerInput(
langutil::EVMVersion _evmVersion,
StringMap const& _sourceCode,
std::string const& _contractName,
frontend::OptimiserSettings _optimiserSettings,
std::map<std::string, solidity::util::h160> _libraryAddresses,
bool _debugFailure = false,
bool _viaIR = false
):
evmVersion(_evmVersion),
sourceCode(_sourceCode),
contractName(_contractName),
optimiserSettings(_optimiserSettings),
libraryAddresses(_libraryAddresses),
debugFailure(_debugFailure),
viaIR(_viaIR)
{}
/// EVM target version
langutil::EVMVersion evmVersion;
/// Source code to be compiled
StringMap const& sourceCode;
/// Contract name without a colon prefix
std::string contractName;
/// Optimiser setting to be used during compilation
frontend::OptimiserSettings optimiserSettings;
/// Information on which library is deployed where
std::map<std::string, solidity::util::h160> libraryAddresses;
/// Flag used for debugging
bool debugFailure;
/// Flag to enable new code generator.
bool viaIR;
};
class SolidityCompilationFramework
{
public:
SolidityCompilationFramework(CompilerInput _input): m_compilerInput(_input)
{}
/// Sets contract name to @param _contractName.
void contractName(std::string const& _contractName)
{
m_compilerInput.contractName = _contractName;
}
/// Sets library addresses to @param _libraryAddresses.
void libraryAddresses(std::map<std::string, solidity::util::h160> _libraryAddresses)
{
m_compilerInput.libraryAddresses = std::move(_libraryAddresses);
}
/// @returns method identifiers in contract called @param _contractName.
Json methodIdentifiers(std::string const& _contractName)
{
return m_compiler.interfaceSymbols(_contractName)["methods"];
}
/// @returns Compilation output comprising EVM bytecode and list of
/// method identifiers in contract if compilation is successful,
/// null value otherwise.
std::optional<CompilerOutput> compileContract();
private:
frontend::CompilerStack m_compiler;
CompilerInput m_compilerInput;
};
class EvmoneUtility
{
public:
EvmoneUtility(
solidity::test::EVMHost& _evmHost,
CompilerInput _compilerInput,
std::string const& _contractName,
std::string const& _libraryName,
std::string const& _methodName
):
m_evmHost(_evmHost),
m_compilationFramework(_compilerInput),
m_contractName(_contractName),
m_libraryName(_libraryName),
m_methodName(_methodName)
{}
/// @returns the result returned by the EVM host on compiling, deploying,
/// and executing test configuration.
/// @param _isabelleData contains encoding data to be passed to the
/// isabelle test entry point.
evmc::Result compileDeployAndExecute(std::string _isabelleData = {});
/// Compares the contents of the memory address pointed to
/// by `_result` of `_length` bytes to u256 zero.
/// @returns true if `_result` is zero, false
/// otherwise.
static bool zeroWord(uint8_t const* _result, size_t _length);
/// @returns an evmc_message with all of its fields zero
/// initialized except gas and input fields.
/// The gas field is set to the maximum permissible value so that we
/// don't run into out of gas errors. The input field is copied from
/// @param _input.
static evmc_message initializeMessage(bytes const& _input);
private:
/// @returns the result of the execution of the function whose
/// keccak256 hash is @param _functionHash that is deployed at
/// @param _deployedAddress in @param _hostContext.
evmc::Result executeContract(
bytes const& _functionHash,
evmc_address _deployedAddress
);
/// @returns the result of deployment of @param _code on @param _hostContext.
evmc::Result deployContract(bytes const& _code);
/// Deploys and executes EVM byte code in @param _byteCode on
/// EVM Host referenced by @param _hostContext. Input passed
/// to execution context is @param _hexEncodedInput.
/// @returns result returning by @param _hostContext.
evmc::Result deployAndExecute(
bytes const& _byteCode,
std::string const& _hexEncodedInput
);
/// Compiles contract named @param _contractName present in
/// @param _sourceCode, optionally using a precompiled library
/// specified via a library mapping and an optimisation setting.
/// @returns a pair containing the generated byte code and method
/// identifiers for methods in @param _contractName.
std::optional<CompilerOutput> compileContract();
/// EVM Host implementation
solidity::test::EVMHost& m_evmHost;
/// Solidity compilation framework
SolidityCompilationFramework m_compilationFramework;
/// Contract name
std::string m_contractName;
/// Library name
std::string m_libraryName;
/// Method name
std::string m_methodName;
};
}
| 5,752
|
C++
|
.h
| 159
| 34.062893
| 85
| 0.773754
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,319
|
YulEvmoneInterface.h
|
ethereum_solidity/test/tools/ossfuzz/YulEvmoneInterface.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <test/EVMHost.h>
#include <libyul/YulStack.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <liblangutil/DebugInfoSelection.h>
namespace solidity::test::fuzzer
{
class YulAssembler
{
public:
YulAssembler(
langutil::EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
solidity::frontend::OptimiserSettings _optSettings,
std::string const& _yulSource
):
m_stack(
_evmVersion,
_eofVersion,
solidity::yul::YulStack::Language::StrictAssembly,
_optSettings,
langutil::DebugInfoSelection::All()
),
m_yulProgram(_yulSource),
m_optimiseYul(_optSettings.runYulOptimiser)
{}
solidity::bytes assemble();
std::shared_ptr<yul::Object> object();
private:
solidity::yul::YulStack m_stack;
std::string m_yulProgram;
bool m_optimiseYul;
};
struct YulEvmoneUtility
{
/// @returns the result of deploying bytecode @param _input on @param _host.
static evmc::Result deployCode(solidity::bytes const& _input, EVMHost& _host);
/// @returns call message to be sent to @param _address.
static evmc_message callMessage(evmc_address _address);
/// @returns true if call result indicates a serious error, false otherwise.
static bool seriousCallError(evmc_status_code _code);
};
}
| 1,933
|
C++
|
.h
| 56
| 31.75
| 79
| 0.763792
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,320
|
yulFuzzerCommon.h
|
ethereum_solidity/test/tools/ossfuzz/yulFuzzerCommon.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <test/tools/yulInterpreter/Interpreter.h>
#include <libyul/backends/evm/EVMDialect.h>
namespace solidity::yul::test::yul_fuzzer
{
struct yulFuzzerUtil
{
enum class TerminationReason
{
ExplicitlyTerminated,
StepLimitReached,
TraceLimitReached,
ExpresionNestingLimitReached,
None
};
/// Interprets the Yul AST pointed to by @param _ast. Flag @param _outputStorageOnly
/// (unset by default) outputs an execution trace of both memory and storage;
/// if set, only storage contents are output as part of the execution trace. The
/// latter avoids false positives that will be produced by the fuzzer when certain
/// optimizer steps are activated e.g., Redundant store eliminator, Equal store
/// eliminator.
static TerminationReason interpret(
std::ostream& _os,
yul::Block const& _astRoot,
Dialect const& _dialect,
bool _disableMemoryTracing = false,
bool _outputStorageOnly = false,
size_t _maxSteps = maxSteps,
size_t _maxTraceSize = maxTraceSize,
size_t _maxExprNesting = maxExprNesting
);
/// @returns true if @param _reason for Yul interpreter terminating is
/// resource exhaustion of some form e.g., exceeded maximum time-out
/// threshold, number of nested expressions etc.
static bool resourceLimitsExceeded(TerminationReason _reason);
static size_t constexpr maxSteps = 100;
static size_t constexpr maxTraceSize = 75;
static size_t constexpr maxExprNesting = 64;
};
}
| 2,118
|
C++
|
.h
| 53
| 37.773585
| 85
| 0.782207
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,324
|
SolidityCustomMutatorInterface.h
|
ethereum_solidity/test/tools/ossfuzz/SolidityCustomMutatorInterface.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Implements libFuzzer's custom mutator interface.
*/
#pragma once
#include <test/tools/ossfuzz/SolidityGenerator.h>
#include <memory>
namespace solidity::test::fuzzer::mutator
{
struct SolidityCustomMutatorInterface
{
SolidityCustomMutatorInterface(uint8_t* _data, size_t _size, size_t _maxSize, unsigned _seed);
/// Generates Solidity test program, copies it into buffer
/// provided by libFuzzer and @returns size of the test program.
size_t generate();
/// Raw pointer to libFuzzer provided input
uint8_t* data;
/// Size of libFuzzer provided input
size_t size;
/// Maximum length of mutant specified by libFuzzer
size_t maxMutantSize;
/// Solidity generator handle
std::shared_ptr<SolidityGenerator> generator;
};
}
| 1,429
|
C++
|
.h
| 38
| 35.736842
| 95
| 0.784526
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,325
|
YulProtoMutator.h
|
ethereum_solidity/test/tools/ossfuzz/protomutators/YulProtoMutator.h
|
#pragma once
#include <test/tools/ossfuzz/yulProto.pb.h>
#include <libsolutil/Common.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <random>
namespace solidity::yul::test::yul_fuzzer
{
using ProtobufMessage = google::protobuf::Message;
template <typename Proto>
using LPMPostProcessor = protobuf_mutator::libfuzzer::PostProcessorRegistration<Proto>;
class MutationInfo: public ScopeGuard
{
public:
MutationInfo(ProtobufMessage const* _message, std::string const& _info);
static void writeLine(std::string const& _str)
{
std::cout << _str << std::endl;
}
void exitInfo();
ProtobufMessage const* m_protobufMsg;
};
struct YulRandomNumGenerator
{
using RandomEngine = std::minstd_rand;
explicit YulRandomNumGenerator(unsigned _seed): m_random(RandomEngine(_seed)) {}
unsigned operator()()
{
return static_cast<unsigned>(m_random());
}
RandomEngine m_random;
};
struct YulProtoMutator
{
/// @param _value: Value of the integer literal
/// @returns an integer literal protobuf message initialized with
/// the given value.
static Literal* intLiteral(unsigned _value);
/// @param _seed: Pseudo-random unsigned integer used as index
/// of variable to be referenced
/// @returns a variable reference protobuf message.
static VarRef* varRef(unsigned _seed);
/// @param _value: value of literal expression
/// @returns an expression protobuf message
static Expression* litExpression(unsigned _value);
/// @param _rand: Pseudo-random number generator
/// of variable to be referenced
/// @returns a variable reference protobuf message
static Expression* refExpression(YulRandomNumGenerator& _rand);
/// Helper type for type matching visitor.
template<class T> struct AlwaysFalse: std::false_type {};
/// Template struct for obtaining a valid enum value of
/// template type from a pseudo-random unsigned integer.
/// @param _seed: Pseudo-random integer
/// @returns Valid enum of enum type T
template <typename T>
struct EnumTypeConverter
{
T enumFromSeed(unsigned _seed)
{
return validEnum(_seed);
}
/// @returns a valid enum of type T from _seed
T validEnum(unsigned _seed);
/// @returns maximum enum value for enum of type T
static unsigned enumMax();
/// @returns minimum enum value for enum of type T
static unsigned enumMin();
};
/// Modulo for mutations that should occur rarely
static constexpr unsigned s_lowIP = 31;
/// Modulo for mutations that should occur not too often
static constexpr unsigned s_mediumIP = 29;
/// Modulo for mutations that should occur often
static constexpr unsigned s_highIP = 23;
/// Add control-flow statement to basic block.
template <typename T>
static void addControlFlow(T* _msg, unsigned _seed);
/// Obtain basic block for statement type.
template <typename T>
static Block* basicBlock(T* _msg, unsigned _seed);
/// Obtain a basic block in a for stmt uniformly
/// at random
static Block* randomBlock(ForStmt* _msg, unsigned _seed);
/// Obtain a basic block in global scope.
static Block* globalBlock(Program* _program);
};
}
| 3,066
|
C++
|
.h
| 87
| 33.08046
| 87
| 0.76023
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,326
|
EVMInstructionInterpreter.h
|
ethereum_solidity/test/tools/yulInterpreter/EVMInstructionInterpreter.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul interpreter module that evaluates EVM instructions.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/FixedHash.h>
#include <libsolutil/Numeric.h>
#include <liblangutil/EVMVersion.h>
#include <vector>
namespace solidity::evmasm
{
enum class Instruction: uint8_t;
}
namespace solidity::yul
{
class YulString;
struct BuiltinFunctionForEVM;
}
namespace solidity::yul::test
{
/// Copy @a _size bytes of @a _source at offset @a _sourceOffset to
/// @a _target at offset @a _targetOffset. Behaves as if @a _source would
/// continue with an infinite sequence of zero bytes beyond its end.
void copyZeroExtended(
std::map<u256, uint8_t>& _target,
bytes const& _source,
size_t _targetOffset,
size_t _sourceOffset,
size_t _size
);
/// Copy @a _size bytes of @a _source at offset @a _sourceOffset to
/// @a _target at offset @a _targetOffset. Behaves as if @a _source would
/// continue with an infinite sequence of zero bytes beyond its end.
/// When target and source areas overlap, behaves as if the data was copied
/// using an intermediate buffer.
void copyZeroExtendedWithOverlap(
std::map<u256, uint8_t>& _target,
std::map<u256, uint8_t> const& _source,
size_t _targetOffset,
size_t _sourceOffset,
size_t _size
);
struct InterpreterState;
/**
* Interprets EVM instructions based on the current state and logs instructions with
* side-effects.
*
* Since this is mainly meant to be used for differential fuzz testing, it is focused
* on a single contract only, does not do any gas counting and differs from the correct
* implementation in many ways:
*
* - If memory access to a "large" memory position is performed, a deterministic
* value is returned. Data that is stored in a "large" memory position is not
* retained.
* - The blockhash instruction returns a fixed value if the argument is in range.
* - Extcodesize returns a deterministic value depending on the address.
* - Extcodecopy copies a deterministic value depending on the address.
* - And many other things
*
* The main focus is that the generated execution trace is the same for equivalent executions
* and likely to be different for non-equivalent executions.
*/
class EVMInstructionInterpreter
{
public:
explicit EVMInstructionInterpreter(langutil::EVMVersion _evmVersion, InterpreterState& _state, bool _disableMemWriteTrace):
m_evmVersion(_evmVersion),
m_state(_state),
m_disableMemoryWriteInstructions(_disableMemWriteTrace)
{}
/// Evaluate instruction
u256 eval(evmasm::Instruction _instruction, std::vector<u256> const& _arguments);
/// Evaluate builtin function
u256 evalBuiltin(
BuiltinFunctionForEVM const& _fun,
std::vector<Expression> const& _arguments,
std::vector<u256> const& _evaluatedArguments
);
/// @returns the blob versioned hash
util::h256 blobHash(u256 const& _index);
private:
/// Checks if the memory access is valid and adjusts msize accordingly.
/// @returns true if memory access is valid, false otherwise
/// A valid memory access must satisfy all of the following pre-requisites:
/// - Sum of @param _offset and @param _size do not overflow modulo u256
/// - Sum of @param _offset, @param _size, and 31 do not overflow modulo u256 (see note below)
/// - @param _size is lesser than or equal to @a s_maxRangeSize
/// - @param _offset is lesser than or equal to the difference of numeric_limits<size_t>::max()
/// and @a s_maxRangeSize
/// Note: Memory expansion is carried out in multiples of 32 bytes.
bool accessMemory(u256 const& _offset, u256 const& _size = 32);
/// @returns the memory contents at the provided address.
/// Does not adjust msize, use @a accessMemory for that
bytes readMemory(u256 const& _offset, u256 const& _size = 32);
/// @returns the memory contents at the provided address.
/// Does not adjust msize, use @a accessMemory for that
u256 readMemoryWord(u256 const& _offset);
/// @returns writes a word to memory
/// Does not adjust msize, use @a accessMemory for that
void writeMemoryWord(u256 const& _offset, u256 const& _value);
void logTrace(
evmasm::Instruction _instruction,
std::vector<u256> const& _arguments = {},
bytes const& _data = {}
);
/// Appends a log to the trace representing an instruction or similar operation by string,
/// with arguments and auxiliary data (if nonempty). Flag @param _writesToMemory indicates
/// whether the instruction writes to (true) or does not write to (false) memory.
void logTrace(
std::string const& _pseudoInstruction,
bool _writesToMemory,
std::vector<u256> const& _arguments = {},
bytes const& _data = {}
);
/// @returns a pair of boolean and size_t whose first value is true if @param _pseudoInstruction
/// is a Yul instruction that the Yul optimizer's loadResolver step rewrites the input
/// memory pointer value to zero if that instruction's read length (contained within @param
// _arguments) is zero, and whose second value is the positional index of the input memory
// pointer argument.
/// If the Yul instruction is unaffected or affected but read length is non-zero, the first
/// value is false.
std::pair<bool, size_t> isInputMemoryPtrModified(
std::string const& _pseudoInstruction,
std::vector<u256> const& _arguments
);
/// @returns disable trace flag.
bool memWriteTracingDisabled()
{
return m_disableMemoryWriteInstructions;
}
langutil::EVMVersion m_evmVersion;
InterpreterState& m_state;
/// Flag to disable trace of instructions that write to memory.
bool m_disableMemoryWriteInstructions;
public:
/// Maximum length for range-based memory access operations.
static constexpr unsigned s_maxRangeSize = 0xffff;
};
} // solidity::yul::test
| 6,409
|
C++
|
.h
| 154
| 39.649351
| 124
| 0.762715
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,327
|
Interpreter.h
|
ethereum_solidity/test/tools/yulInterpreter/Interpreter.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul interpreter.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/optimiser/ASTWalker.h>
#include <libevmasm/Instruction.h>
#include <libsolutil/FixedHash.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Exceptions.h>
#include <map>
namespace solidity::yul
{
struct Dialect;
}
namespace solidity::yul::test
{
class InterpreterTerminatedGeneric: public util::Exception
{
};
class ExplicitlyTerminated: public InterpreterTerminatedGeneric
{
};
class ExplicitlyTerminatedWithReturn: public ExplicitlyTerminated
{
};
class StepLimitReached: public InterpreterTerminatedGeneric
{
};
class TraceLimitReached: public InterpreterTerminatedGeneric
{
};
class ExpressionNestingLimitReached: public InterpreterTerminatedGeneric
{
};
enum class ControlFlowState
{
Default,
Continue,
Break,
Leave
};
struct InterpreterState
{
bytes calldata;
bytes returndata;
std::map<u256, uint8_t> memory;
/// This is different than memory.size() because we ignore gas.
u256 msize;
std::map<util::h256, util::h256> storage;
std::map<util::h256, util::h256> transientStorage;
util::h160 address = util::h160("0x0000000000000000000000000000000011111111");
u256 balance = 0x22222222;
u256 selfbalance = 0x22223333;
util::h160 origin = util::h160("0x0000000000000000000000000000000033333333");
util::h160 caller = util::h160("0x0000000000000000000000000000000044444444");
u256 callvalue = 0x55555555;
/// Deployed code
bytes code = util::asBytes("codecodecodecodecode");
u256 gasprice = 0x66666666;
util::h160 coinbase = util::h160("0x0000000000000000000000000000000077777777");
u256 timestamp = 0x88888888;
u256 blockNumber = 1024;
u256 difficulty = 0x9999999;
u256 prevrandao = (u256(1) << 64) + 1;
u256 gaslimit = 4000000;
u256 chainid = 0x01;
/// The minimum value of basefee: 7 wei.
u256 basefee = 0x07;
/// The minimum value of blobbasefee: 1 wei.
u256 blobbasefee = 0x01;
/// Log of changes / effects. Sholud be structured data in the future.
std::vector<std::string> trace;
/// This is actually an input parameter that more or less limits the runtime.
size_t maxTraceSize = 0;
size_t maxSteps = 0;
size_t numSteps = 0;
size_t maxExprNesting = 0;
ControlFlowState controlFlowState = ControlFlowState::Default;
/// Number of the current state instance, used for recursion protection
size_t numInstance = 0;
// Blob commitment hash version
util::FixedHash<1> const blobHashVersion = util::FixedHash<1>(1);
// Blob commitments
std::array<u256, 2> const blobCommitments = {0x01, 0x02};
/// Prints execution trace and non-zero storage to @param _out.
/// Flag @param _disableMemoryTrace, if set, does not produce a memory dump. This
/// avoids false positives reports by the fuzzer when certain optimizer steps are
/// activated e.g., Redundant store eliminator, Equal store eliminator.
void dumpTraceAndState(std::ostream& _out, bool _disableMemoryTrace) const;
/// Prints non-zero storage to @param _out.
void dumpStorage(std::ostream& _out) const;
/// Prints non-zero transient storage to @param _out.
void dumpTransientStorage(std::ostream& _out) const;
bytes readMemory(u256 const& _offset, u256 const& _size)
{
yulAssert(_size <= 0xffff, "Too large read.");
bytes data(size_t(_size), uint8_t(0));
for (size_t i = 0; i < data.size(); ++i)
data[i] = memory[_offset + i];
return data;
}
};
/**
* Scope structure built and maintained during execution.
*/
struct Scope
{
/// Used for variables and functions. Value is nullptr for variables.
std::map<YulName, FunctionDefinition const*> names;
std::map<Block const*, std::unique_ptr<Scope>> subScopes;
Scope* parent = nullptr;
};
/**
* Yul interpreter.
*/
class Interpreter: public ASTWalker
{
public:
/// Executes the Yul interpreter. Flag @param _disableMemoryTracing if set ensures that
/// instructions that write to memory do not affect @param _state. This
/// avoids false positives reports by the fuzzer when certain optimizer steps are
/// activated e.g., Redundant store eliminator, Equal store eliminator.
static void run(
InterpreterState& _state,
Dialect const& _dialect,
Block const& _ast,
bool _disableExternalCalls,
bool _disableMemoryTracing
);
Interpreter(
InterpreterState& _state,
Dialect const& _dialect,
Scope& _scope,
bool _disableExternalCalls,
bool _disableMemoryTracing,
std::map<YulName, u256> _variables = {}
):
m_dialect(_dialect),
m_state(_state),
m_variables(std::move(_variables)),
m_scope(&_scope),
m_disableExternalCalls(_disableExternalCalls),
m_disableMemoryTrace(_disableMemoryTracing)
{
}
void operator()(ExpressionStatement const& _statement) override;
void operator()(Assignment const& _assignment) override;
void operator()(VariableDeclaration const& _varDecl) override;
void operator()(If const& _if) override;
void operator()(Switch const& _switch) override;
void operator()(FunctionDefinition const&) override;
void operator()(ForLoop const&) override;
void operator()(Break const&) override;
void operator()(Continue const&) override;
void operator()(Leave const&) override;
void operator()(Block const& _block) override;
bytes returnData() const { return m_state.returndata; }
std::vector<std::string> const& trace() const { return m_state.trace; }
u256 valueOfVariable(YulName _name) const { return m_variables.at(_name); }
protected:
/// Asserts that the expression evaluates to exactly one value and returns it.
virtual u256 evaluate(Expression const& _expression);
/// Evaluates the expression and returns its value.
virtual std::vector<u256> evaluateMulti(Expression const& _expression);
void enterScope(Block const& _block);
void leaveScope();
/// Increment interpreter step count, throwing exception if step limit
/// is reached.
void incrementStep();
Dialect const& m_dialect;
InterpreterState& m_state;
/// Values of variables.
std::map<YulName, u256> m_variables;
Scope* m_scope;
/// If not set, external calls (e.g. using `call()`) to the same contract
/// are evaluated in a new parser instance.
bool m_disableExternalCalls;
bool m_disableMemoryTrace;
};
/**
* Yul expression evaluator.
*/
class ExpressionEvaluator: public ASTWalker
{
public:
ExpressionEvaluator(
InterpreterState& _state,
Dialect const& _dialect,
Scope& _scope,
std::map<YulName, u256> const& _variables,
bool _disableExternalCalls,
bool _disableMemoryTrace
):
m_state(_state),
m_dialect(_dialect),
m_variables(_variables),
m_scope(_scope),
m_disableExternalCalls(_disableExternalCalls),
m_disableMemoryTrace(_disableMemoryTrace)
{}
void operator()(Literal const&) override;
void operator()(Identifier const&) override;
void operator()(FunctionCall const& _funCall) override;
/// Asserts that the expression has exactly one value and returns it.
u256 value() const;
/// Returns the list of values of the expression.
std::vector<u256> values() const { return m_values; }
protected:
void runExternalCall(evmasm::Instruction _instruction);
virtual std::unique_ptr<Interpreter> makeInterpreterCopy(std::map<YulName, u256> _variables = {}) const
{
return std::make_unique<Interpreter>(
m_state,
m_dialect,
m_scope,
m_disableExternalCalls,
m_disableMemoryTrace,
std::move(_variables)
);
}
virtual std::unique_ptr<Interpreter> makeInterpreterNew(InterpreterState& _state, Scope& _scope) const
{
return std::make_unique<Interpreter>(
_state,
m_dialect,
_scope,
m_disableExternalCalls,
m_disableMemoryTrace
);
}
void setValue(u256 _value);
/// Evaluates the given expression from right to left and
/// stores it in m_value.
void evaluateArgs(
std::vector<Expression> const& _expr,
std::vector<std::optional<LiteralKind>> const* _literalArguments
);
/// Increment evaluation count, throwing exception if the
/// nesting level is beyond the upper bound configured in
/// the interpreter state.
void incrementStep();
InterpreterState& m_state;
Dialect const& m_dialect;
/// Values of variables.
std::map<YulName, u256> const& m_variables;
Scope& m_scope;
/// Current value of the expression
std::vector<u256> m_values;
/// Current expression nesting level
unsigned m_nestingLevel = 0;
bool m_disableExternalCalls;
/// Flag to disable memory tracing
bool m_disableMemoryTrace;
};
}
| 9,034
|
C++
|
.h
| 270
| 31.288889
| 104
| 0.76416
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,328
|
Inspector.h
|
ethereum_solidity/test/tools/yulInterpreter/Inspector.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul inspector.
*/
#include <test/tools/yulInterpreter/Interpreter.h>
#include <libyul/AST.h>
#include <string>
#pragma once
namespace solidity::yul::test
{
/**
* Inspector class to respond to queries by the user for:
*
* * Stepping through and over instructions.
* * Printing a specific or all variables.
* * Inspecting memory, storage and calldata memory.
*/
class Inspector
{
public:
enum class NodeAction
{
RunNode,
StepThroughNode,
};
Inspector(std::string const& _source, InterpreterState const& _state)
:m_source(_source), m_state(_state) {}
/* Asks the user what action to take.
* @returns NodeAction::RunNode if the current AST node (and all children nodes!) should be
* processed without stopping, else NodeAction::StepThroughNode.
*/
NodeAction queryUser(langutil::DebugData const& _data, std::map<YulName, u256> const& _variables);
void stepMode(NodeAction _action) { m_stepMode = _action; }
std::string const& source() const { return m_source; }
void interactiveVisit(langutil::DebugData const& _debugData, std::map<YulName, u256> const& _variables, std::function<void()> _visitNode)
{
Inspector::NodeAction action = queryUser(_debugData, _variables);
if (action == NodeAction::RunNode)
{
// user requested to run the whole node without stopping
stepMode(Inspector::NodeAction::RunNode);
_visitNode();
// Reset step mode back
stepMode(Inspector::NodeAction::StepThroughNode);
}
else
_visitNode();
}
private:
std::string currentSource(langutil::DebugData const& _data) const;
/// Source of the file
std::string const& m_source;
/// State of the interpreter
InterpreterState const& m_state;
/// Last user query command
std::string m_lastInput;
/// Used to run AST nodes without user interaction
NodeAction m_stepMode = NodeAction::StepThroughNode;
};
/**
* Yul Interpreter with inspection. Allows the user to go through the code step
* by step and inspect the state using the `Inspector` class
*/
class InspectedInterpreter: public Interpreter
{
public:
static void run(
std::shared_ptr<Inspector> _inspector,
InterpreterState& _state,
Dialect const& _dialect,
Block const& _ast,
bool _disableExternalCalls,
bool _disableMemoryTracing
);
InspectedInterpreter(
std::shared_ptr<Inspector> _inspector,
InterpreterState& _state,
Dialect const& _dialect,
Scope& _scope,
bool _disableExternalCalls,
bool _disableMemoryTracing,
std::map<YulName, u256> _variables = {}
):
Interpreter(_state, _dialect, _scope, _disableExternalCalls, _disableMemoryTracing, _variables),
m_inspector(_inspector)
{
}
void operator()(ExpressionStatement const& _node) override { helper(_node); }
void operator()(Assignment const& _node) override { helper(_node); }
void operator()(VariableDeclaration const& _node) override { helper(_node); }
void operator()(If const& _node) override { helper(_node); }
void operator()(Switch const& _node) override { helper(_node); }
void operator()(ForLoop const& _node) override { helper(_node); }
void operator()(Break const& _node) override { helper(_node); }
void operator()(Continue const& _node) override { helper(_node); }
void operator()(Leave const& _node) override { helper(_node); }
void operator()(Block const& _node) override { helper(_node); }
protected:
/// Asserts that the expression evaluates to exactly one value and returns it.
u256 evaluate(Expression const& _expression) override;
/// Evaluates the expression and returns its value.
std::vector<u256> evaluateMulti(Expression const& _expression) override;
private:
std::shared_ptr<Inspector> m_inspector;
template <typename ConcreteNode>
void helper(ConcreteNode const& _node)
{
m_inspector->interactiveVisit(*_node.debugData, m_variables, [&]() {
Interpreter::operator()(_node);
});
}
};
class InspectedExpressionEvaluator: public ExpressionEvaluator
{
public:
InspectedExpressionEvaluator(
std::shared_ptr<Inspector> _inspector,
InterpreterState& _state,
Dialect const& _dialect,
Scope& _scope,
std::map<YulName, u256> const& _variables,
bool _disableExternalCalls,
bool _disableMemoryTrace
):
ExpressionEvaluator(_state, _dialect, _scope, _variables, _disableExternalCalls, _disableMemoryTrace),
m_inspector(_inspector)
{}
template <typename ConcreteNode>
void helper(ConcreteNode const& _node)
{
m_inspector->interactiveVisit(*_node.debugData, m_variables, [&]() {
ExpressionEvaluator::operator()(_node);
});
}
void operator()(Literal const& _node) override { helper(_node); }
void operator()(Identifier const& _node) override { helper(_node); }
void operator()(FunctionCall const& _node) override { helper(_node); }
protected:
std::unique_ptr<Interpreter> makeInterpreterCopy(std::map<YulName, u256> _variables = {}) const override
{
return std::make_unique<InspectedInterpreter>(
m_inspector,
m_state,
m_dialect,
m_scope,
m_disableExternalCalls,
m_disableMemoryTrace,
std::move(_variables)
);
}
std::unique_ptr<Interpreter> makeInterpreterNew(InterpreterState& _state, Scope& _scope) const override
{
return std::make_unique<InspectedInterpreter>(
std::make_unique<Inspector>(
m_inspector->source(),
_state
),
_state,
m_dialect,
_scope,
m_disableExternalCalls,
m_disableMemoryTrace
);
}
private:
std::shared_ptr<Inspector> m_inspector;
};
}
| 6,098
|
C++
|
.h
| 181
| 31.165746
| 138
| 0.746814
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,332
|
SSAControlFlowGraphTest.h
|
ethereum_solidity/test/libyul/SSAControlFlowGraphTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/TestCase.h>
#include <memory>
namespace solidity::yul
{
struct Dialect;
namespace test
{
class SSAControlFlowGraphTest: public solidity::frontend::test::TestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _config);
explicit SSAControlFlowGraphTest(std::string const& _filename);
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool const _formatted = false) override;
private:
Dialect const* m_dialect = nullptr;
};
}
}
| 1,191
|
C++
|
.h
| 33
| 34.363636
| 116
| 0.786771
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,333
|
YulOptimizerTest.h
|
ethereum_solidity/test/libyul/YulOptimizerTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/TestCase.h>
namespace solidity::langutil
{
class Error;
using ErrorList = std::vector<std::shared_ptr<Error const>>;
}
namespace solidity::yul
{
struct AsmAnalysisInfo;
class Object;
struct Dialect;
}
namespace solidity::yul::test
{
class YulOptimizerTest: public solidity::frontend::test::EVMVersionRestrictedTestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<YulOptimizerTest>(_config.filename);
}
explicit YulOptimizerTest(std::string const& _filename);
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool const _formatted = false) override;
private:
std::pair<std::shared_ptr<Object>, std::shared_ptr<AsmAnalysisInfo>> parse(
std::ostream& _stream, std::string const& _linePrefix, bool const _formatted, std::string const& _source
);
std::string m_optimizerStep;
Dialect const* m_dialect = nullptr;
std::shared_ptr<Object> m_object;
std::shared_ptr<AsmAnalysisInfo> m_analysisInfo;
};
}
| 1,716
|
C++
|
.h
| 48
| 33.895833
| 116
| 0.781609
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,336
|
ControlFlowGraphTest.h
|
ethereum_solidity/test/libyul/ControlFlowGraphTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/TestCase.h>
namespace solidity::yul
{
struct Dialect;
namespace test
{
class ControlFlowGraphTest: public solidity::frontend::test::TestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<ControlFlowGraphTest>(_config.filename);
}
explicit ControlFlowGraphTest(std::string const& _filename);
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool const _formatted = false) override;
private:
Dialect const* m_dialect = nullptr;
};
}
}
| 1,238
|
C++
|
.h
| 35
| 33.6
| 116
| 0.784937
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,339
|
YulOptimizerTestCommon.h
|
ethereum_solidity/test/libyul/YulOptimizerTestCommon.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/YulName.h>
#include <set>
#include <memory>
namespace solidity::yul
{
struct AsmAnalysisInfo;
class Object;
struct Dialect;
class AST;
}
namespace solidity::yul::test
{
class YulOptimizerTestCommon
{
public:
explicit YulOptimizerTestCommon(
std::shared_ptr<Object const> _obj,
Dialect const& _dialect
);
/// Sets optimiser step to be run to @param
/// _optimiserStep.
void setStep(std::string const& _optimizerStep);
/// Runs chosen optimiser step returning pointer
/// to yul AST Block post optimisation.
Block const* run();
/// Runs chosen optimiser step returning true if
/// successful, false otherwise.
bool runStep();
/// Returns the string name of a randomly chosen
/// optimiser step.
/// @param _seed is an unsigned integer that
/// seeds the random selection.
std::string randomOptimiserStep(unsigned _seed);
/// the resulting object after performing optimization steps
std::shared_ptr<Object> optimizedObject() const;
private:
Block disambiguate();
void updateContext(Block const& _block);
std::string m_optimizerStep;
Dialect const* m_dialect = nullptr;
std::set<YulName> m_reservedIdentifiers;
std::unique_ptr<NameDispenser> m_nameDispenser;
std::unique_ptr<OptimiserStepContext> m_context;
std::shared_ptr<Object const> m_object;
std::shared_ptr<Object> m_optimizedObject;
std::map<std::string, std::function<Block(void)>> m_namedSteps;
};
}
| 2,201
|
C++
|
.h
| 65
| 32
| 69
| 0.779557
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,342
|
StackShufflingTest.h
|
ethereum_solidity/test/libyul/StackShufflingTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/TestCase.h>
#include <libyul/backends/evm/ControlFlowGraph.h>
using namespace solidity::frontend::test;
namespace solidity::yul::test
{
class StackShufflingTest: public TestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<StackShufflingTest>(_config.filename);
}
explicit StackShufflingTest(std::string const& _filename);
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool const _formatted = false) override;
private:
bool parse(std::string const& _source);
Stack m_sourceStack;
Stack m_targetStack;
std::map<YulName, yul::FunctionCall> m_functions;
std::map<YulName, Scope::Variable> m_variables;
};
}
| 1,419
|
C++
|
.h
| 37
| 36.459459
| 116
| 0.783528
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,343
|
ASTJSONTest.h
|
ethereum_solidity/test/libsolidity/ASTJSONTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libsolutil/AnsiColorized.h>
#include <libsolidity/interface/CompilerStack.h>
#include <test/TestCase.h>
#include <iosfwd>
#include <string>
#include <vector>
#include <utility>
namespace solidity::frontend
{
class CompilerStack;
}
namespace solidity::frontend::test
{
class ASTJSONTest: public EVMVersionRestrictedTestCase
{
public:
struct TestVariant
{
TestVariant(std::string_view _baseName, CompilerStack::State _stopAfter):
baseName(_baseName),
stopAfter(_stopAfter)
{}
std::string name() const
{
return stopAfter == CompilerStack::State::Parsed ? "parseOnly" : "";
}
std::string astFilename() const
{
return std::string(baseName) +
(name().empty() ? "" : "_") +
name() +
".json";
}
std::string baseName;
CompilerStack::State stopAfter;
std::string result;
std::string expectation;
};
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<ASTJSONTest>(_config.filename);
}
ASTJSONTest(std::string const& _filename);
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool const _formatted = false) override;
void printSource(std::ostream& _stream, std::string const& _linePrefix = "", bool const _formatted = false) const override;
void printUpdatedExpectations(std::ostream& _stream, std::string const& _linePrefix) const override;
private:
bool runTest(
TestVariant& _testVariant,
std::map<std::string, unsigned> const& _sourceIndices,
CompilerStack& _compiler,
std::ostream& _stream,
std::string const& _linePrefix = "",
bool const _formatted = false
);
void updateExpectation(
std::string const& _filename,
std::string const& _expectation,
std::string const& _variant
) const;
void generateTestVariants(std::string const& _filename);
void fillSources(std::string const& _filename);
void validateTestConfiguration() const;
std::vector<TestVariant> m_variants;
std::optional<CompilerStack::State> m_expectedFailAfter;
std::vector<std::pair<std::string, std::string>> m_sources;
};
}
| 2,760
|
C++
|
.h
| 83
| 30.831325
| 124
| 0.754703
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,344
|
FunctionDependencyGraphTest.h
|
ethereum_solidity/test/libsolidity/FunctionDependencyGraphTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/libsolidity/AnalysisFramework.h>
#include <test/TestCase.h>
#include <test/CommonSyntaxTest.h>
#include <iosfwd>
#include <string>
#include <vector>
#include <utility>
namespace solidity::frontend::test
{
using solidity::test::SyntaxTestError;
class FunctionDependencyGraphTest: public AnalysisFramework, public TestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<FunctionDependencyGraphTest>(_config.filename);
}
FunctionDependencyGraphTest(std::string const& _filename): TestCase(_filename)
{
m_source = m_reader.source();
m_expectation = m_reader.simpleExpectations();
}
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool _formatted = false) override;
};
}
| 1,493
|
C++
|
.h
| 40
| 35.1
| 111
| 0.778933
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,345
|
MemoryGuardTest.h
|
ethereum_solidity/test/libsolidity/MemoryGuardTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/libsolidity/AnalysisFramework.h>
#include <test/TestCase.h>
#include <test/CommonSyntaxTest.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/AnsiColorized.h>
#include <iosfwd>
#include <string>
#include <vector>
#include <utility>
namespace solidity::frontend::test
{
using solidity::test::SyntaxTestError;
class MemoryGuardTest: public AnalysisFramework, public EVMVersionRestrictedTestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<MemoryGuardTest>(_config.filename);
}
MemoryGuardTest(std::string const& _filename): EVMVersionRestrictedTestCase(_filename)
{
m_source = m_reader.source();
m_expectation = m_reader.simpleExpectations();
}
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool _formatted = false) override;
protected:
void setupCompiler(CompilerStack& _compiler) override;
};
}
| 1,625
|
C++
|
.h
| 44
| 35.090909
| 110
| 0.792224
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,346
|
ASTPropertyTest.h
|
ethereum_solidity/test/libsolidity/ASTPropertyTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/TestCase.h>
#include <libsolutil/JSON.h>
#include <string>
#include <vector>
namespace solidity::frontend
{
class CompilerStack;
}
namespace solidity::frontend::test
{
using StringPair = std::pair<std::string, std::string>;
class ASTPropertyTest: public EVMVersionRestrictedTestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<ASTPropertyTest>(_config.filename);
}
ASTPropertyTest(std::string const& _filename);
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool const _formatted = false) override;
private:
struct Test
{
std::string property;
std::string expectedValue;
std::string obtainedValue;
};
void readExpectations();
std::vector<StringPair> readKeyValuePairs(std::string const& _input);
void extractTestsFromAST(Json const& _astJson);
std::string formatExpectations(bool _obtainedResult = true);
std::vector<std::string> m_testOrder;
std::map<std::string, Test> m_tests;
};
}
| 1,717
|
C++
|
.h
| 50
| 32.36
| 116
| 0.780739
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,347
|
SemanticTest.h
|
ethereum_solidity/test/libsolidity/SemanticTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <test/libsolidity/util/TestFileParser.h>
#include <test/libsolidity/util/TestFunctionCall.h>
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <test/libsolidity/AnalysisFramework.h>
#include <test/TestCase.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/AnsiColorized.h>
#include <iosfwd>
#include <string>
#include <vector>
#include <utility>
namespace solidity::frontend::test
{
struct AnnotatedEventSignature
{
std::string signature;
std::vector<std::string> indexedTypes;
std::vector<std::string> nonIndexedTypes;
};
enum class RequiresYulOptimizer
{
False,
MinimalStack,
Full,
};
std::ostream& operator<<(std::ostream& _output, RequiresYulOptimizer _requiresYulOptimizer);
/**
* Class that represents a semantic test (or end-to-end test) and allows running it as part of the
* boost unit test environment or isoltest. It reads the Solidity source and an additional comment
* section from the given file. This comment section should define a set of functions to be called
* and an expected result they return after being executed.
*/
class SemanticTest: public SolidityExecutionFramework, public EVMVersionRestrictedTestCase
{
public:
static std::unique_ptr<TestCase> create(Config const& _options)
{
return std::make_unique<SemanticTest>(
_options.filename,
_options.evmVersion,
_options.eofVersion,
_options.vmPaths,
_options.enforceGasCost,
_options.enforceGasCostMinValue
);
}
explicit SemanticTest(
std::string const& _filename,
langutil::EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
std::vector<boost::filesystem::path> const& _vmPaths,
bool _enforceGasCost = false,
u256 _enforceGasCostMinValue = 100000
);
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool _formatted = false) override;
void printSource(std::ostream &_stream, std::string const& _linePrefix = "", bool _formatted = false) const override;
void printUpdatedExpectations(std::ostream& _stream, std::string const& _linePrefix = "") const override;
void printUpdatedSettings(std::ostream& _stream, std::string const& _linePrefix = "") override;
/// Instantiates a test file parser that parses the additional comment section at the end of
/// the input stream \param _stream. Each function call is represented using a `FunctionCallTest`
/// and added to the list of call to be executed when `run()` is called.
/// Throws if parsing expectations failed.
void parseExpectations(std::istream& _stream);
/// Compiles and deploys currently held source.
/// Returns true if deployment was successful, false otherwise.
bool deploy(std::string const& _contractName, u256 const& _value, bytes const& _arguments, std::map<std::string, solidity::test::Address> const& _libraries = {});
private:
TestResult runTest(
std::ostream& _stream,
std::string const& _linePrefix,
bool _formatted,
bool _isYulRun
);
TestResult tryRunTestWithYulOptimizer(
std::ostream& _stream,
std::string const& _linePrefix,
bool _formatted
);
bool checkGasCostExpectation(TestFunctionCall& io_test, bool _compileViaYul) const;
std::map<std::string, Builtin> makeBuiltins();
std::vector<SideEffectHook> makeSideEffectHooks() const;
std::vector<std::string> eventSideEffectHook(FunctionCall const&) const;
std::optional<AnnotatedEventSignature> matchEvent(util::h256 const& hash) const;
static std::string formatEventParameter(std::optional<AnnotatedEventSignature> _signature, bool _indexed, size_t _index, bytes const& _data);
OptimiserSettings optimizerSettingsFor(RequiresYulOptimizer _requiresYulOptimizer);
SourceMap m_sources;
std::size_t m_lineOffset;
std::vector<TestFunctionCall> m_tests;
std::map<std::string, Builtin> const m_builtins;
std::vector<SideEffectHook> const m_sideEffectHooks;
bool m_testCaseWantsYulRun = true;
bool m_testCaseWantsLegacyRun = true;
bool m_runWithABIEncoderV1Only = false;
bool m_allowNonExistingFunctions = false;
bool m_gasCostFailure = false;
bool m_enforceGasCost = false;
RequiresYulOptimizer m_requiresYulOptimizer{};
u256 m_enforceGasCostMinValue;
};
}
| 4,792
|
C++
|
.h
| 114
| 39.921053
| 163
| 0.7855
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,349
|
OptimizedIRCachingTest.h
|
ethereum_solidity/test/libsolidity/OptimizedIRCachingTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Unit tests for the optimized IR caching in CompilerStack.
*/
#pragma once
#include <test/libsolidity/AnalysisFramework.h>
#include <test/TestCase.h>
#include <ostream>
#include <string>
namespace solidity::frontend::test
{
class OptimizedIRCachingTest: public AnalysisFramework, public EVMVersionRestrictedTestCase
{
public:
OptimizedIRCachingTest(std::string const& _filename):
EVMVersionRestrictedTestCase(_filename)
{
m_source = m_reader.source();
m_expectation = m_reader.simpleExpectations();
}
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<OptimizedIRCachingTest>(_config.filename);
}
TestResult run(std::ostream& _stream, std::string const& _linePrefix = "", bool _formatted = false) override;
protected:
void setupCompiler(CompilerStack& _compiler) override;
};
}
| 1,533
|
C++
|
.h
| 42
| 34.52381
| 110
| 0.788371
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,350
|
ABITestsCommon.h
|
ethereum_solidity/test/libsolidity/ABITestsCommon.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <string>
namespace solidity::frontend::test
{
#define NEW_ENCODER(CODE) \
{ \
std::string sourceCodeTmp = sourceCode; \
sourceCode = "pragma abicoder v2;\n" + sourceCode; \
{ CODE } \
sourceCode = sourceCodeTmp; \
}
#define OLD_ENCODER(CODE) \
{ \
std::string sourceCodeTmp = sourceCode; \
sourceCode = "pragma abicoder v1;\n" + sourceCode; \
{ CODE } \
sourceCode = sourceCodeTmp; \
}
#define BOTH_ENCODERS(CODE) \
{ \
OLD_ENCODER(CODE) \
NEW_ENCODER(CODE) \
}
} // end namespaces
| 1,192
|
C++
|
.h
| 37
| 30.405405
| 69
| 0.753927
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,351
|
SyntaxTest.h
|
ethereum_solidity/test/libsolidity/SyntaxTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/libsolidity/AnalysisFramework.h>
#include <test/TestCase.h>
#include <test/CommonSyntaxTest.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/AnsiColorized.h>
#include <iosfwd>
#include <string>
#include <vector>
#include <utility>
namespace solidity::frontend::test
{
using solidity::test::SyntaxTestError;
class SyntaxTest: public AnalysisFramework, public solidity::test::CommonSyntaxTest
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<SyntaxTest>(_config.filename, _config.evmVersion);
}
SyntaxTest(
std::string const& _filename,
langutil::EVMVersion _evmVersion,
langutil::Error::Severity _minSeverity = langutil::Error::Severity::Info
);
protected:
void setupCompiler(CompilerStack& _compiler) override;
void parseAndAnalyze() override;
virtual void filterObtainedErrors();
bool m_optimiseYul{};
std::string m_compileViaYul{};
langutil::Error::Severity m_minSeverity{};
PipelineStage m_stopAfter;
};
}
| 1,712
|
C++
|
.h
| 49
| 33.061224
| 83
| 0.793459
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,352
|
AnalysisFramework.h
|
ethereum_solidity/test/libsolidity/AnalysisFramework.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Framework for testing features from the analysis phase of compiler.
*/
#pragma once
#include <test/libsolidity/ErrorCheck.h>
#include <libsolidity/interface/CompilerStack.h>
#include <functional>
#include <string>
#include <memory>
namespace solidity::frontend
{
class Type;
class FunctionType;
using FunctionTypePointer = FunctionType const*;
}
namespace solidity::frontend::test
{
enum class PipelineStage {
Parsing,
Analysis,
Compilation,
};
class AnalysisFramework
{
protected:
virtual ~AnalysisFramework() = default;
/// Runs analysis via runFramework() and returns either an AST or a filtered list of errors.
/// Uses Boost test macros to fail if errors do not occur specifically at the analysis stage.
///
/// @deprecated This is a legacy helper. Use runFramework() directly in new tests.
///
/// @param _includeWarningsAndInfos Do not remove warning and info messages from the error list.
/// @param _addPreamble Apply withPreamble() to @p _source.
/// @param _allowMultiple When false, use Boost test macros to fail when there's more
/// than one item on the error list.
std::pair<SourceUnit const*, langutil::ErrorList> runAnalysisAndExpectNoParsingErrors(
std::string const& _source,
bool _includeWarningsAndInfos = false,
bool _addPreamble = true,
bool _allowMultiple = false
);
/// Runs analysis via runAnalysisAndExpectNoParsingErrors() and returns the list of errors.
/// Uses Boost test macros to fail if there are no errors.
///
/// @deprecated This is a legacy helper. Use runFramework() directly in new tests.
///
/// @param _includeWarningsAndInfos Do not remove warning and info messages from the error list.
/// @param _allowMultiple When false, use Boost test macros to fail when there's more
/// than one item on the error list.
langutil::ErrorList runAnalysisAndExpectError(
std::string const& _source,
bool _includeWarningsAndInfos = false,
bool _allowMultiple = false
);
public:
/// Runs the full compiler pipeline on specified sources. This is the main function of the
/// framework. Resets the stack, configures it and runs either until the first failed stage or
/// until the @p _targetStage is reached.
/// Afterwards the caller can inspect the stack via @p compiler(). The framework provides a few
/// convenience helpers to check the state and error list, in general the caller can freely
/// access the stack, including generating outputs if the compilation succeeded.
bool runFramework(StringMap _sources, PipelineStage _targetStage = PipelineStage::Compilation);
bool runFramework(std::string _source, PipelineStage _targetStage = PipelineStage::Compilation)
{
return runFramework({{"", std::move(_source)}}, _targetStage);
}
void resetFramework();
PipelineStage targetStage() const { return m_targetStage; }
bool pipelineSuccessful() const { return stageSuccessful(m_targetStage); }
bool stageSuccessful(PipelineStage _stage) const;
std::string formatErrors(
langutil::ErrorList const& _errors,
bool _colored = false,
bool _withErrorIds = false
) const;
std::string formatError(
langutil::Error const& _error,
bool _colored = false,
bool _withErrorIds = false
) const;
static ContractDefinition const* retrieveContractByName(SourceUnit const& _source, std::string const& _name);
static FunctionTypePointer retrieveFunctionBySignature(
ContractDefinition const& _contract,
std::string const& _signature
);
/// filter out the warnings in m_warningsToFilter or all warnings and infos if _includeWarningsAndInfos is false
langutil::ErrorList filterErrors(langutil::ErrorList const& _errorList, bool _includeWarningsAndInfos = true) const;
langutil::ErrorList filteredErrors(bool _includeWarningsAndInfos = true) const
{
return filterErrors(compiler().errors(), _includeWarningsAndInfos);
}
/// @returns reference to lazy-instantiated CompilerStack.
solidity::frontend::CompilerStack& compiler()
{
if (!m_compiler)
m_compiler = createStack();
return *m_compiler;
}
/// @returns reference to lazy-instantiated CompilerStack.
solidity::frontend::CompilerStack const& compiler() const
{
if (!m_compiler)
m_compiler = createStack();
return *m_compiler;
}
protected:
/// Creates a new instance of @p CompilerStack. Override if your test case needs to pass in
/// custom constructor arguments.
virtual std::unique_ptr<CompilerStack> createStack() const;
/// Configures @p CompilerStack. The default implementation sets basic parameters based on
/// CLI options. Override if your test case needs extra configuration.
virtual void setupCompiler(CompilerStack& _compiler);
/// Executes the requested pipeline stages until @p m_targetStage is reached.
/// Stops at the first failed stage.
void executeCompilationPipeline();
std::vector<std::string> m_warningsToFilter = {"This is a pre-release compiler version"};
std::vector<std::string> m_messagesToCut = {"Source file requires different compiler version (current compiler is"};
private:
mutable std::unique_ptr<solidity::frontend::CompilerStack> m_compiler;
PipelineStage m_targetStage = PipelineStage::Compilation;
};
// Asserts that the compilation down to typechecking
// emits multiple errors of different types and messages, provided in the second argument.
#define CHECK_ALLOW_MULTI(text, expectations) \
do \
{ \
ErrorList errors = runAnalysisAndExpectError((text), true, true); \
auto message = searchErrors(errors, (expectations)); \
BOOST_CHECK_MESSAGE(message.empty(), message); \
} while(0)
#define CHECK_ERROR_OR_WARNING(text, typ, substrings, includeWarningsAndInfos, allowMulti) \
do \
{ \
ErrorList errors = runAnalysisAndExpectError((text), (includeWarningsAndInfos), (allowMulti)); \
std::vector<std::pair<Error::Type, std::string>> expectations; \
for (auto const& str: substrings) \
expectations.emplace_back((Error::Type::typ), str); \
auto message = searchErrors(errors, expectations); \
BOOST_CHECK_MESSAGE(message.empty(), message); \
} while(0)
// [checkError(text, type, substring)] asserts that the compilation down to typechecking
// emits an error of type [type] and with a message containing [substring].
#define CHECK_ERROR(text, type, substring) \
CHECK_ERROR_OR_WARNING(text, type, std::vector<std::string>{(substring)}, false, false)
// [checkError(text, type, substring)] asserts that the compilation down to typechecking
// emits multiple errors of the same type [type] and with a messages containing [substrings].
// Because of the limitations of the preprocessor, you cannot use {{T1, "abc"}, {T2, "def"}} as arguments,
// but have to replace them by (std::vector<std::pair<Error::Type, std::string>>{"abc", "def"})
// (note the parentheses)
#define CHECK_ERROR_ALLOW_MULTI(text, type, substrings) \
CHECK_ERROR_OR_WARNING(text, type, substrings, false, true)
// [checkWarning(text, substring)] asserts that the compilation down to typechecking
// emits a warning and with a message containing [substring].
#define CHECK_WARNING(text, substring) \
CHECK_ERROR_OR_WARNING(text, Warning, std::vector<std::string>{(substring)}, true, false)
// [checkWarningAllowMulti(text, substring)] asserts that the compilation down to typechecking
// emits a warning and with a message containing [substring].
// Because of the limitations of the preprocessor, you cannot use {"abc", "def"} as arguments,
// but have to replace them by (std::vector<std::string>{"abc", "def"}) (note the parentheses)
#define CHECK_WARNING_ALLOW_MULTI(text, substrings) \
CHECK_ERROR_OR_WARNING(text, Warning, substrings, true, true)
// [checkSuccess(text)] asserts that the compilation down to typechecking succeeds.
#define CHECK_SUCCESS(text) do { \
auto [ast, errors] = runAnalysisAndExpectNoParsingErrors((text)); \
BOOST_CHECK(errors.empty()); \
} while(0)
#define CHECK_SUCCESS_NO_WARNINGS(text) \
do \
{ \
auto [ast, errors] = runAnalysisAndExpectNoParsingErrors((text), true); \
std::string message; \
if (!errors.empty()) \
message = formatErrors(errors);\
BOOST_CHECK_MESSAGE(errors.empty(), message); \
} \
while(0)
}
| 8,788
|
C++
|
.h
| 191
| 44.031414
| 117
| 0.767551
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,353
|
SMTCheckerTest.h
|
ethereum_solidity/test/libsolidity/SMTCheckerTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/libsolidity/SyntaxTest.h>
#include <libsmtutil/SolverInterface.h>
#include <libsolidity/formal/ModelChecker.h>
#include <libsolidity/interface/SMTSolverCommand.h>
#include <libsolidity/interface/UniversalCallback.h>
#include <string>
namespace solidity::frontend::test
{
class SMTCheckerTest: public SyntaxTest
{
public:
static std::unique_ptr<TestCase> create(Config const& _config)
{
return std::make_unique<SMTCheckerTest>(_config.filename);
}
explicit SMTCheckerTest(std::string const& _filename);
void setupCompiler(CompilerStack& _compiler) override;
void filterObtainedErrors() override;
void printUpdatedExpectations(std::ostream& _stream, std::string const& _linePrefix) const override;
protected:
std::unique_ptr<CompilerStack> createStack() const override;
/*
Options that can be set in the test:
SMTEngine: `all`, `chc`, `bmc`, `none`, where the default is `all`.
Set in m_modelCheckerSettings.
SMTIgnoreCex: `yes`, `no`, where the default is `no`.
Set in m_ignoreCex.
SMTIgnoreInv: `yes`, `no`, where the default is `no`.
Set in m_modelCheckerSettings.
SMTShowProvedSafe: `yes`, `no`, where the default is `no`.
Set in m_modelCheckerSettings.
SMTShowUnproved: `yes`, `no`, where the default is `yes`.
Set in m_modelCheckerSettings.
SMTSolvers: `all`, `cvc5`, `z3`, `eld`, `none`, where the default is `z3`.
Set in m_modelCheckerSettings.
BMCLoopIterations: number of loop iterations for BMC engine, the default is 1.
Set in m_modelCheckerSettings.
*/
ModelCheckerSettings m_modelCheckerSettings;
bool m_ignoreCex = false;
std::vector<SyntaxTestError> m_unfilteredErrorList;
SMTSolverCommand smtCommand;
UniversalCallback universalCallback;
};
}
| 2,427
|
C++
|
.h
| 60
| 38.283333
| 101
| 0.782275
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,357
|
NatspecJSONTest.h
|
ethereum_solidity/test/libsolidity/NatspecJSONTest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Unit tests for the Natspec userdoc and devdoc JSON output.
*/
#pragma once
#include <test/libsolidity/SyntaxTest.h>
#include <libsolutil/JSON.h>
#include <istream>
#include <map>
#include <memory>
#include <ostream>
#include <string>
#include <string_view>
#include <tuple>
namespace solidity::frontend::test
{
enum class NatspecJSONKind
{
Devdoc,
Userdoc,
};
std::ostream& operator<<(std::ostream& _output, NatspecJSONKind _kind);
using NatspecMap = std::map<std::string, std::map<NatspecJSONKind, Json>>;
using SerializedNatspecMap = std::map<std::string, std::map<NatspecJSONKind, std::string>>;
class NatspecJSONTest: public SyntaxTest
{
public:
static std::unique_ptr<TestCase> create(Config const& _config);
NatspecJSONTest(std::string const& _filename, langutil::EVMVersion _evmVersion):
SyntaxTest(
_filename,
_evmVersion,
langutil::Error::Severity::Error // _minSeverity
)
{}
protected:
void parseCustomExpectations(std::istream& _stream) override;
bool expectationsMatch() override;
void printExpectedResult(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const override;
void printObtainedResult(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const override;
NatspecMap m_expectedNatspecJSON;
private:
static std::tuple<std::string_view, NatspecJSONKind> parseExpectationHeader(std::string_view _line);
static std::string extractExpectationJSON(std::istream& _stream);
static std::string_view expectLinePrefix(std::string_view _line);
std::string formatNatspecExpectations(NatspecMap const& _expectations) const;
SerializedNatspecMap prettyPrinted(NatspecMap const& _expectations) const;
NatspecMap obtainedNatspec() const;
};
}
| 2,427
|
C++
|
.h
| 63
| 36.555556
| 113
| 0.788486
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,362
|
TestFunctionCall.h
|
ethereum_solidity/test/libsolidity/util/TestFunctionCall.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <test/libsolidity/util/TestFileParser.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <test/libsolidity/util/ContractABIUtils.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/AnsiColorized.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/JSON.h>
#include <iosfwd>
#include <numeric>
#include <stdexcept>
#include <string>
#include <vector>
namespace solidity::frontend::test
{
/**
* Represents a function call and the result it returned. It stores the call
* representation itself, the actual byte result (if any) and a string representation
* used for the interactive update routine provided by isoltest. It also provides
* functionality to compare the actual result with the expectations attached to the
* call object, as well as a way to reset the result if executed multiple times.
*/
class TestFunctionCall
{
public:
enum class RenderMode
{
ExpectedValuesExpectedGas,
ActualValuesExpectedGas,
ExpectedValuesActualGas
};
TestFunctionCall(FunctionCall _call):
m_call(std::move(_call)),
m_gasCostsExcludingCode(m_call.expectations.gasUsedExcludingCode),
m_codeDepositGasCosts(m_call.expectations.gasUsedForCodeDeposit)
{}
/// Formats this function call test and applies the format that was detected during parsing.
/// _renderMode determines the source of values to be inserted into the updated test expectations.
/// RenderMode::ActualValuesExpectedGas: use the values produced by the test but for gas preserve the original expectations,
/// RenderMode::ExpectedValuesExpectedGas: preserve the original expectations for both gas and other values,
/// RenderMode::ExpectedValuesActualGas: use the original expectations but for gas use actual values,
/// If _highlight is false, it's formatted without colorized highlighting. If it's true, AnsiColorized is
/// used to apply a colorized highlighting.
/// If _interactivePrint is true, we are producing output that will be interactively shown to the user
/// in the terminal rather than used to update the expectations in the test file.
/// If test expectations do not match, the contract ABI is consulted in order to get the
/// right encoding for returned bytes, based on the parsed return types.
/// Reports warnings and errors to the error reporter.
std::string format(
ErrorReporter& _errorReporter,
std::string const& _linePrefix = "",
RenderMode _renderMode = RenderMode::ExpectedValuesExpectedGas,
bool const _highlight = false,
bool const _interactivePrint = false
) const;
/// Overloaded version that passes an error reporter which is never used outside
/// of this function.
std::string format(
std::string const& _linePrefix = "",
RenderMode const _renderMode = RenderMode::ExpectedValuesExpectedGas,
bool const _highlight = false
) const
{
ErrorReporter reporter;
return format(reporter, _linePrefix, _renderMode, _highlight);
}
/// Resets current results in case the function was called and the result
/// stored already (e.g. if test case was updated via isoltest).
void reset();
FunctionCall const& call() const { return m_call; }
void calledNonExistingFunction() { m_calledNonExistingFunction = true; }
void setFailure(const bool _failure) { m_failure = _failure; }
void setRawBytes(const bytes _rawBytes) { m_rawBytes = _rawBytes; }
void setGasCostExcludingCode(std::string const& _runType, u256 const& _gasCost) { m_gasCostsExcludingCode[_runType] = _gasCost; }
void setCodeDepositGasCost(std::string const& _runType, u256 const& _gasCost) { m_codeDepositGasCosts[_runType] = _gasCost; }
void setContractABI(Json _contractABI) { m_contractABI = std::move(_contractABI); }
void setSideEffects(std::vector<std::string> _sideEffects) { m_call.actualSideEffects = _sideEffects; }
private:
/// Tries to format the given `bytes`, applying the detected ABI types that have be set for each parameter.
/// Throws if there's a mismatch in the size of `bytes` and the desired formats that are specified
/// in the ABI type.
/// Reports warnings and errors to the error reporter.
std::string formatBytesParameters(
ErrorReporter& _errorReporter,
bytes const& _bytes,
std::string const& _signature,
ParameterList const& _params,
bool highlight = false,
bool failure = false
) const;
/// Formats a FAILURE plus additional parameters, if e.g. a revert message was returned.
std::string formatFailure(
ErrorReporter& _errorReporter,
FunctionCall const& _call,
bytes const& _output,
bool _renderResult,
bool _highlight
) const;
/// Formats the given parameters using their raw string representation.
std::string formatRawParameters(
ParameterList const& _params,
std::string const& _linePrefix = ""
) const;
/// Formats gas usage expectations one per line
std::string formatGasExpectations(
std::string const& _linePrefix,
bool _useActualCost,
bool _showDifference
) const;
/// Compares raw expectations (which are converted to a byte representation before),
/// and also the expected transaction status of the function call to the actual test results.
bool matchesExpectation() const;
/// Function call that has been parsed and which holds all parameters / expectations.
FunctionCall m_call;
/// Result of the actual call been made.
bytes m_rawBytes = bytes{};
/// Actual gas costs
std::map<std::string, u256> m_gasCostsExcludingCode;
/// Actual code deposit gas costs
std::map<std::string, u256> m_codeDepositGasCosts;
/// Transaction status of the actual call. False in case of a REVERT or any other failure.
bool m_failure = true;
/// JSON object which holds the contract ABI and that is used to set the output formatting
/// in the interactive update routine.
Json m_contractABI = Json{};
/// Flags that the test failed because the called function is not known to exist on the contract.
bool m_calledNonExistingFunction = false;
};
}
| 6,562
|
C++
|
.h
| 142
| 44.028169
| 130
| 0.775695
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,363
|
Common.h
|
ethereum_solidity/test/libsolidity/util/Common.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/// Utilities shared by multiple libsolidity tests.
#include <libsolidity/interface/CompilerStack.h>
#include <string>
namespace solidity::frontend::test
{
/// @returns @p _sourceCode prefixed with the version pragma and the SPDX license identifier.
/// Can optionally also insert an abicoder pragma when missing.
std::string withPreamble(std::string const& _sourceCode, bool _addAbicoderV1Pragma = false);
/// @returns a copy of @p _sources with preamble prepended to all sources.
StringMap withPreamble(StringMap _sources, bool _addAbicoderV1Pragma = false);
std::string stripPreReleaseWarning(std::string const& _stderrContent);
} // namespace solidity::frontend::test
| 1,365
|
C++
|
.h
| 26
| 50.653846
| 93
| 0.793675
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,364
|
SoltestErrors.h
|
ethereum_solidity/test/libsolidity/util/SoltestErrors.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <libsolutil/AnsiColorized.h>
#include <libsolutil/Assertions.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Exceptions.h>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/facilities/overload.hpp>
namespace solidity::frontend::test
{
struct InternalSoltestError: virtual util::Exception {};
#if !BOOST_PP_VARIADICS_MSVC
#define soltestAssert(...) BOOST_PP_OVERLOAD(soltestAssert_,__VA_ARGS__)(__VA_ARGS__)
#else
#define soltestAssert(...) BOOST_PP_CAT(BOOST_PP_OVERLOAD(soltestAssert_,__VA_ARGS__)(__VA_ARGS__),BOOST_PP_EMPTY())
#endif
#define soltestAssert_1(CONDITION) \
soltestAssert_2((CONDITION), "")
#define soltestAssert_2(CONDITION, DESCRIPTION) \
assertThrowWithDefaultDescription( \
(CONDITION), \
::solidity::frontend::test::InternalSoltestError, \
(DESCRIPTION), \
"Soltest assertion failed" \
)
class TestParserError: virtual public util::Exception
{
public:
explicit TestParserError(std::string const& _description)
{
*this << util::errinfo_comment(_description);
}
};
/**
* Representation of a notice, warning or error that can occur while
* formatting and therefore updating an interactive function call test.
*/
struct FormatError
{
enum Type
{
Notice,
Warning,
Error
};
explicit FormatError(Type _type, std::string _message):
type(_type),
message(std::move(_message))
{}
Type type;
std::string message;
};
using FormatErrors = std::vector<FormatError>;
/**
* Utility class that collects notices, warnings and errors and is able
* to format them for ANSI colorized output during the interactive update
* process in isoltest.
* Its purpose is to help users of isoltest to automatically
* update test files and always keep track of what is happening.
*/
class ErrorReporter
{
public:
explicit ErrorReporter() {}
/// Adds a new FormatError of type Notice with the given message.
void notice(std::string _notice)
{
m_errors.push_back(FormatError{FormatError::Notice, std::move(_notice)});
}
/// Adds a new FormatError of type Warning with the given message.
void warning(std::string _warning)
{
m_errors.push_back(FormatError{FormatError::Warning, std::move(_warning)});
}
/// Adds a new FormatError of type Error with the given message.
void error(std::string _error)
{
m_errors.push_back(FormatError{FormatError::Error, std::move(_error)});
}
/// Prints all errors depending on their type using ANSI colorized output.
/// It will be used to print notices, warnings and errors during the
/// interactive update process.
std::string format(std::string const& _linePrefix, bool _formatted)
{
std::stringstream os;
for (auto const& error: m_errors)
{
switch (error.type)
{
case FormatError::Notice:
break;
case FormatError::Warning:
util::AnsiColorized(
os,
_formatted,
{util::formatting::YELLOW}
) << _linePrefix << "Warning: " << error.message << std::endl;
break;
case FormatError::Error:
util::AnsiColorized(
os,
_formatted,
{util::formatting::RED}
) << _linePrefix << "Error: " << error.message << std::endl;
break;
}
}
return os.str();
}
private:
FormatErrors m_errors;
};
}
| 3,914
|
C++
|
.h
| 126
| 28.595238
| 116
| 0.745488
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,367
|
loader.h
|
ethereum_solidity/test/evmc/loader.h
|
// EVMC: Ethereum Client-VM Connector API.
// Copyright 2018 The EVMC Authors.
// Licensed under the Apache License, Version 2.0.
/**
* EVMC Loader Library
*
* The EVMC Loader Library supports loading VMs implemented as Dynamically Loaded Libraries
* (DLLs, shared objects).
*
* @defgroup loader EVMC Loader
* @{
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/** The function pointer type for EVMC create functions. */
typedef struct evmc_vm* (*evmc_create_fn)(void);
/// Error codes for the EVMC loader.
///
/// Objects of this type SHOULD be initialized with ::EVMC_LOADER_UNSPECIFIED_ERROR
/// before passing to the EVMC loader.
enum evmc_loader_error_code
{
/** The loader succeeded. */
EVMC_LOADER_SUCCESS = 0,
/** The loader cannot open the given file name. */
EVMC_LOADER_CANNOT_OPEN = 1,
/** The VM create function not found. */
EVMC_LOADER_SYMBOL_NOT_FOUND = 2,
/** The invalid argument value provided. */
EVMC_LOADER_INVALID_ARGUMENT = 3,
/** The creation of a VM instance has failed. */
EVMC_LOADER_VM_CREATION_FAILURE = 4,
/** The ABI version of the VM instance has mismatched. */
EVMC_LOADER_ABI_VERSION_MISMATCH = 5,
/** The VM option is invalid. */
EVMC_LOADER_INVALID_OPTION_NAME = 6,
/** The VM option value is invalid. */
EVMC_LOADER_INVALID_OPTION_VALUE = 7,
/// This error value will be never returned by the EVMC loader,
/// but can be used by users to init evmc_loader_error_code objects.
EVMC_LOADER_UNSPECIFIED_ERROR = -1
};
/**
* Dynamically loads the EVMC module with a VM implementation.
*
* This function tries to open a dynamically loaded library (DLL) at the given `filename`.
* On UNIX-like systems dlopen() function is used. On Windows LoadLibrary() function is used.
*
* If the file does not exist or is not a valid shared library the ::EVMC_LOADER_CANNOT_OPEN error
* code is signaled and NULL is returned.
*
* After the DLL is successfully loaded the function tries to find the EVM create function in the
* library. The `filename` is used to guess the EVM name and the name of the create function.
* The create function name is constructed by the following rules. Consider example path:
* "/ethereum/libexample-interpreter.so.1.0".
* - the filename is taken from the path:
* "libexample-interpreter.so.1.0",
* - the "lib" prefix and all file extensions are stripped from the name:
* "example-interpreter"
* - all "-" are replaced with "_" to construct _base name_:
* "example_interpreter",
* - the function name "evmc_create_" + _base name_ is searched in the library:
* "evmc_create_example_interpreter",
* - if the function is not found, the function name "evmc_create" is searched in the library.
*
* If the create function is found in the library, the pointer to the function is returned.
* Otherwise, the ::EVMC_LOADER_SYMBOL_NOT_FOUND error code is signaled and NULL is returned.
*
* It is safe to call this function with the same filename argument multiple times
* (the DLL is not going to be loaded multiple times).
*
* @param filename The null terminated path (absolute or relative) to an EVMC module
* (dynamically loaded library) containing the VM implementation.
* If the value is NULL, an empty C-string or longer than the path maximum length
* the ::EVMC_LOADER_INVALID_ARGUMENT is signaled.
* @param error_code The pointer to the error code. If not NULL the value is set to
* ::EVMC_LOADER_SUCCESS on success or any other error code as described above.
* @return The pointer to the EVM create function or NULL in case of error.
*/
evmc_create_fn evmc_load(const char* filename, enum evmc_loader_error_code* error_code);
/**
* Dynamically loads the EVMC module and creates the VM instance.
*
* This is a macro for creating the VM instance with the function returned from evmc_load().
* The function signals the same errors as evmc_load() and additionally:
* - ::EVMC_LOADER_VM_CREATION_FAILURE when the create function returns NULL,
* - ::EVMC_LOADER_ABI_VERSION_MISMATCH when the created VM instance has ABI version different
* from the ABI version of this library (::EVMC_ABI_VERSION).
*
* It is safe to call this function with the same filename argument multiple times:
* the DLL is not going to be loaded multiple times, but the function will return new VM instance
* each time.
*
* @param filename The null terminated path (absolute or relative) to an EVMC module
* (dynamically loaded library) containing the VM implementation.
* If the value is NULL, an empty C-string or longer than the path maximum length
* the ::EVMC_LOADER_INVALID_ARGUMENT is signaled.
* @param error_code The pointer to the error code. If not NULL the value is set to
* ::EVMC_LOADER_SUCCESS on success or any other error code as described above.
* @return The pointer to the created VM or NULL in case of error.
*/
struct evmc_vm* evmc_load_and_create(const char* filename, enum evmc_loader_error_code* error_code);
/**
* Dynamically loads the EVMC module, then creates and configures the VM instance.
*
* This function performs the following actions atomically:
* - loads the EVMC module (as evmc_load()),
* - creates the VM instance,
* - configures the VM instance with options provided in the @p config parameter.
*
* The configuration string (@p config) has the following syntax:
*
* <path> ("," <option-name> ["=" <option-value>])*
*
* In this syntax, an option without a value can be specified (`,option,`)
* as a shortcut for using empty value (`,option=,`).
*
* Options are passed to a VM in the order they are specified in the configuration string.
* It is up to the VM implementation how to handle duplicated options and other conflicts.
*
* Example configuration string:
*
* ./modules/vm.so,engine=compiler,trace,verbosity=2
*
* The function signals the same errors as evmc_load_and_create() and additionally:
* - ::EVMC_LOADER_INVALID_OPTION_NAME
* when the provided options list contains an option unknown for the VM,
* - ::EVMC_LOADER_INVALID_OPTION_VALUE
* when there exists unsupported value for a given VM option.
*
* @param config The path to the EVMC module with additional configuration options.
* @param error_code The pointer to the error code. If not NULL the value is set to
* ::EVMC_LOADER_SUCCESS on success or any other error code as described above.
* @return The pointer to the created VM or NULL in case of error.
*/
struct evmc_vm* evmc_load_and_configure(const char* config,
enum evmc_loader_error_code* error_code);
/**
* Returns the human-readable message describing the most recent error
* that occurred in EVMC loading since the last call to this function.
*
* In case any loading function returned ::EVMC_LOADER_SUCCESS this function always returns NULL.
* In case of error code other than success returned, this function MAY return the error message.
* Calling this function "consumes" the error message and the function will return NULL
* from subsequent invocations.
* This function is not thread-safe.
*
* @return Error message or NULL if no additional information is available.
* The returned pointer MUST NOT be freed by the caller.
*/
const char* evmc_last_error_msg(void);
#ifdef __cplusplus
}
#endif
/** @} */
| 7,586
|
C++
|
.h
| 157
| 45.770701
| 100
| 0.716059
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,369
|
utils.h
|
ethereum_solidity/test/evmc/utils.h
|
// EVMC: Ethereum Client-VM Connector API.
// Copyright 2018 The EVMC Authors.
// Licensed under the Apache License, Version 2.0.
#pragma once
/**
* @file
* A collection of helper macros to handle some non-portable features of C/C++ compilers.
*
* @addtogroup helpers
* @{
*/
/**
* @def EVMC_EXPORT
* Marks a function to be exported from a shared library.
*/
#if defined _MSC_VER || defined __MINGW32__
#define EVMC_EXPORT __declspec(dllexport)
#else
#define EVMC_EXPORT __attribute__((visibility("default")))
#endif
/**
* @def EVMC_NOEXCEPT
* Safe way of marking a function with `noexcept` C++ specifier.
*/
#ifdef __cplusplus
#define EVMC_NOEXCEPT noexcept
#else
#define EVMC_NOEXCEPT
#endif
/** @} */
| 721
|
C++
|
.h
| 30
| 22.466667
| 89
| 0.723032
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
3,372
|
evmc.h
|
ethereum_solidity/test/evmc/evmc.h
|
/**
* EVMC: Ethereum Client-VM Connector API
*
* @copyright
* Copyright 2016 The EVMC Authors.
* Licensed under the Apache License, Version 2.0.
*
* @defgroup EVMC EVMC
* @{
*/
#ifndef EVMC_H
#define EVMC_H
#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ >= 6)
/**
* Portable declaration of "deprecated" attribute.
*
* Available for clang and GCC 6+ compilers. The older GCC compilers know
* this attribute, but it cannot be applied to enum elements.
*/
#define EVMC_DEPRECATED __attribute__((deprecated))
#else
#define EVMC_DEPRECATED
#endif
#include <stdbool.h> /* Definition of bool, true and false. */
#include <stddef.h> /* Definition of size_t. */
#include <stdint.h> /* Definition of int64_t, uint64_t. */
#ifdef __cplusplus
extern "C" {
#endif
/* BEGIN Python CFFI declarations */
enum
{
/**
* The EVMC ABI version number of the interface declared in this file.
*
* The EVMC ABI version always equals the major version number of the EVMC project.
* The Host SHOULD check if the ABI versions match when dynamically loading VMs.
*
* @see @ref versioning
*/
EVMC_ABI_VERSION = 12
};
/**
* The fixed size array of 32 bytes.
*
* 32 bytes of data capable of storing e.g. 256-bit hashes.
*/
typedef struct evmc_bytes32
{
/** The 32 bytes. */
uint8_t bytes[32];
} evmc_bytes32;
/**
* The alias for evmc_bytes32 to represent a big-endian 256-bit integer.
*/
typedef struct evmc_bytes32 evmc_uint256be;
/** Big-endian 160-bit hash suitable for keeping an Ethereum address. */
typedef struct evmc_address
{
/** The 20 bytes of the hash. */
uint8_t bytes[20];
} evmc_address;
/** The kind of call-like instruction. */
enum evmc_call_kind
{
EVMC_CALL = 0, /**< Request CALL. */
EVMC_DELEGATECALL = 1, /**< Request DELEGATECALL. Valid since Homestead.
The value param ignored. */
EVMC_CALLCODE = 2, /**< Request CALLCODE. */
EVMC_CREATE = 3, /**< Request CREATE. */
EVMC_CREATE2 = 4, /**< Request CREATE2. Valid since Constantinople.*/
EVMC_EOFCREATE = 5 /**< Request EOFCREATE. Valid since Prague.*/
};
/** The flags for ::evmc_message. */
enum evmc_flags
{
EVMC_STATIC = 1 /**< Static call mode. */
};
/**
* The message describing an EVM call, including a zero-depth calls from a transaction origin.
*
* Most of the fields are modelled by the section 8. Message Call of the Ethereum Yellow Paper.
*/
struct evmc_message
{
/** The kind of the call. For zero-depth calls ::EVMC_CALL SHOULD be used. */
enum evmc_call_kind kind;
/**
* Additional flags modifying the call execution behavior.
* In the current version the only valid values are ::EVMC_STATIC or 0.
*/
uint32_t flags;
/**
* The present depth of the message call stack.
*
* Defined as `e` in the Yellow Paper.
*/
int32_t depth;
/**
* The amount of gas available to the message execution.
*
* Defined as `g` in the Yellow Paper.
*/
int64_t gas;
/**
* The recipient of the message.
*
* This is the address of the account which storage/balance/nonce is going to be modified
* by the message execution. In case of ::EVMC_CALL, this is also the account where the
* message value evmc_message::value is going to be transferred.
* For ::EVMC_CALLCODE or ::EVMC_DELEGATECALL, this may be different from
* the evmc_message::code_address.
*
* Defined as `r` in the Yellow Paper.
*/
evmc_address recipient;
/**
* The sender of the message.
*
* The address of the sender of a message call defined as `s` in the Yellow Paper.
* This must be the message recipient of the message at the previous (lower) depth,
* except for the ::EVMC_DELEGATECALL where recipient is the 2 levels above the present depth.
* At the depth 0 this must be the transaction origin.
*/
evmc_address sender;
/**
* The message input data.
*
* The arbitrary length byte array of the input data of the call,
* defined as `d` in the Yellow Paper.
* This MAY be NULL.
*/
const uint8_t* input_data;
/**
* The size of the message input data.
*
* If input_data is NULL this MUST be 0.
*/
size_t input_size;
/**
* The amount of Ether transferred with the message.
*
* This is transferred value for ::EVMC_CALL or apparent value for ::EVMC_DELEGATECALL.
* Defined as `v` or `v~` in the Yellow Paper.
*/
evmc_uint256be value;
/**
* The optional value used in new contract address construction.
*
* Needed only for a Host to calculate created address when kind is ::EVMC_CREATE2 or
* ::EVMC_EOFCREATE.
* Ignored in evmc_execute_fn().
*/
evmc_bytes32 create2_salt;
/**
* The address of the code to be executed.
*
* For ::EVMC_CALLCODE or ::EVMC_DELEGATECALL this may be different from
* the evmc_message::recipient.
* Not required when invoking evmc_execute_fn(), only when invoking evmc_call_fn().
* Ignored if kind is ::EVMC_CREATE, ::EVMC_CREATE2 or ::EVMC_EOFCREATE.
*
* In case of ::EVMC_CAPABILITY_PRECOMPILES implementation, this fields should be inspected
* to identify the requested precompile.
*
* Defined as `c` in the Yellow Paper.
*/
evmc_address code_address;
/**
* The code to be executed.
*/
const uint8_t* code;
/**
* The length of the code to be executed.
*/
size_t code_size;
};
/** The hashed initcode used for TXCREATE instruction. */
typedef struct evmc_tx_initcode
{
evmc_bytes32 hash; /**< The initcode hash. */
const uint8_t* code; /**< The code. */
size_t code_size; /**< The length of the code. */
} evmc_tx_initcode;
/** The transaction and block data for execution. */
struct evmc_tx_context
{
evmc_uint256be tx_gas_price; /**< The transaction gas price. */
evmc_address tx_origin; /**< The transaction origin account. */
evmc_address block_coinbase; /**< The miner of the block. */
int64_t block_number; /**< The block number. */
int64_t block_timestamp; /**< The block timestamp. */
int64_t block_gas_limit; /**< The block gas limit. */
evmc_uint256be block_prev_randao; /**< The block previous RANDAO (EIP-4399). */
evmc_uint256be chain_id; /**< The blockchain's ChainID. */
evmc_uint256be block_base_fee; /**< The block base fee per gas (EIP-1559, EIP-3198). */
evmc_uint256be blob_base_fee; /**< The blob base fee (EIP-7516). */
const evmc_bytes32* blob_hashes; /**< The array of blob hashes (EIP-4844). */
size_t blob_hashes_count; /**< The number of blob hashes (EIP-4844). */
const evmc_tx_initcode* initcodes; /**< The array of transaction initcodes (TXCREATE). */
size_t initcodes_count; /**< The number of transaction initcodes (TXCREATE). */
};
/**
* @struct evmc_host_context
* The opaque data type representing the Host execution context.
* @see evmc_execute_fn().
*/
struct evmc_host_context;
/**
* Get transaction context callback function.
*
* This callback function is used by an EVM to retrieve the transaction and
* block context.
*
* @param context The pointer to the Host execution context.
* @return The transaction context.
*/
typedef struct evmc_tx_context (*evmc_get_tx_context_fn)(struct evmc_host_context* context);
/**
* Get block hash callback function.
*
* This callback function is used by a VM to query the hash of the header of the given block.
* If the information about the requested block is not available, then this is signalled by
* returning null bytes.
*
* @param context The pointer to the Host execution context.
* @param number The block number.
* @return The block hash or null bytes
* if the information about the block is not available.
*/
typedef evmc_bytes32 (*evmc_get_block_hash_fn)(struct evmc_host_context* context, int64_t number);
/**
* The execution status code.
*
* Successful execution is represented by ::EVMC_SUCCESS having value 0.
*
* Positive values represent failures defined by VM specifications with generic
* ::EVMC_FAILURE code of value 1.
*
* Status codes with negative values represent VM internal errors
* not provided by EVM specifications. These errors MUST not be passed back
* to the caller. They MAY be handled by the Client in predefined manner
* (see e.g. ::EVMC_REJECTED), otherwise internal errors are not recoverable.
* The generic representant of errors is ::EVMC_INTERNAL_ERROR but
* an EVM implementation MAY return negative status codes that are not defined
* in the EVMC documentation.
*
* @note
* In case new status codes are needed, please create an issue or pull request
* in the EVMC repository (https://github.com/ethereum/evmc).
*/
enum evmc_status_code
{
/** Execution finished with success. */
EVMC_SUCCESS = 0,
/** Generic execution failure. */
EVMC_FAILURE = 1,
/**
* Execution terminated with REVERT opcode.
*
* In this case the amount of gas left MAY be non-zero and additional output
* data MAY be provided in ::evmc_result.
*/
EVMC_REVERT = 2,
/** The execution has run out of gas. */
EVMC_OUT_OF_GAS = 3,
/**
* The designated INVALID instruction has been hit during execution.
*
* The EIP-141 (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-141.md)
* defines the instruction 0xfe as INVALID instruction to indicate execution
* abortion coming from high-level languages. This status code is reported
* in case this INVALID instruction has been encountered.
*/
EVMC_INVALID_INSTRUCTION = 4,
/** An undefined instruction has been encountered. */
EVMC_UNDEFINED_INSTRUCTION = 5,
/**
* The execution has attempted to put more items on the EVM stack
* than the specified limit.
*/
EVMC_STACK_OVERFLOW = 6,
/** Execution of an opcode has required more items on the EVM stack. */
EVMC_STACK_UNDERFLOW = 7,
/** Execution has violated the jump destination restrictions. */
EVMC_BAD_JUMP_DESTINATION = 8,
/**
* Tried to read outside memory bounds.
*
* An example is RETURNDATACOPY reading past the available buffer.
*/
EVMC_INVALID_MEMORY_ACCESS = 9,
/** Call depth has exceeded the limit (if any) */
EVMC_CALL_DEPTH_EXCEEDED = 10,
/** Tried to execute an operation which is restricted in static mode. */
EVMC_STATIC_MODE_VIOLATION = 11,
/**
* A call to a precompiled or system contract has ended with a failure.
*
* An example: elliptic curve functions handed invalid EC points.
*/
EVMC_PRECOMPILE_FAILURE = 12,
/**
* Contract validation has failed (e.g. due to EVM 1.5 jump validity,
* Casper's purity checker or ewasm contract rules).
*/
EVMC_CONTRACT_VALIDATION_FAILURE = 13,
/**
* An argument to a state accessing method has a value outside of the
* accepted range of values.
*/
EVMC_ARGUMENT_OUT_OF_RANGE = 14,
/**
* A WebAssembly `unreachable` instruction has been hit during execution.
*/
EVMC_WASM_UNREACHABLE_INSTRUCTION = 15,
/**
* A WebAssembly trap has been hit during execution. This can be for many
* reasons, including division by zero, validation errors, etc.
*/
EVMC_WASM_TRAP = 16,
/** The caller does not have enough funds for value transfer. */
EVMC_INSUFFICIENT_BALANCE = 17,
/** EVM implementation generic internal error. */
EVMC_INTERNAL_ERROR = -1,
/**
* The execution of the given code and/or message has been rejected
* by the EVM implementation.
*
* This error SHOULD be used to signal that the EVM is not able to or
* willing to execute the given code type or message.
* If an EVM returns the ::EVMC_REJECTED status code,
* the Client MAY try to execute it in other EVM implementation.
* For example, the Client tries running a code in the EVM 1.5. If the
* code is not supported there, the execution falls back to the EVM 1.0.
*/
EVMC_REJECTED = -2,
/** The VM failed to allocate the amount of memory needed for execution. */
EVMC_OUT_OF_MEMORY = -3
};
/* Forward declaration. */
struct evmc_result;
/**
* Releases resources assigned to an execution result.
*
* This function releases memory (and other resources, if any) assigned to the
* specified execution result making the result object invalid.
*
* @param result The execution result which resources are to be released. The
* result itself it not modified by this function, but becomes
* invalid and user MUST discard it as well.
* This MUST NOT be NULL.
*
* @note
* The result is passed by pointer to avoid (shallow) copy of the ::evmc_result
* struct. Think of this as the best possible C language approximation to
* passing objects by reference.
*/
typedef void (*evmc_release_result_fn)(const struct evmc_result* result);
/** The EVM code execution result. */
struct evmc_result
{
/** The execution status code. */
enum evmc_status_code status_code;
/**
* The amount of gas left after the execution.
*
* If evmc_result::status_code is neither ::EVMC_SUCCESS nor ::EVMC_REVERT
* the value MUST be 0.
*/
int64_t gas_left;
/**
* The refunded gas accumulated from this execution and its sub-calls.
*
* The transaction gas refund limit is not applied.
* If evmc_result::status_code is other than ::EVMC_SUCCESS the value MUST be 0.
*/
int64_t gas_refund;
/**
* The reference to output data.
*
* The output contains data coming from RETURN opcode (iff evmc_result::code
* field is ::EVMC_SUCCESS) or from REVERT opcode.
*
* The memory containing the output data is owned by EVM and has to be
* freed with evmc_result::release().
*
* This pointer MAY be NULL.
* If evmc_result::output_size is 0 this pointer MUST NOT be dereferenced.
*/
const uint8_t* output_data;
/**
* The size of the output data.
*
* If evmc_result::output_data is NULL this MUST be 0.
*/
size_t output_size;
/**
* The method releasing all resources associated with the result object.
*
* This method (function pointer) is optional (MAY be NULL) and MAY be set
* by the VM implementation. If set it MUST be called by the user once to
* release memory and other resources associated with the result object.
* Once the resources are released the result object MUST NOT be used again.
*
* The suggested code pattern for releasing execution results:
* @code
* struct evmc_result result = ...;
* if (result.release)
* result.release(&result);
* @endcode
*
* @note
* It works similarly to C++ virtual destructor. Attaching the release
* function to the result itself allows VM composition.
*/
evmc_release_result_fn release;
/**
* The address of the possibly created contract.
*
* The create address may be provided even though the contract creation has failed
* (evmc_result::status_code is not ::EVMC_SUCCESS). This is useful in situations
* when the address is observable, e.g. access to it remains warm.
* In all other cases the address MUST be null bytes.
*/
evmc_address create_address;
/**
* Reserved data that MAY be used by a evmc_result object creator.
*
* This reserved 4 bytes together with 20 bytes from create_address form
* 24 bytes of memory called "optional data" within evmc_result struct
* to be optionally used by the evmc_result object creator.
*
* @see evmc_result_optional_data, evmc_get_optional_data().
*
* Also extends the size of the evmc_result to 64 bytes (full cache line).
*/
uint8_t padding[4];
};
/**
* Check account existence callback function.
*
* This callback function is used by the VM to check if
* there exists an account at given address.
* @param context The pointer to the Host execution context.
* @param address The address of the account the query is about.
* @return true if exists, false otherwise.
*/
typedef bool (*evmc_account_exists_fn)(struct evmc_host_context* context,
const evmc_address* address);
/**
* Get storage callback function.
*
* This callback function is used by a VM to query the given account storage entry.
*
* @param context The Host execution context.
* @param address The address of the account.
* @param key The index of the account's storage entry.
* @return The storage value at the given storage key or null bytes
* if the account does not exist.
*/
typedef evmc_bytes32 (*evmc_get_storage_fn)(struct evmc_host_context* context,
const evmc_address* address,
const evmc_bytes32* key);
/**
* Get transient storage callback function.
*
* This callback function is used by a VM to query
* the given account transient storage (EIP-1153) entry.
*
* @param context The Host execution context.
* @param address The address of the account.
* @param key The index of the account's transient storage entry.
* @return The transient storage value at the given storage key or null bytes
* if the account does not exist.
*/
typedef evmc_bytes32 (*evmc_get_transient_storage_fn)(struct evmc_host_context* context,
const evmc_address* address,
const evmc_bytes32* key);
/**
* The effect of an attempt to modify a contract storage item.
*
* See @ref storagestatus for additional information about design of this enum
* and analysis of the specification.
*
* For the purpose of explaining the meaning of each element, the following
* notation is used:
* - 0 is zero value,
* - X != 0 (X is any value other than 0),
* - Y != 0, Y != X, (Y is any value other than X and 0),
* - Z != 0, Z != X, Z != X (Z is any value other than Y and X and 0),
* - the "o -> c -> v" triple describes the change status in the context of:
* - o: original value (cold value before a transaction started),
* - c: current storage value,
* - v: new storage value to be set.
*
* The order of elements follows EIPs introducing net storage gas costs:
* - EIP-2200: https://eips.ethereum.org/EIPS/eip-2200,
* - EIP-1283: https://eips.ethereum.org/EIPS/eip-1283.
*/
enum evmc_storage_status
{
/**
* The new/same value is assigned to the storage item without affecting the cost structure.
*
* The storage value item is either:
* - left unchanged (c == v) or
* - the dirty value (o != c) is modified again (c != v).
* This is the group of cases related to minimal gas cost of only accessing warm storage.
* 0|X -> 0 -> 0 (current value unchanged)
* 0|X|Y -> Y -> Y (current value unchanged)
* 0|X -> Y -> Z (modified previously added/modified value)
*
* This is "catch all remaining" status. I.e. if all other statuses are correctly matched
* this status should be assigned to all remaining cases.
*/
EVMC_STORAGE_ASSIGNED = 0,
/**
* A new storage item is added by changing
* the current clean zero to a nonzero value.
* 0 -> 0 -> Z
*/
EVMC_STORAGE_ADDED = 1,
/**
* A storage item is deleted by changing
* the current clean nonzero to the zero value.
* X -> X -> 0
*/
EVMC_STORAGE_DELETED = 2,
/**
* A storage item is modified by changing
* the current clean nonzero to other nonzero value.
* X -> X -> Z
*/
EVMC_STORAGE_MODIFIED = 3,
/**
* A storage item is added by changing
* the current dirty zero to a nonzero value other than the original value.
* X -> 0 -> Z
*/
EVMC_STORAGE_DELETED_ADDED = 4,
/**
* A storage item is deleted by changing
* the current dirty nonzero to the zero value and the original value is not zero.
* X -> Y -> 0
*/
EVMC_STORAGE_MODIFIED_DELETED = 5,
/**
* A storage item is added by changing
* the current dirty zero to the original value.
* X -> 0 -> X
*/
EVMC_STORAGE_DELETED_RESTORED = 6,
/**
* A storage item is deleted by changing
* the current dirty nonzero to the original zero value.
* 0 -> Y -> 0
*/
EVMC_STORAGE_ADDED_DELETED = 7,
/**
* A storage item is modified by changing
* the current dirty nonzero to the original nonzero value other than the current value.
* X -> Y -> X
*/
EVMC_STORAGE_MODIFIED_RESTORED = 8
};
/**
* Set storage callback function.
*
* This callback function is used by a VM to update the given account storage entry.
* The VM MUST make sure that the account exists. This requirement is only a formality because
* VM implementations only modify storage of the account of the current execution context
* (i.e. referenced by evmc_message::recipient).
*
* @param context The pointer to the Host execution context.
* @param address The address of the account.
* @param key The index of the storage entry.
* @param value The value to be stored.
* @return The effect on the storage item.
*/
typedef enum evmc_storage_status (*evmc_set_storage_fn)(struct evmc_host_context* context,
const evmc_address* address,
const evmc_bytes32* key,
const evmc_bytes32* value);
/**
* Set transient storage callback function.
*
* This callback function is used by a VM to update
* the given account's transient storage (EIP-1153) entry.
* The VM MUST make sure that the account exists. This requirement is only a formality because
* VM implementations only modify storage of the account of the current execution context
* (i.e. referenced by evmc_message::recipient).
*
* @param context The pointer to the Host execution context.
* @param address The address of the account.
* @param key The index of the transient storage entry.
* @param value The value to be stored.
*/
typedef void (*evmc_set_transient_storage_fn)(struct evmc_host_context* context,
const evmc_address* address,
const evmc_bytes32* key,
const evmc_bytes32* value);
/**
* Get balance callback function.
*
* This callback function is used by a VM to query the balance of the given account.
*
* @param context The pointer to the Host execution context.
* @param address The address of the account.
* @return The balance of the given account or 0 if the account does not exist.
*/
typedef evmc_uint256be (*evmc_get_balance_fn)(struct evmc_host_context* context,
const evmc_address* address);
/**
* Get code size callback function.
*
* This callback function is used by a VM to get the size of the code stored
* in the account at the given address.
*
* @param context The pointer to the Host execution context.
* @param address The address of the account.
* @return The size of the code in the account or 0 if the account does not exist.
*/
typedef size_t (*evmc_get_code_size_fn)(struct evmc_host_context* context,
const evmc_address* address);
/**
* Get code hash callback function.
*
* This callback function is used by a VM to get the keccak256 hash of the code stored
* in the account at the given address. For existing accounts not having a code, this
* function returns keccak256 hash of empty data.
*
* @param context The pointer to the Host execution context.
* @param address The address of the account.
* @return The hash of the code in the account or null bytes if the account does not exist.
*/
typedef evmc_bytes32 (*evmc_get_code_hash_fn)(struct evmc_host_context* context,
const evmc_address* address);
/**
* Copy code callback function.
*
* This callback function is used by an EVM to request a copy of the code
* of the given account to the memory buffer provided by the EVM.
* The Client MUST copy the requested code, starting with the given offset,
* to the provided memory buffer up to the size of the buffer or the size of
* the code, whichever is smaller.
*
* @param context The pointer to the Host execution context. See ::evmc_host_context.
* @param address The address of the account.
* @param code_offset The offset of the code to copy.
* @param buffer_data The pointer to the memory buffer allocated by the EVM
* to store a copy of the requested code.
* @param buffer_size The size of the memory buffer.
* @return The number of bytes copied to the buffer by the Client.
*/
typedef size_t (*evmc_copy_code_fn)(struct evmc_host_context* context,
const evmc_address* address,
size_t code_offset,
uint8_t* buffer_data,
size_t buffer_size);
/**
* Selfdestruct callback function.
*
* This callback function is used by an EVM to SELFDESTRUCT given contract.
* The execution of the contract will not be stopped, that is up to the EVM.
*
* @param context The pointer to the Host execution context. See ::evmc_host_context.
* @param address The address of the contract to be selfdestructed.
* @param beneficiary The address where the remaining ETH is going to be transferred.
* @return The information if the given address has not been registered as
* selfdestructed yet. True if registered for the first time, false otherwise.
*/
typedef bool (*evmc_selfdestruct_fn)(struct evmc_host_context* context,
const evmc_address* address,
const evmc_address* beneficiary);
/**
* Log callback function.
*
* This callback function is used by an EVM to inform about a LOG that happened
* during an EVM bytecode execution.
*
* @param context The pointer to the Host execution context. See ::evmc_host_context.
* @param address The address of the contract that generated the log.
* @param data The pointer to unindexed data attached to the log.
* @param data_size The length of the data.
* @param topics The pointer to the array of topics attached to the log.
* @param topics_count The number of the topics. Valid values are between 0 and 4 inclusively.
*/
typedef void (*evmc_emit_log_fn)(struct evmc_host_context* context,
const evmc_address* address,
const uint8_t* data,
size_t data_size,
const evmc_bytes32 topics[],
size_t topics_count);
/**
* Access status per EIP-2929: Gas cost increases for state access opcodes.
*/
enum evmc_access_status
{
/**
* The entry hasn't been accessed before – it's the first access.
*/
EVMC_ACCESS_COLD = 0,
/**
* The entry is already in accessed_addresses or accessed_storage_keys.
*/
EVMC_ACCESS_WARM = 1
};
/**
* Access account callback function.
*
* This callback function is used by a VM to add the given address
* to accessed_addresses substate (EIP-2929).
*
* @param context The Host execution context.
* @param address The address of the account.
* @return EVMC_ACCESS_WARM if accessed_addresses already contained the address
* or EVMC_ACCESS_COLD otherwise.
*/
typedef enum evmc_access_status (*evmc_access_account_fn)(struct evmc_host_context* context,
const evmc_address* address);
/**
* Access storage callback function.
*
* This callback function is used by a VM to add the given account storage entry
* to accessed_storage_keys substate (EIP-2929).
*
* @param context The Host execution context.
* @param address The address of the account.
* @param key The index of the account's storage entry.
* @return EVMC_ACCESS_WARM if accessed_storage_keys already contained the key
* or EVMC_ACCESS_COLD otherwise.
*/
typedef enum evmc_access_status (*evmc_access_storage_fn)(struct evmc_host_context* context,
const evmc_address* address,
const evmc_bytes32* key);
/**
* Pointer to the callback function supporting EVM calls.
*
* @param context The pointer to the Host execution context.
* @param msg The call parameters.
* @return The result of the call.
*/
typedef struct evmc_result (*evmc_call_fn)(struct evmc_host_context* context,
const struct evmc_message* msg);
/**
* The Host interface.
*
* The set of all callback functions expected by VM instances. This is C
* realisation of vtable for OOP interface (only virtual methods, no data).
* Host implementations SHOULD create constant singletons of this (similarly
* to vtables) to lower the maintenance and memory management cost.
*/
struct evmc_host_interface
{
/** Check account existence callback function. */
evmc_account_exists_fn account_exists;
/** Get storage callback function. */
evmc_get_storage_fn get_storage;
/** Set storage callback function. */
evmc_set_storage_fn set_storage;
/** Get balance callback function. */
evmc_get_balance_fn get_balance;
/** Get code size callback function. */
evmc_get_code_size_fn get_code_size;
/** Get code hash callback function. */
evmc_get_code_hash_fn get_code_hash;
/** Copy code callback function. */
evmc_copy_code_fn copy_code;
/** Selfdestruct callback function. */
evmc_selfdestruct_fn selfdestruct;
/** Call callback function. */
evmc_call_fn call;
/** Get transaction context callback function. */
evmc_get_tx_context_fn get_tx_context;
/** Get block hash callback function. */
evmc_get_block_hash_fn get_block_hash;
/** Emit log callback function. */
evmc_emit_log_fn emit_log;
/** Access account callback function. */
evmc_access_account_fn access_account;
/** Access storage callback function. */
evmc_access_storage_fn access_storage;
/** Get transient storage callback function. */
evmc_get_transient_storage_fn get_transient_storage;
/** Set transient storage callback function. */
evmc_set_transient_storage_fn set_transient_storage;
};
/* Forward declaration. */
struct evmc_vm;
/**
* Destroys the VM instance.
*
* @param vm The VM instance to be destroyed.
*/
typedef void (*evmc_destroy_fn)(struct evmc_vm* vm);
/**
* Possible outcomes of evmc_set_option.
*/
enum evmc_set_option_result
{
EVMC_SET_OPTION_SUCCESS = 0,
EVMC_SET_OPTION_INVALID_NAME = 1,
EVMC_SET_OPTION_INVALID_VALUE = 2
};
/**
* Configures the VM instance.
*
* Allows modifying options of the VM instance.
* Options:
* - code cache behavior: on, off, read-only, ...
* - optimizations,
*
* @param vm The VM instance to be configured.
* @param name The option name. NULL-terminated string. Cannot be NULL.
* @param value The new option value. NULL-terminated string. Cannot be NULL.
* @return The outcome of the operation.
*/
typedef enum evmc_set_option_result (*evmc_set_option_fn)(struct evmc_vm* vm,
char const* name,
char const* value);
/**
* EVM revision.
*
* The revision of the EVM specification based on the Ethereum
* upgrade / hard fork codenames.
*/
enum evmc_revision
{
/**
* The Frontier revision.
*
* The one Ethereum launched with.
*/
EVMC_FRONTIER = 0,
/**
* The Homestead revision.
*
* https://eips.ethereum.org/EIPS/eip-606
*/
EVMC_HOMESTEAD = 1,
/**
* The Tangerine Whistle revision.
*
* https://eips.ethereum.org/EIPS/eip-608
*/
EVMC_TANGERINE_WHISTLE = 2,
/**
* The Spurious Dragon revision.
*
* https://eips.ethereum.org/EIPS/eip-607
*/
EVMC_SPURIOUS_DRAGON = 3,
/**
* The Byzantium revision.
*
* https://eips.ethereum.org/EIPS/eip-609
*/
EVMC_BYZANTIUM = 4,
/**
* The Constantinople revision.
*
* https://eips.ethereum.org/EIPS/eip-1013
*/
EVMC_CONSTANTINOPLE = 5,
/**
* The Petersburg revision.
*
* Other names: Constantinople2, ConstantinopleFix.
*
* https://eips.ethereum.org/EIPS/eip-1716
*/
EVMC_PETERSBURG = 6,
/**
* The Istanbul revision.
*
* https://eips.ethereum.org/EIPS/eip-1679
*/
EVMC_ISTANBUL = 7,
/**
* The Berlin revision.
*
* https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/berlin.md
*/
EVMC_BERLIN = 8,
/**
* The London revision.
*
* https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/london.md
*/
EVMC_LONDON = 9,
/**
* The Paris revision (aka The Merge).
*
* https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/paris.md
*/
EVMC_PARIS = 10,
/**
* The Shanghai revision.
*
* https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md
*/
EVMC_SHANGHAI = 11,
/**
* The Cancun revision.
*
* https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/cancun.md
*/
EVMC_CANCUN = 12,
/**
* The Prague revision.
*
* The future next revision after Cancun.
*/
EVMC_PRAGUE = 13,
/**
* The Osaka revision.
*
* The future next revision after Prague.
*/
EVMC_OSAKA = 14,
/** The maximum EVM revision supported. */
EVMC_MAX_REVISION = EVMC_OSAKA,
/**
* The latest known EVM revision with finalized specification.
*
* This is handy for EVM tools to always use the latest revision available.
*/
EVMC_LATEST_STABLE_REVISION = EVMC_CANCUN
};
/**
* Executes the given code using the input from the message.
*
* This function MAY be invoked multiple times for a single VM instance.
*
* @param vm The VM instance. This argument MUST NOT be NULL.
* @param host The Host interface. This argument MUST NOT be NULL unless
* the @p vm has the ::EVMC_CAPABILITY_PRECOMPILES capability.
* @param context The opaque pointer to the Host execution context.
* This argument MAY be NULL. The VM MUST pass the same
* pointer to the methods of the @p host interface.
* The VM MUST NOT dereference the pointer.
* @param rev The requested EVM specification revision.
* @param msg The call parameters. See ::evmc_message. This argument MUST NOT be NULL.
* @param code The reference to the code to be executed. This argument MAY be NULL.
* @param code_size The length of the code. If @p code is NULL this argument MUST be 0.
* @return The execution result.
*/
typedef struct evmc_result (*evmc_execute_fn)(struct evmc_vm* vm,
const struct evmc_host_interface* host,
struct evmc_host_context* context,
enum evmc_revision rev,
const struct evmc_message* msg,
uint8_t const* code,
size_t code_size);
/**
* Possible capabilities of a VM.
*/
enum evmc_capabilities
{
/**
* The VM is capable of executing EVM1 bytecode.
*/
EVMC_CAPABILITY_EVM1 = (1u << 0),
/**
* The VM is capable of executing ewasm bytecode.
*/
EVMC_CAPABILITY_EWASM = (1u << 1),
/**
* The VM is capable of executing the precompiled contracts
* defined for the range of code addresses.
*
* The EIP-1352 (https://eips.ethereum.org/EIPS/eip-1352) specifies
* the range 0x000...0000 - 0x000...ffff of addresses
* reserved for precompiled and system contracts.
*
* This capability is **experimental** and MAY be removed without notice.
*/
EVMC_CAPABILITY_PRECOMPILES = (1u << 2)
};
/**
* Alias for unsigned integer representing a set of bit flags of EVMC capabilities.
*
* @see evmc_capabilities
*/
typedef uint32_t evmc_capabilities_flagset;
/**
* Return the supported capabilities of the VM instance.
*
* This function MAY be invoked multiple times for a single VM instance,
* and its value MAY be influenced by calls to evmc_vm::set_option.
*
* @param vm The VM instance.
* @return The supported capabilities of the VM. @see evmc_capabilities.
*/
typedef evmc_capabilities_flagset (*evmc_get_capabilities_fn)(struct evmc_vm* vm);
/**
* The VM instance.
*
* Defines the base struct of the VM implementation.
*/
struct evmc_vm
{
/**
* EVMC ABI version implemented by the VM instance.
*
* Can be used to detect ABI incompatibilities.
* The EVMC ABI version represented by this file is in ::EVMC_ABI_VERSION.
*/
const int abi_version;
/**
* The name of the EVMC VM implementation.
*
* It MUST be a NULL-terminated not empty string.
* The content MUST be UTF-8 encoded (this implies ASCII encoding is also allowed).
*/
const char* name;
/**
* The version of the EVMC VM implementation, e.g. "1.2.3b4".
*
* It MUST be a NULL-terminated not empty string.
* The content MUST be UTF-8 encoded (this implies ASCII encoding is also allowed).
*/
const char* version;
/**
* Pointer to function destroying the VM instance.
*
* This is a mandatory method and MUST NOT be set to NULL.
*/
evmc_destroy_fn destroy;
/**
* Pointer to function executing a code by the VM instance.
*
* This is a mandatory method and MUST NOT be set to NULL.
*/
evmc_execute_fn execute;
/**
* A method returning capabilities supported by the VM instance.
*
* The value returned MAY change when different options are set via the set_option() method.
*
* A Client SHOULD only rely on the value returned if it has queried it after
* it has called the set_option().
*
* This is a mandatory method and MUST NOT be set to NULL.
*/
evmc_get_capabilities_fn get_capabilities;
/**
* Optional pointer to function modifying VM's options.
*
* If the VM does not support this feature the pointer can be NULL.
*/
evmc_set_option_fn set_option;
};
/* END Python CFFI declarations */
#ifdef EVMC_DOCUMENTATION
/**
* Example of a function creating an instance of an example EVM implementation.
*
* Each EVM implementation MUST provide a function returning an EVM instance.
* The function SHOULD be named `evmc_create_<vm-name>(void)`. If the VM name contains hyphens
* replaces them with underscores in the function names.
*
* @par Binaries naming convention
* For VMs distributed as shared libraries, the name of the library SHOULD match the VM name.
* The conventional library filename prefixes and extensions SHOULD be ignored by the Client.
* For example, the shared library with the "beta-interpreter" implementation may be named
* `libbeta-interpreter.so`.
*
* @return The VM instance or NULL indicating instance creation failure.
*/
struct evmc_vm* evmc_create_example_vm(void);
#endif
#ifdef __cplusplus
}
#endif
#endif
/** @} */
| 40,777
|
C++
|
.h
| 1,078
| 32.397959
| 108
| 0.654505
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,373
|
helpers.h
|
ethereum_solidity/test/evmc/helpers.h
|
// EVMC: Ethereum Client-VM Connector API.
// Copyright 2018 The EVMC Authors.
// Licensed under the Apache License, Version 2.0.
/**
* EVMC Helpers
*
* A collection of C helper functions for invoking a VM instance methods.
* These are convenient for languages where invoking function pointers
* is "ugly" or impossible (such as Go).
*
* @defgroup helpers EVMC Helpers
* @{
*/
#pragma once
#include <evmc/evmc.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
#endif
/**
* Returns true if the VM has a compatible ABI version.
*/
static inline bool evmc_is_abi_compatible(struct evmc_vm* vm)
{
return vm->abi_version == EVMC_ABI_VERSION;
}
/**
* Returns the name of the VM.
*/
static inline const char* evmc_vm_name(struct evmc_vm* vm)
{
return vm->name;
}
/**
* Returns the version of the VM.
*/
static inline const char* evmc_vm_version(struct evmc_vm* vm)
{
return vm->version;
}
/**
* Checks if the VM has the given capability.
*
* @see evmc_get_capabilities_fn
*/
static inline bool evmc_vm_has_capability(struct evmc_vm* vm, enum evmc_capabilities capability)
{
return (vm->get_capabilities(vm) & (evmc_capabilities_flagset)capability) != 0;
}
/**
* Destroys the VM instance.
*
* @see evmc_destroy_fn
*/
static inline void evmc_destroy(struct evmc_vm* vm)
{
vm->destroy(vm);
}
/**
* Sets the option for the VM, if the feature is supported by the VM.
*
* @see evmc_set_option_fn
*/
static inline enum evmc_set_option_result evmc_set_option(struct evmc_vm* vm,
char const* name,
char const* value)
{
if (vm->set_option)
return vm->set_option(vm, name, value);
return EVMC_SET_OPTION_INVALID_NAME;
}
/**
* Executes code in the VM instance.
*
* @see evmc_execute_fn.
*/
static inline struct evmc_result evmc_execute(struct evmc_vm* vm,
const struct evmc_host_interface* host,
struct evmc_host_context* context,
enum evmc_revision rev,
const struct evmc_message* msg,
uint8_t const* code,
size_t code_size)
{
return vm->execute(vm, host, context, rev, msg, code, code_size);
}
/// The evmc_result release function using free() for releasing the memory.
///
/// This function is used in the evmc_make_result(),
/// but may be also used in other case if convenient.
///
/// @param result The result object.
static void evmc_free_result_memory(const struct evmc_result* result)
{
free((uint8_t*)result->output_data);
}
/// Creates the result from the provided arguments.
///
/// The provided output is copied to memory allocated with malloc()
/// and the evmc_result::release function is set to one invoking free().
///
/// In case of memory allocation failure, the result has all fields zeroed
/// and only evmc_result::status_code is set to ::EVMC_OUT_OF_MEMORY internal error.
///
/// @param status_code The status code.
/// @param gas_left The amount of gas left.
/// @param gas_refund The amount of refunded gas.
/// @param output_data The pointer to the output.
/// @param output_size The output size.
static inline struct evmc_result evmc_make_result(enum evmc_status_code status_code,
int64_t gas_left,
int64_t gas_refund,
const uint8_t* output_data,
size_t output_size)
{
struct evmc_result result;
memset(&result, 0, sizeof(result));
if (output_size != 0)
{
uint8_t* buffer = (uint8_t*)malloc(output_size);
if (!buffer)
{
result.status_code = EVMC_OUT_OF_MEMORY;
return result;
}
memcpy(buffer, output_data, output_size);
result.output_data = buffer;
result.output_size = output_size;
result.release = evmc_free_result_memory;
}
result.status_code = status_code;
result.gas_left = gas_left;
result.gas_refund = gas_refund;
return result;
}
/**
* Releases the resources allocated to the execution result.
*
* @param result The result object to be released. MUST NOT be NULL.
*
* @see evmc_result::release() evmc_release_result_fn
*/
static inline void evmc_release_result(struct evmc_result* result)
{
if (result->release)
result->release(result);
}
/**
* Helpers for optional storage of evmc_result.
*
* In some contexts (i.e. evmc_result::create_address is unused) objects of
* type evmc_result contains a memory storage that MAY be used by the object
* owner. This group defines helper types and functions for accessing
* the optional storage.
*
* @defgroup result_optional_storage Result Optional Storage
* @{
*/
/**
* The union representing evmc_result "optional storage".
*
* The evmc_result struct contains 24 bytes of optional storage that can be
* reused by the object creator if the object does not contain
* evmc_result::create_address.
*
* A VM implementation MAY use this memory to keep additional data
* when returning result from evmc_execute_fn().
* The host application MAY use this memory to keep additional data
* when returning result of performed calls from evmc_call_fn().
*
* @see evmc_get_optional_storage(), evmc_get_const_optional_storage().
*/
union evmc_result_optional_storage
{
uint8_t bytes[24]; /**< 24 bytes of optional storage. */
void* pointer; /**< Optional pointer. */
};
/** Provides read-write access to evmc_result "optional storage". */
static inline union evmc_result_optional_storage* evmc_get_optional_storage(
struct evmc_result* result)
{
return (union evmc_result_optional_storage*)&result->create_address;
}
/** Provides read-only access to evmc_result "optional storage". */
static inline const union evmc_result_optional_storage* evmc_get_const_optional_storage(
const struct evmc_result* result)
{
return (const union evmc_result_optional_storage*)&result->create_address;
}
/** @} */
/** Returns text representation of the ::evmc_status_code. */
static inline const char* evmc_status_code_to_string(enum evmc_status_code status_code)
{
switch (status_code)
{
case EVMC_SUCCESS:
return "success";
case EVMC_FAILURE:
return "failure";
case EVMC_REVERT:
return "revert";
case EVMC_OUT_OF_GAS:
return "out of gas";
case EVMC_INVALID_INSTRUCTION:
return "invalid instruction";
case EVMC_UNDEFINED_INSTRUCTION:
return "undefined instruction";
case EVMC_STACK_OVERFLOW:
return "stack overflow";
case EVMC_STACK_UNDERFLOW:
return "stack underflow";
case EVMC_BAD_JUMP_DESTINATION:
return "bad jump destination";
case EVMC_INVALID_MEMORY_ACCESS:
return "invalid memory access";
case EVMC_CALL_DEPTH_EXCEEDED:
return "call depth exceeded";
case EVMC_STATIC_MODE_VIOLATION:
return "static mode violation";
case EVMC_PRECOMPILE_FAILURE:
return "precompile failure";
case EVMC_CONTRACT_VALIDATION_FAILURE:
return "contract validation failure";
case EVMC_ARGUMENT_OUT_OF_RANGE:
return "argument out of range";
case EVMC_WASM_UNREACHABLE_INSTRUCTION:
return "wasm unreachable instruction";
case EVMC_WASM_TRAP:
return "wasm trap";
case EVMC_INSUFFICIENT_BALANCE:
return "insufficient balance";
case EVMC_INTERNAL_ERROR:
return "internal error";
case EVMC_REJECTED:
return "rejected";
case EVMC_OUT_OF_MEMORY:
return "out of memory";
}
return "<unknown>";
}
/** Returns the name of the ::evmc_revision. */
static inline const char* evmc_revision_to_string(enum evmc_revision rev)
{
switch (rev)
{
case EVMC_FRONTIER:
return "Frontier";
case EVMC_HOMESTEAD:
return "Homestead";
case EVMC_TANGERINE_WHISTLE:
return "Tangerine Whistle";
case EVMC_SPURIOUS_DRAGON:
return "Spurious Dragon";
case EVMC_BYZANTIUM:
return "Byzantium";
case EVMC_CONSTANTINOPLE:
return "Constantinople";
case EVMC_PETERSBURG:
return "Petersburg";
case EVMC_ISTANBUL:
return "Istanbul";
case EVMC_BERLIN:
return "Berlin";
case EVMC_LONDON:
return "London";
case EVMC_PARIS:
return "Paris";
case EVMC_SHANGHAI:
return "Shanghai";
case EVMC_CANCUN:
return "Cancun";
case EVMC_PRAGUE:
return "Prague";
case EVMC_OSAKA:
return "Osaka";
}
return "<unknown>";
}
/** @} */
#ifdef __cplusplus
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
} // extern "C"
#endif
| 9,162
|
C++
|
.h
| 290
| 25.948276
| 96
| 0.652798
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
3,374
|
bytes.hpp
|
ethereum_solidity/test/evmc/bytes.hpp
|
// EVMC: Ethereum Client-VM Connector API.
// Copyright 2024 The EVMC Authors.
// Licensed under the Apache License, Version 2.0.
#pragma once
#include <algorithm>
#include <cstring>
#include <string>
#include <string_view>
namespace evmc
{
/// The char traits for byte-like types.
///
/// See: https://en.cppreference.com/w/cpp/string/char_traits.
template <typename T>
struct byte_traits : std::char_traits<char>
{
static_assert(sizeof(T) == 1, "type must be a byte");
using char_type = T; ///< The byte type.
/// Assigns c2 to c1.
static constexpr void assign(char_type& c1, const char_type& c2) { c1 = c2; }
/// Assigns value to each byte in [ptr, ptr+count).
static constexpr char_type* assign(char_type* ptr, std::size_t count, char_type value)
{
std::fill_n(ptr, count, value);
return ptr;
}
/// Returns true if bytes are equal.
static constexpr bool eq(char_type a, char_type b) { return a == b; }
/// Returns true if byte a is less than byte b.
static constexpr bool lt(char_type a, char_type b) { return a < b; }
/// Copies count bytes from src to dest. Performs correctly even if ranges overlap.
static constexpr char_type* move(char_type* dest, const char_type* src, std::size_t count)
{
if (dest < src)
std::copy_n(src, count, dest);
else if (src < dest)
std::copy_backward(src, src + count, dest + count);
return dest;
}
/// Copies count bytes from src to dest. The ranges must not overlap.
static constexpr char_type* copy(char_type* dest, const char_type* src, std::size_t count)
{
std::copy_n(src, count, dest);
return dest;
}
/// Compares lexicographically the bytes in two ranges of equal length.
static constexpr int compare(const char_type* a, const char_type* b, std::size_t count)
{
for (; count != 0; --count, ++a, ++b)
{
if (lt(*a, *b))
return -1;
if (lt(*b, *a))
return 1;
}
return 0;
}
/// Returns the length of a null-terminated byte string.
// TODO: Not constexpr
static std::size_t length(const char_type* s)
{
return std::strlen(reinterpret_cast<const char*>(s));
}
/// Finds the value in the range of bytes and returns the pointer to the first occurrence
/// or nullptr if not found.
static constexpr const char_type* find(const char_type* s,
std::size_t count,
const char_type& value)
{
const auto end = s + count;
const auto p = std::find(s, end, value);
return p != end ? p : nullptr;
}
};
/// String of unsigned chars representing bytes.
using bytes = std::basic_string<unsigned char, byte_traits<unsigned char>>;
/// String view of unsigned chars representing bytes.
using bytes_view = std::basic_string_view<unsigned char, byte_traits<unsigned char>>;
} // namespace evmc
| 3,048
|
C++
|
.h
| 79
| 32.063291
| 94
| 0.620981
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,386
|
Program.h
|
ethereum_solidity/tools/yulPhaser/Program.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/AST.h>
#include <liblangutil/Exceptions.h>
#include <cstddef>
#include <optional>
#include <ostream>
#include <set>
#include <string>
#include <variant>
#include <vector>
namespace solidity::langutil
{
class CharStream;
class Scanner;
}
namespace solidity::yul
{
struct AsmAnalysisInfo;
struct Dialect;
struct CodeWeights;
}
namespace solidity::phaser
{
/**
* Class representing parsed and analysed Yul program that we can apply optimisations to.
* The program is already disambiguated and has several prerequisite optimiser steps applied to it
* so that the requirements of any possible step that could be later applied by the user are
* already satisfied.
*
* The class allows the user to apply extra optimisations and obtain metrics and general
* information about the resulting syntax tree.
*/
class Program
{
public:
Program(Program const& program);
Program(Program&& program):
m_ast(std::move(program.m_ast)),
m_dialect{program.m_dialect},
m_nameDispenser(std::move(program.m_nameDispenser))
{}
Program operator=(Program const& program) = delete;
Program operator=(Program&& program) = delete;
static std::variant<Program, langutil::ErrorList> load(langutil::CharStream& _sourceCode);
void optimise(std::vector<std::string> const& _optimisationSteps);
size_t codeSize(yul::CodeWeights const& _weights) const { return computeCodeSize(m_ast->root(), _weights); }
yul::Block const& ast() const { return m_ast->root(); }
friend std::ostream& operator<<(std::ostream& _stream, Program const& _program);
std::string toJson() const;
private:
Program(
yul::Dialect const& _dialect,
std::unique_ptr<yul::AST> _ast
):
m_ast(std::move(_ast)),
m_dialect{_dialect},
m_nameDispenser(_dialect, m_ast->root(), {})
{}
static std::variant<std::unique_ptr<yul::AST>, langutil::ErrorList> parseObject(
yul::Dialect const& _dialect,
langutil::CharStream _source
);
static std::variant<std::unique_ptr<yul::AsmAnalysisInfo>, langutil::ErrorList> analyzeAST(
yul::Dialect const& _dialect,
yul::AST const& _ast
);
static std::unique_ptr<yul::AST> disambiguateAST(
yul::Dialect const& _dialect,
yul::AST const& _ast,
yul::AsmAnalysisInfo const& _analysisInfo
);
static std::unique_ptr<yul::AST> applyOptimisationSteps(
yul::Dialect const& _dialect,
yul::NameDispenser& _nameDispenser,
std::unique_ptr<yul::AST> _ast,
std::vector<std::string> const& _optimisationSteps
);
static size_t computeCodeSize(yul::Block const& _ast, yul::CodeWeights const& _weights);
std::unique_ptr<yul::AST> m_ast;
yul::Dialect const& m_dialect;
yul::NameDispenser m_nameDispenser;
};
}
| 3,396
|
C++
|
.h
| 98
| 32.581633
| 109
| 0.763126
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,389
|
SideEffects.h
|
ethereum_solidity/libyul/SideEffects.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <algorithm>
#include <set>
namespace solidity::yul
{
/**
* Side effects of code.
*
* The default-constructed value applies to the "empty code".
*/
struct SideEffects
{
/// Corresponds to the effect that a Yul-builtin has on a generic data location (storage, memory
/// and other blockchain state).
enum Effect
{
None,
Read,
Write
};
friend Effect operator+(Effect const& _a, Effect const& _b)
{
return static_cast<Effect>(std::max(static_cast<int>(_a), static_cast<int>(_b)));
}
/// If true, expressions in this code can be freely moved and copied without altering the
/// semantics.
/// At statement level, it means that functions containing this code can be
/// called multiple times, their calls can be rearranged and calls can also be
/// deleted without changing the semantics.
/// This means it cannot depend on storage, memory or transient storage, cannot have any side-effects,
/// but it can depend on state that is constant across an EVM-call.
bool movable = true;
/// If true, the expressions in this code can be moved or copied (together with their arguments)
/// across control flow branches and instructions as long as these instructions' 'effects' do
/// not influence the 'effects' of the aforementioned expressions.
bool movableApartFromEffects = true;
/// If true, the code can be removed without changing the semantics.
bool canBeRemoved = true;
/// If true, the code can be removed without changing the semantics as long as
/// the whole program does not contain the msize instruction.
bool canBeRemovedIfNoMSize = true;
/// If false, the code calls a for-loop or a recursive function, and therefore potentially loops
/// infinitely. All builtins are set to true by default, even `invalid()`.
bool cannotLoop = true;
/// Can write, read or have no effect on the blockchain state, when the value of `otherState` is
/// `Write`, `Read` or `None` respectively.
Effect otherState = None;
/// Can write, read or have no effect on storage, when the value of `storage` is `Write`, `Read`
/// or `None` respectively. When the value is `Write`, the expression can invalidate storage,
/// potentially indirectly through external calls.
Effect storage = None;
/// Can write, read or have no effect on memory, when the value of `memory` is `Write`, `Read`
/// or `None` respectively. Note that, when the value is `Read`, the expression can have an
/// effect on `msize()`.
Effect memory = None;
/// Can write, read or have no effect on transient storage, when the value of `transientStorage` is `Write`, `Read`
/// or `None` respectively. When the value is `Write`, the expression can invalidate transient storage,
/// potentially indirectly through external calls.
Effect transientStorage = None;
/// @returns the worst-case side effects.
static SideEffects worst()
{
return SideEffects{false, false, false, false, false, Write, Write, Write, Write};
}
/// @returns the combined side effects of two pieces of code.
SideEffects operator+(SideEffects const& _other)
{
return SideEffects{
movable && _other.movable,
movableApartFromEffects && _other.movableApartFromEffects,
canBeRemoved && _other.canBeRemoved,
canBeRemovedIfNoMSize && _other.canBeRemovedIfNoMSize,
cannotLoop && _other.cannotLoop,
otherState + _other.otherState,
storage + _other.storage,
memory + _other.memory,
transientStorage + _other.transientStorage
};
}
/// Adds the side effects of another piece of code to this side effect.
SideEffects& operator+=(SideEffects const& _other)
{
*this = *this + _other;
return *this;
}
bool operator==(SideEffects const& _other) const
{
return
movable == _other.movable &&
movableApartFromEffects == _other.movableApartFromEffects &&
canBeRemoved == _other.canBeRemoved &&
canBeRemovedIfNoMSize == _other.canBeRemovedIfNoMSize &&
cannotLoop == _other.cannotLoop &&
otherState == _other.otherState &&
storage == _other.storage &&
memory == _other.memory &&
transientStorage == _other.transientStorage;
}
};
}
| 4,778
|
C++
|
.h
| 114
| 39.5
| 116
| 0.746237
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,392
|
ControlFlowSideEffects.h
|
ethereum_solidity/libyul/ControlFlowSideEffects.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libevmasm/Instruction.h>
#include <libevmasm/SemanticInformation.h>
namespace solidity::yul
{
/**
* Side effects of a user-defined or builtin function.
*
* Each of the three booleans represents a reachability condition. There is an implied
* fourth alternative, which is going out of gas while executing the function. Since
* this can always happen and depends on the supply of gas, it is not considered.
*
* If all three booleans are false, it means that the function always leads to infinite
* recursion.
*/
struct ControlFlowSideEffects
{
/// If true, the function contains at least one reachable branch that terminates successfully.
bool canTerminate = false;
/// If true, the function contains at least one reachable branch that reverts.
bool canRevert = false;
/// If true, the function has a regular outgoing control-flow.
bool canContinue = true;
bool terminatesOrReverts() const
{
return (canTerminate || canRevert) && !canContinue;
}
static ControlFlowSideEffects fromInstruction(evmasm::Instruction _instruction)
{
ControlFlowSideEffects controlFlowSideEffects;
if (evmasm::SemanticInformation::terminatesControlFlow(_instruction))
{
controlFlowSideEffects.canContinue = false;
if (evmasm::SemanticInformation::reverts(_instruction))
{
controlFlowSideEffects.canTerminate = false;
controlFlowSideEffects.canRevert = true;
}
else
{
controlFlowSideEffects.canTerminate = true;
controlFlowSideEffects.canRevert = false;
}
}
return controlFlowSideEffects;
}
};
}
| 2,256
|
C++
|
.h
| 62
| 33.903226
| 95
| 0.7847
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,394
|
AST.h
|
ethereum_solidity/libyul/AST.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Parsed inline assembly to be used by the AST
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <liblangutil/DebugData.h>
#include <libsolutil/Numeric.h>
#include <memory>
#include <optional>
namespace solidity::yul
{
struct NameWithDebugData { langutil::DebugData::ConstPtr debugData; YulName name; };
using NameWithDebugDataList = std::vector<NameWithDebugData>;
/// Literal number or string (up to 32 bytes)
enum class LiteralKind { Number, Boolean, String };
/// Literal value that holds a u256 word of data, can be of LiteralKind type and - in case of arguments to
/// builtins - exceed the u256 word (32 bytes), in which case the value is stored as string. The former is constructed
/// via u256 word and optional hint and leads to unlimited == false, the latter is
/// constructed via the string constructor and leads to unlimited == true.
class LiteralValue {
public:
using Data = u256;
using BuiltinStringLiteralData = std::string;
using RepresentationHint = std::shared_ptr<std::string>;
LiteralValue() = default;
explicit LiteralValue(std::string _builtinStringLiteralValue);
explicit LiteralValue(Data const& _data, std::optional<std::string> const& _hint = std::nullopt);
bool operator==(LiteralValue const& _rhs) const;
bool operator<(LiteralValue const& _rhs) const;
Data const& value() const;
BuiltinStringLiteralData const& builtinStringLiteralValue() const;
bool unlimited() const;
RepresentationHint const& hint() const;
private:
std::optional<Data> m_numericValue;
std::shared_ptr<std::string> m_stringValue;
};
struct Literal { langutil::DebugData::ConstPtr debugData; LiteralKind kind; LiteralValue value; };
/// External / internal identifier or label reference
struct Identifier { langutil::DebugData::ConstPtr debugData; YulName name; };
/// Assignment ("x := mload(20:u256)", expects push-1-expression on the right hand
/// side and requires x to occupy exactly one stack slot.
///
/// Multiple assignment ("x, y := f()"), where the left hand side variables each occupy
/// a single stack slot and expects a single expression on the right hand returning
/// the same amount of items as the number of variables.
struct Assignment { langutil::DebugData::ConstPtr debugData; std::vector<Identifier> variableNames; std::unique_ptr<Expression> value; };
struct FunctionCall { langutil::DebugData::ConstPtr debugData; Identifier functionName; std::vector<Expression> arguments; };
/// Statement that contains only a single expression
struct ExpressionStatement { langutil::DebugData::ConstPtr debugData; Expression expression; };
/// Block-scope variable declaration ("let x:u256 := mload(20:u256)"), non-hoisted
struct VariableDeclaration { langutil::DebugData::ConstPtr debugData; NameWithDebugDataList variables; std::unique_ptr<Expression> value; };
/// Block that creates a scope (frees declared stack variables)
struct Block { langutil::DebugData::ConstPtr debugData; std::vector<Statement> statements; };
/// Function definition ("function f(a, b) -> (d, e) { ... }")
struct FunctionDefinition { langutil::DebugData::ConstPtr debugData; YulName name; NameWithDebugDataList parameters; NameWithDebugDataList returnVariables; Block body; };
/// Conditional execution without "else" part.
struct If { langutil::DebugData::ConstPtr debugData; std::unique_ptr<Expression> condition; Block body; };
/// Switch case or default case
struct Case { langutil::DebugData::ConstPtr debugData; std::unique_ptr<Literal> value; Block body; };
/// Switch statement
struct Switch { langutil::DebugData::ConstPtr debugData; std::unique_ptr<Expression> expression; std::vector<Case> cases; };
struct ForLoop { langutil::DebugData::ConstPtr debugData; Block pre; std::unique_ptr<Expression> condition; Block post; Block body; };
/// Break statement (valid within for loop)
struct Break { langutil::DebugData::ConstPtr debugData; };
/// Continue statement (valid within for loop)
struct Continue { langutil::DebugData::ConstPtr debugData; };
/// Leave statement (valid within function)
struct Leave { langutil::DebugData::ConstPtr debugData; };
/// Immutable AST comprised of its top-level block
class AST
{
public:
explicit AST(Block _root): m_root(std::move(_root)) {}
[[nodiscard]] Block const& root() const { return m_root; }
private:
Block m_root;
};
/// Extracts the IR source location from a Yul node.
template <class T> inline langutil::SourceLocation nativeLocationOf(T const& _node)
{
return _node.debugData ? _node.debugData->nativeLocation : langutil::SourceLocation{};
}
/// Extracts the IR source location from a Yul node.
template <class... Args> inline langutil::SourceLocation nativeLocationOf(std::variant<Args...> const& _node)
{
return std::visit([](auto const& _arg) { return nativeLocationOf(_arg); }, _node);
}
/// Extracts the original source location from a Yul node.
template <class T> inline langutil::SourceLocation originLocationOf(T const& _node)
{
return _node.debugData ? _node.debugData->originLocation : langutil::SourceLocation{};
}
/// Extracts the original source location from a Yul node.
template <class... Args> inline langutil::SourceLocation originLocationOf(std::variant<Args...> const& _node)
{
return std::visit([](auto const& _arg) { return originLocationOf(_arg); }, _node);
}
/// Extracts the debug data from a Yul node.
template <class T> inline langutil::DebugData::ConstPtr debugDataOf(T const& _node)
{
return _node.debugData;
}
/// Extracts the debug data from a Yul node.
template <class... Args> inline langutil::DebugData::ConstPtr debugDataOf(std::variant<Args...> const& _node)
{
return std::visit([](auto const& _arg) { return debugDataOf(_arg); }, _node);
}
inline bool hasDefaultCase(Switch const& _switch)
{
return std::any_of(
_switch.cases.begin(),
_switch.cases.end(),
[](Case const& _case) { return !_case.value; }
);
}
}
| 6,622
|
C++
|
.h
| 134
| 47.88806
| 170
| 0.765125
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,396
|
Object.h
|
ethereum_solidity/libyul/Object.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul code and data object container.
*/
#pragma once
#include <libyul/AsmPrinter.h>
#include <libyul/ASTForward.h>
#include <liblangutil/CharStreamProvider.h>
#include <liblangutil/DebugInfoSelection.h>
#include <libsolutil/Common.h>
#include <libsolutil/JSON.h>
#include <memory>
#include <set>
#include <limits>
namespace solidity::yul
{
struct Dialect;
struct AsmAnalysisInfo;
using SourceNameMap = std::map<unsigned, std::shared_ptr<std::string const>>;
class Object;
/**
* Generic base class for both Yul objects and Yul data.
*/
struct ObjectNode
{
virtual ~ObjectNode() = default;
/// Name of the object.
/// Can be empty since .yul files can also just contain code, without explicitly placing it in an object.
std::string name;
virtual std::string toString(
langutil::DebugInfoSelection const& _debugInfoSelection,
langutil::CharStreamProvider const* _soliditySourceProvider
) const = 0;
virtual Json toJson() const = 0;
};
/**
* Named data in Yul objects.
*/
struct Data: public ObjectNode
{
Data(std::string _name, bytes _data): data(std::move(_data)) { name = _name; }
bytes data;
std::string toString(
langutil::DebugInfoSelection const& _debugInfoSelection,
langutil::CharStreamProvider const* _soliditySourceProvider
) const override;
Json toJson() const override;
};
struct ObjectDebugData
{
std::optional<SourceNameMap> sourceNames = {};
std::string formatUseSrcComment() const;
};
/**
* Yul code and data object container.
*/
class Object: public ObjectNode
{
public:
explicit Object(Dialect const& _dialect): m_dialect(_dialect) {}
/// @returns a (parseable) string representation.
std::string toString(
langutil::DebugInfoSelection const& _debugInfoSelection = langutil::DebugInfoSelection::Default(),
langutil::CharStreamProvider const* _soliditySourceProvider = nullptr
) const override;
/// @returns a compact JSON representation of the AST.
Json toJson() const override;
/// Summarizes the structure of the subtree rooted at a given object,
/// in particular the paths that can be used from within to refer to nested nodes (objects and data).
struct Structure
{
/// The name of the object
std::string objectName;
/// Available dot-separated paths to nested objects (relative to current object).
std::set<std::string> objectPaths;
/// Available dot-separated paths to nested data entries (relative to current object).
std::set<std::string> dataPaths;
/// Checks if a path is available.
bool contains(std::string const& _path) const { return containsObject(_path) || containsData(_path); }
/// Checks if a path is available and leads to an object.
bool containsObject(std::string const& _path) const { return objectPaths.count(_path) > 0; }
/// Checks if a path is available and leads to a data entry.
bool containsData(std::string const& _path) const { return dataPaths.count(_path) > 0; }
std::set<std::string> topLevelSubObjectNames() const;
};
/// @returns the set of names of data objects accessible from within the code of
/// this object, including the name of object itself
/// Handles all names containing dots as reserved identifiers, not accessible as data.
Structure summarizeStructure() const;
/// @returns vector of subIDs if possible to reach subobject with @a _qualifiedName, throws otherwise
/// For "B.C" should return vector of two values if success (subId of B and subId of C in B).
/// In object "A" if called for "A.B" will return only one value (subId for B)
/// will return empty vector for @a _qualifiedName that equals to object name.
/// Example:
/// A1{ B2{ C3, D3 }, E2{ F3{ G4, K4, H4{ I5 } } } }
/// pathToSubObject("A1.E2.F3.H4") == {1, 0, 2}
/// pathToSubObject("E2.F3.H4") == {1, 0, 2}
/// pathToSubObject("A1.E2") == {1}
/// The path must not lead to a @a Data object (will throw in that case).
std::vector<size_t> pathToSubObject(std::string_view _qualifiedName) const;
std::shared_ptr<AST const> code() const;
void setCode(std::shared_ptr<AST const> const& _ast, std::shared_ptr<yul::AsmAnalysisInfo> = nullptr);
bool hasCode() const;
/// sub id for object if it is subobject of another object, max value if it is not subobject
size_t subId = std::numeric_limits<size_t>::max();
std::vector<std::shared_ptr<ObjectNode>> subObjects;
std::map<std::string, size_t, std::less<>> subIndexByName;
std::shared_ptr<yul::AsmAnalysisInfo> analysisInfo;
std::shared_ptr<ObjectDebugData const> debugData;
/// Collects names of all Solidity source units present in the debug data
/// of the Yul object (including sub-objects) and their assigned indices.
/// @param _indices map that will be filled with source indices of the current Yul object & its sub-objects.
void collectSourceIndices(std::map<std::string, unsigned>& _indices) const;
/// @returns true, if the range of source indices starts at zero and is contiguous, false otherwise.
bool hasContiguousSourceIndices() const;
/// @returns the name of the special metadata data object.
static std::string metadataName() { return ".metadata"; }
Dialect const& dialect() const { return m_dialect; }
private:
Dialect const& m_dialect;
std::shared_ptr<AST const> m_code;
};
}
| 5,900
|
C++
|
.h
| 136
| 41.257353
| 109
| 0.750175
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,397
|
YulControlFlowGraphExporter.h
|
ethereum_solidity/libyul/YulControlFlowGraphExporter.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/backends/evm/ControlFlow.h>
#include <libsolutil/JSON.h>
#include <libsolutil/Visitor.h>
using namespace solidity;
using namespace yul;
class YulControlFlowGraphExporter
{
public:
YulControlFlowGraphExporter(ControlFlow const& _controlFlow);
Json run();
Json exportBlock(SSACFG const& _cfg, SSACFG::BlockId _blockId);
Json exportFunction(SSACFG const& _cfg);
std::string varToString(SSACFG const& _cfg, SSACFG::ValueId _var);
private:
ControlFlow const& m_controlFlow;
Json toJson(SSACFG const& _cfg, SSACFG::BlockId _blockId);
Json toJson(Json& _ret, SSACFG const& _cfg, SSACFG::Operation const& _operation);
Json toJson(SSACFG const& _cfg, std::vector<SSACFG::ValueId> const& _values);
};
| 1,420
|
C++
|
.h
| 34
| 39.941176
| 82
| 0.787373
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,398
|
Builtins.h
|
ethereum_solidity/libyul/Builtins.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <cstddef>
namespace solidity::yul
{
/// Handle to reference a builtin function in the AST
struct BuiltinHandle
{
size_t id;
bool operator==(BuiltinHandle const& _other) const { return id == _other.id; }
bool operator<(BuiltinHandle const& _other) const { return id < _other.id; }
};
}
| 1,001
|
C++
|
.h
| 26
| 36.615385
| 79
| 0.774327
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,399
|
YulName.h
|
ethereum_solidity/libyul/YulName.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/YulString.h>
namespace solidity::yul
{
using YulName = YulString;
}
| 786
|
C++
|
.h
| 20
| 37.45
| 69
| 0.790789
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,400
|
Scope.h
|
ethereum_solidity/libyul/Scope.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Scopes for identifiers.
*/
#pragma once
#include <liblangutil/Exceptions.h>
#include <libyul/YulName.h>
#include <functional>
#include <memory>
#include <optional>
#include <variant>
namespace solidity::yul
{
struct Scope
{
struct Variable
{
YulName name;
};
struct Function
{
size_t numArguments;
size_t numReturns;
YulName name;
};
using Identifier = std::variant<Variable, Function>;
bool registerVariable(YulName _name);
bool registerFunction(
YulName _name,
size_t _numArguments,
size_t _numReturns
);
/// Looks up the identifier in this or super scopes and returns a valid pointer if found
/// or a nullptr if not found. Variable lookups up across function boundaries will fail, as
/// will any lookups across assembly boundaries.
/// The pointer will be invalidated if the scope is modified.
/// @param _crossedFunction if true, we already crossed a function boundary during recursive lookup
Identifier* lookup(YulName _name);
/// Looks up the identifier in this and super scopes (will not find variables across function
/// boundaries and generally stops at assembly boundaries) and calls the visitor, returns
/// false if not found.
template <class V>
bool lookup(YulName _name, V const& _visitor)
{
if (Identifier* id = lookup(_name))
{
std::visit(_visitor, *id);
return true;
}
else
return false;
}
/// @returns true if the name exists in this scope or in super scopes (also searches
/// across function and assembly boundaries).
bool exists(YulName _name) const;
/// @returns the number of variables directly registered inside the scope.
size_t numberOfVariables() const;
/// @returns true if this scope is inside a function.
bool insideFunction() const;
Scope* superScope = nullptr;
/// If true, variables from the super scope are not visible here (other identifiers are),
/// but they are still taken into account to prevent shadowing.
bool functionScope = false;
std::map<YulName, Identifier> identifiers;
};
}
| 2,697
|
C++
|
.h
| 79
| 31.949367
| 100
| 0.764118
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,401
|
Dialect.h
|
ethereum_solidity/libyul/Dialect.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul dialect.
*/
#pragma once
#include <libyul/Builtins.h>
#include <libyul/ControlFlowSideEffects.h>
#include <libyul/Exceptions.h>
#include <libyul/SideEffects.h>
#include <libyul/YulString.h>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace solidity::yul
{
enum class LiteralKind;
class LiteralValue;
struct Literal;
struct BuiltinFunction
{
std::string name;
size_t numParameters;
size_t numReturns;
SideEffects sideEffects;
ControlFlowSideEffects controlFlowSideEffects;
/// If true, this is the msize instruction or might contain it.
bool isMSize = false;
/// Must be empty or the same length as the arguments.
/// If set at index i, the i'th argument has to be a literal which means it can't be moved to variables.
std::vector<std::optional<LiteralKind>> literalArguments{};
std::optional<LiteralKind> literalArgument(size_t i) const
{
return literalArguments.empty() ? std::nullopt : literalArguments.at(i);
}
};
struct Dialect
{
/// Noncopiable.
Dialect(Dialect const&) = delete;
Dialect& operator=(Dialect const&) = delete;
/// Finds a builtin by name and returns the corresponding handle.
/// @returns Builtin handle or null if the name does not match any builtin in the dialect.
virtual std::optional<BuiltinHandle> findBuiltin(std::string_view /*_name*/) const { return std::nullopt; }
/// Retrieves the description of a builtin function by its handle.
/// Note that handles are dialect-specific and can be used only with a dialect that created them.
virtual BuiltinFunction const& builtin(BuiltinHandle const&) const { yulAssert(false); }
/// @returns true if the identifier is reserved. This includes the builtins too.
virtual bool reservedIdentifier(std::string_view _name) const { return findBuiltin(_name).has_value(); }
virtual std::optional<BuiltinHandle> discardFunctionHandle() const { return std::nullopt; }
virtual std::optional<BuiltinHandle> equalityFunctionHandle() const { return std::nullopt; }
virtual std::optional<BuiltinHandle> booleanNegationFunctionHandle() const { return std::nullopt; }
virtual std::optional<BuiltinHandle> memoryStoreFunctionHandle() const { return std::nullopt; }
virtual std::optional<BuiltinHandle> memoryLoadFunctionHandle() const { return std::nullopt; }
virtual std::optional<BuiltinHandle> storageStoreFunctionHandle() const { return std::nullopt; }
virtual std::optional<BuiltinHandle> storageLoadFunctionHandle() const { return std::nullopt; }
virtual std::optional<BuiltinHandle> hashFunctionHandle() const { return std::nullopt; }
Literal zeroLiteral() const;
Dialect() = default;
virtual ~Dialect() = default;
};
}
| 3,375
|
C++
|
.h
| 75
| 42.973333
| 108
| 0.778489
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,402
|
Exceptions.h
|
ethereum_solidity/libyul/Exceptions.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Exceptions in Yul.
*/
#pragma once
#include <libsolutil/Exceptions.h>
#include <libsolutil/Assertions.h>
#include <libyul/YulName.h>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/facilities/overload.hpp>
namespace solidity::yul
{
struct YulException: virtual util::Exception {};
struct OptimizerException: virtual YulException {};
struct CodegenException: virtual YulException {};
struct YulAssertion: virtual YulException {};
struct StackTooDeepError: virtual YulException
{
StackTooDeepError(YulName _variable, int _depth, std::string const& _message):
variable(_variable), depth(_depth)
{
*this << util::errinfo_comment(_message);
}
StackTooDeepError(YulName _functionName, YulName _variable, int _depth, std::string const& _message):
functionName(_functionName), variable(_variable), depth(_depth)
{
*this << util::errinfo_comment(_message);
}
YulName functionName;
YulName variable;
int depth;
};
/// Assertion that throws an YulAssertion containing the given description if it is not met.
#if !BOOST_PP_VARIADICS_MSVC
#define yulAssert(...) BOOST_PP_OVERLOAD(yulAssert_,__VA_ARGS__)(__VA_ARGS__)
#else
#define yulAssert(...) BOOST_PP_CAT(BOOST_PP_OVERLOAD(yulAssert_,__VA_ARGS__)(__VA_ARGS__),BOOST_PP_EMPTY())
#endif
#define yulAssert_1(CONDITION) \
yulAssert_2((CONDITION), "")
#define yulAssert_2(CONDITION, DESCRIPTION) \
assertThrowWithDefaultDescription( \
(CONDITION), \
::solidity::yul::YulAssertion, \
(DESCRIPTION), \
"Yul assertion failed" \
)
}
| 2,267
|
C++
|
.h
| 62
| 34.677419
| 108
| 0.769968
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,404
|
YulStack.h
|
ethereum_solidity/libyul/YulStack.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Full assembly stack that can support Yul as input.
*/
#pragma once
#include <liblangutil/CharStreamProvider.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/ErrorReporter.h>
#include <liblangutil/EVMVersion.h>
#include <libsolutil/JSON.h>
#include <libyul/Object.h>
#include <libyul/ObjectOptimizer.h>
#include <libyul/ObjectParser.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <libevmasm/LinkerObject.h>
#include <memory>
#include <string>
namespace solidity::evmasm
{
class Assembly;
}
namespace solidity::langutil
{
class Scanner;
}
namespace solidity::yul
{
class AbstractAssembly;
struct MachineAssemblyObject
{
std::shared_ptr<evmasm::LinkerObject> bytecode;
std::shared_ptr<evmasm::Assembly> assembly;
std::unique_ptr<std::string> sourceMappings;
};
/*
* Full assembly stack that can support EVM-assembly and Yul as input and EVM as output.
*/
class YulStack: public langutil::CharStreamProvider
{
public:
using Language = yul::Language;
enum class Machine { EVM };
enum State {
Empty,
Parsed,
AnalysisSuccessful
};
YulStack():
YulStack(
langutil::EVMVersion{},
std::nullopt,
Language::Assembly,
solidity::frontend::OptimiserSettings::none(),
langutil::DebugInfoSelection::Default()
)
{}
YulStack(
langutil::EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
Language _language,
solidity::frontend::OptimiserSettings _optimiserSettings,
langutil::DebugInfoSelection const& _debugInfoSelection,
langutil::CharStreamProvider const* _soliditySourceProvider = nullptr,
std::shared_ptr<ObjectOptimizer> _objectOptimizer = nullptr
):
m_language(_language),
m_evmVersion(_evmVersion),
m_eofVersion(_eofVersion),
m_optimiserSettings(std::move(_optimiserSettings)),
m_debugInfoSelection(_debugInfoSelection),
m_soliditySourceProvider(_soliditySourceProvider),
m_errorReporter(m_errors),
m_objectOptimizer(_objectOptimizer ? std::move(_objectOptimizer) : std::make_shared<ObjectOptimizer>())
{}
/// @returns the char stream used during parsing
langutil::CharStream const& charStream(std::string const& _sourceName) const override;
/// Runs parsing and analysis steps, returns false if input cannot be assembled.
/// Multiple calls overwrite the previous state.
bool parseAndAnalyze(std::string const& _sourceName, std::string const& _source);
/// Run the optimizer suite. Can only be used with Yul or strict assembly.
/// If the settings (see constructor) disabled the optimizer, nothing is done here.
void optimize();
/// Run the assembly step (should only be called after parseAndAnalyze).
MachineAssemblyObject assemble(Machine _machine);
/// Run the assembly step (should only be called after parseAndAnalyze).
/// In addition to the value returned by @a assemble, returns
/// a second object that is the runtime code.
/// Only available for EVM.
std::pair<MachineAssemblyObject, MachineAssemblyObject>
assembleWithDeployed(
std::optional<std::string_view> _deployName = {}
);
/// Run the assembly step (should only be called after parseAndAnalyze).
/// Similar to @a assemblyWithDeployed, but returns EVM assembly objects.
/// Only available for EVM.
std::pair<std::shared_ptr<evmasm::Assembly>, std::shared_ptr<evmasm::Assembly>>
assembleEVMWithDeployed(
std::optional<std::string_view> _deployName = {}
);
/// @returns the errors generated during parsing, analysis (and potentially assembly).
langutil::ErrorList const& errors() const { return m_errors; }
bool hasErrors() const { return m_errorReporter.hasErrors(); }
/// Pretty-print the input after having parsed it.
std::string print() const;
Json astJson() const;
// return the JSON representation of the YuL CFG (experimental)
Json cfgJson() const;
/// Return the parsed and analyzed object.
std::shared_ptr<Object> parserResult() const;
langutil::DebugInfoSelection debugInfoSelection() const { return m_debugInfoSelection; }
private:
bool parse(std::string const& _sourceName, std::string const& _source);
bool analyzeParsed();
bool analyzeParsed(yul::Object& _object);
void compileEVM(yul::AbstractAssembly& _assembly, bool _optimize) const;
/// Prints the Yul object stored internally and parses it again.
/// This ensures that the debug info in the AST matches the source that printing would produce
/// rather than the initial source.
/// @warning Does not update the error list or the original source (@a m_charStream) to make
/// it possible to report errors to the user even after the optimization has been performed.
void reparse();
void reportUnimplementedFeatureError(langutil::UnimplementedFeatureError const& _error);
Language m_language = Language::Assembly;
langutil::EVMVersion m_evmVersion;
std::optional<uint8_t> m_eofVersion;
solidity::frontend::OptimiserSettings m_optimiserSettings;
langutil::DebugInfoSelection m_debugInfoSelection{};
/// Provider of the Solidity sources that the Yul code was generated from.
/// Necessary when code snippets are requested as a part of debug info. When null, code snippets are omitted.
/// NOTE: Not owned by YulStack, the user must ensure that it is not destroyed before the stack is.
langutil::CharStreamProvider const* m_soliditySourceProvider{};
std::unique_ptr<langutil::CharStream> m_charStream;
State m_stackState = Empty;
std::shared_ptr<yul::Object> m_parserResult;
langutil::ErrorList m_errors;
langutil::ErrorReporter m_errorReporter;
std::shared_ptr<ObjectOptimizer> m_objectOptimizer;
};
}
| 6,229
|
C++
|
.h
| 152
| 38.769737
| 110
| 0.780758
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,405
|
AsmParser.h
|
ethereum_solidity/libyul/AsmParser.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Solidity inline assembly parser.
*/
#pragma once
#include <libyul/AST.h>
#include <libyul/ASTForward.h>
#include <libyul/Dialect.h>
#include <liblangutil/SourceLocation.h>
#include <liblangutil/Scanner.h>
#include <liblangutil/ParserBase.h>
#include <map>
#include <memory>
#include <variant>
#include <vector>
#include <string_view>
namespace solidity::yul
{
class Parser: public langutil::ParserBase
{
public:
enum class ForLoopComponent
{
None, ForLoopPre, ForLoopPost, ForLoopBody
};
enum class UseSourceLocationFrom
{
Scanner, LocationOverride, Comments,
};
explicit Parser(
langutil::ErrorReporter& _errorReporter,
Dialect const& _dialect,
std::optional<langutil::SourceLocation> _locationOverride = {}
):
ParserBase(_errorReporter),
m_dialect(_dialect),
m_locationOverride{_locationOverride ? *_locationOverride : langutil::SourceLocation{}},
m_useSourceLocationFrom{
_locationOverride ?
UseSourceLocationFrom::LocationOverride :
UseSourceLocationFrom::Scanner
}
{}
/// Constructs a Yul parser that is using the debug data
/// from the comments (via @src and other tags).
explicit Parser(
langutil::ErrorReporter& _errorReporter,
Dialect const& _dialect,
std::optional<std::map<unsigned, std::shared_ptr<std::string const>>> _sourceNames
):
ParserBase(_errorReporter),
m_dialect(_dialect),
m_sourceNames{std::move(_sourceNames)},
m_useSourceLocationFrom{
m_sourceNames.has_value() ?
UseSourceLocationFrom::Comments :
UseSourceLocationFrom::Scanner
}
{}
/// Parses an inline assembly block starting with `{` and ending with `}`.
/// @returns an empty shared pointer on error.
std::unique_ptr<AST> parseInline(std::shared_ptr<langutil::Scanner> const& _scanner);
/// Parses an assembly block starting with `{` and ending with `}`
/// and expects end of input after the '}'.
/// @returns an empty shared pointer on error.
std::unique_ptr<AST> parse(langutil::CharStream& _charStream);
protected:
langutil::SourceLocation currentLocation() const override
{
if (m_useSourceLocationFrom == UseSourceLocationFrom::LocationOverride)
return m_locationOverride;
return ParserBase::currentLocation();
}
langutil::Token advance() override;
void fetchDebugDataFromComment();
std::optional<std::pair<std::string_view, langutil::SourceLocation>> parseSrcComment(
std::string_view _arguments,
langutil::SourceLocation const& _commentLocation
);
std::optional<std::pair<std::string_view, std::optional<int>>> parseASTIDComment(
std::string_view _arguments,
langutil::SourceLocation const& _commentLocation
);
/// Creates a DebugData object with the correct source location set.
langutil::DebugData::ConstPtr createDebugData() const;
void updateLocationEndFrom(
langutil::DebugData::ConstPtr& _debugData,
langutil::SourceLocation const& _location
) const;
/// Creates an inline assembly node with the current debug data.
template <class T> T createWithDebugData() const
{
T r;
r.debugData = createDebugData();
return r;
}
Block parseBlock();
Statement parseStatement();
Case parseCase();
ForLoop parseForLoop();
/// Parses a functional expression that has to push exactly one stack element
Expression parseExpression(bool _unlimitedLiteralArgument = false);
/// Parses an elementary operation, i.e. a literal, identifier, instruction or
/// builtin function call (only the name).
std::variant<Literal, Identifier> parseLiteralOrIdentifier(bool _unlimitedLiteralArgument = false);
VariableDeclaration parseVariableDeclaration();
FunctionDefinition parseFunctionDefinition();
FunctionCall parseCall(std::variant<Literal, Identifier>&& _initialOp);
NameWithDebugData parseNameWithDebugData();
YulName expectAsmIdentifier();
void raiseUnsupportedTypesError(langutil::SourceLocation const& _location) const;
/// Reports an error if we are currently not inside the body part of a for loop.
void checkBreakContinuePosition(std::string const& _which);
static bool isValidNumberLiteral(std::string const& _literal);
private:
Dialect const& m_dialect;
std::optional<std::map<unsigned, std::shared_ptr<std::string const>>> m_sourceNames;
langutil::SourceLocation m_locationOverride;
langutil::SourceLocation m_locationFromComment;
std::optional<int64_t> m_astIDFromComment;
UseSourceLocationFrom m_useSourceLocationFrom = UseSourceLocationFrom::Scanner;
ForLoopComponent m_currentForLoopComponent = ForLoopComponent::None;
bool m_insideFunction = false;
};
}
| 5,249
|
C++
|
.h
| 140
| 35.157143
| 100
| 0.78248
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,406
|
CompilabilityChecker.h
|
ethereum_solidity/libyul/CompilabilityChecker.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Component that checks whether all variables are reachable on the stack.
*/
#pragma once
#include <libyul/Dialect.h>
#include <libyul/ASTForward.h>
#include <libyul/Object.h>
#include <map>
#include <memory>
namespace solidity::yul
{
/**
* Component that checks whether all variables are reachable on the stack and
* provides a mapping from function name to the largest stack difference found
* in that function (no entry present if that function is compilable), as well
* as the set of unreachable variables for each function.
*
* This only works properly if the outermost block is compilable and
* functions are not nested. Otherwise, it might miss reporting some functions.
*
* Only checks the code of the object itself, does not descend into sub-objects.
*/
struct CompilabilityChecker
{
CompilabilityChecker(
Dialect const& _dialect,
Object const& _object,
bool _optimizeStackAllocation
);
std::map<YulName, std::vector<YulName>> unreachableVariables;
std::map<YulName, int> stackDeficit;
};
}
| 1,717
|
C++
|
.h
| 47
| 34.638298
| 80
| 0.784467
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,407
|
ControlFlowSideEffectsCollector.h
|
ethereum_solidity/libyul/ControlFlowSideEffectsCollector.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/ControlFlowSideEffects.h>
#include <set>
#include <stack>
#include <optional>
#include <list>
namespace solidity::yul
{
struct Dialect;
struct ControlFlowNode
{
std::vector<ControlFlowNode const*> successors;
/// Function call AST node, if present.
FunctionCall const* functionCall = nullptr;
};
/**
* The control flow of a function with entry and exit nodes.
*/
struct FunctionFlow
{
ControlFlowNode const* entry;
ControlFlowNode const* exit;
};
/**
* Requires: Disambiguator, Function Hoister.
*/
class ControlFlowBuilder: private ASTWalker
{
public:
/// Computes the control-flows of all function defined in the block.
/// Assumes the functions are hoisted to the topmost block.
explicit ControlFlowBuilder(Block const& _ast);
std::map<FunctionDefinition const*, FunctionFlow> const& functionFlows() const { return m_functionFlows; }
private:
using ASTWalker::operator();
void operator()(FunctionCall const& _functionCall) override;
void operator()(If const& _if) override;
void operator()(Switch const& _switch) override;
void operator()(FunctionDefinition const& _functionDefinition) override;
void operator()(ForLoop const& _forLoop) override;
void operator()(Break const& _break) override;
void operator()(Continue const& _continue) override;
void operator()(Leave const& _leaveStatement) override;
void newConnectedNode();
ControlFlowNode* newNode();
std::vector<std::shared_ptr<ControlFlowNode>> m_nodes;
ControlFlowNode* m_currentNode = nullptr;
ControlFlowNode const* m_leave = nullptr;
ControlFlowNode const* m_break = nullptr;
ControlFlowNode const* m_continue = nullptr;
std::map<FunctionDefinition const*, FunctionFlow> m_functionFlows;
};
/**
* Computes control-flow side-effects for user-defined functions.
* Source does not have to be disambiguated, unless you want the side-effects
* based on function names.
*/
class ControlFlowSideEffectsCollector
{
public:
explicit ControlFlowSideEffectsCollector(
Dialect const& _dialect,
Block const& _ast
);
std::map<FunctionDefinition const*, ControlFlowSideEffects> const& functionSideEffects() const
{
return m_functionSideEffects;
}
/// Returns the side effects by function name, requires unique function names.
std::map<YulName, ControlFlowSideEffects> functionSideEffectsNamed() const;
private:
/// @returns false if nothing could be processed.
bool processFunction(FunctionDefinition const& _function);
/// @returns the next pending node of the function that is not
/// a function call to a function that might not continue.
/// De-queues the node or returns nullptr if no such node is found.
ControlFlowNode const* nextProcessableNode(FunctionDefinition const& _function);
/// @returns the side-effects of either a builtin call or a user defined function
/// call (as far as already computed).
ControlFlowSideEffects const& sideEffects(FunctionCall const& _call) const;
/// Queues the given node to be processed (if not already visited)
/// and if it is a function call, records that `_functionName` calls
/// `*_node->functionCall`.
void recordReachabilityAndQueue(FunctionDefinition const& _function, ControlFlowNode const* _node);
Dialect const& m_dialect;
ControlFlowBuilder m_cfgBuilder;
/// Function references, but only for calls to user-defined functions.
std::map<FunctionCall const*, FunctionDefinition const*> m_functionReferences;
/// Side effects of user-defined functions, is being constructod.
std::map<FunctionDefinition const*, ControlFlowSideEffects> m_functionSideEffects;
/// Control flow nodes still to process, per function.
std::map<FunctionDefinition const*, std::list<ControlFlowNode const*>> m_pendingNodes;
/// Control flow nodes already processed, per function.
std::map<FunctionDefinition const*, std::set<ControlFlowNode const*>> m_processedNodes;
/// Set of reachable function calls nodes in each function (including calls to builtins).
std::map<FunctionDefinition const*, std::set<FunctionCall const*>> m_functionCalls;
};
}
| 4,774
|
C++
|
.h
| 113
| 40.283186
| 107
| 0.788134
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,410
|
ObjectOptimizer.h
|
ethereum_solidity/libyul/ObjectOptimizer.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/Object.h>
#include <liblangutil/EVMVersion.h>
#include <libsolutil/FixedHash.h>
#include <map>
#include <memory>
#include <optional>
namespace solidity::yul
{
enum class Language
{
Assembly,
StrictAssembly,
};
Dialect const& languageToDialect(Language _language, langutil::EVMVersion _version, std::optional<uint8_t> _eofVersion);
/// Encapsulates logic for applying @a yul::OptimiserSuite to a whole hierarchy of Yul objects.
/// Also, acts as a transparent cache for optimized objects.
///
/// The cache is designed to allow sharing its instances widely across the compiler, without the
/// need to invalidate entries due to changing settings or context.
/// Caching is performed at the granularity of individual ASTs rather than whole object trees,
/// which means that reuse is possible even within a single hierarchy, e.g. when creation and
/// deployed objects have common dependencies.
class ObjectOptimizer
{
public:
/// Optimization settings and context information.
/// This information becomes a part of the cache key and, together with the object content,
/// must uniquely determine the result of optimization.
struct Settings
{
Language language;
langutil::EVMVersion evmVersion;
std::optional<uint8_t> eofVersion;
bool optimizeStackAllocation;
std::string yulOptimiserSteps;
std::string yulOptimiserCleanupSteps;
size_t expectedExecutionsPerDeployment;
};
/// Recursively optimizes a Yul object with given settings, reusing cached ASTs where possible
/// or caching the result otherwise. The object is modified in-place.
/// Automatically accounts for the difference between creation and deployed objects.
/// @warning Does not ensure that nativeLocations in the resulting AST match the optimized code.
void optimize(Object& _object, Settings const& _settings);
size_t size() const { return m_cachedObjects.size(); }
private:
struct CachedObject
{
std::shared_ptr<Block const> optimizedAST;
Dialect const* dialect;
};
void optimize(Object& _object, Settings const& _settings, bool _isCreation);
void storeOptimizedObject(util::h256 _cacheKey, Object const& _optimizedObject, Dialect const& _dialect);
void overwriteWithOptimizedObject(util::h256 _cacheKey, Object& _object) const;
static std::optional<util::h256> calculateCacheKey(
Block const& _ast,
ObjectDebugData const& _debugData,
Settings const& _settings,
bool _isCreation
);
std::map<util::h256, CachedObject> m_cachedObjects;
};
}
| 3,218
|
C++
|
.h
| 78
| 39.230769
| 120
| 0.789103
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,413
|
AsmPrinter.h
|
ethereum_solidity/libyul/AsmPrinter.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @date 2017
* Converts a parsed assembly into its textual form.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <libsolutil/CommonData.h>
#include <liblangutil/CharStreamProvider.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/DebugData.h>
#include <map>
namespace solidity::yul
{
struct Dialect;
/**
* Converts a parsed Yul AST into readable string representation.
* Ignores source locations.
*/
class AsmPrinter
{
public:
explicit AsmPrinter(
Dialect const&,
std::optional<std::map<unsigned, std::shared_ptr<std::string const>>> _sourceIndexToName = {},
langutil::DebugInfoSelection const& _debugInfoSelection = langutil::DebugInfoSelection::Default(),
langutil::CharStreamProvider const* _soliditySourceProvider = nullptr
):
m_debugInfoSelection(_debugInfoSelection),
m_soliditySourceProvider(_soliditySourceProvider)
{
if (_sourceIndexToName)
for (auto&& [index, name]: *_sourceIndexToName)
m_nameToSourceIndex[*name] = index;
}
std::string operator()(Literal const& _literal);
std::string operator()(Identifier const& _identifier);
std::string operator()(ExpressionStatement const& _expr);
std::string operator()(Assignment const& _assignment);
std::string operator()(VariableDeclaration const& _variableDeclaration);
std::string operator()(FunctionDefinition const& _functionDefinition);
std::string operator()(FunctionCall const& _functionCall);
std::string operator()(If const& _if);
std::string operator()(Switch const& _switch);
std::string operator()(ForLoop const& _forLoop);
std::string operator()(Break const& _break);
std::string operator()(Continue const& _continue);
std::string operator()(Leave const& _continue);
std::string operator()(Block const& _block);
static std::string formatSourceLocation(
langutil::SourceLocation const& _location,
std::map<std::string, unsigned> const& _nameToSourceIndex,
langutil::DebugInfoSelection const& _debugInfoSelection = langutil::DebugInfoSelection::Default(),
langutil::CharStreamProvider const* m_soliditySourceProvider = nullptr
);
private:
std::string formatNameWithDebugData(NameWithDebugData _variable);
std::string formatDebugData(langutil::DebugData::ConstPtr const& _debugData, bool _statement);
template <class T>
std::string formatDebugData(T const& _node)
{
bool isExpression = std::is_constructible<Expression, T>::value;
return formatDebugData(_node.debugData, !isExpression);
}
std::map<std::string, unsigned> m_nameToSourceIndex;
langutil::SourceLocation m_lastLocation = {};
langutil::DebugInfoSelection m_debugInfoSelection = {};
langutil::CharStreamProvider const* m_soliditySourceProvider = nullptr;
};
}
| 3,448
|
C++
|
.h
| 85
| 38.423529
| 100
| 0.7804
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,414
|
FunctionReferenceResolver.h
|
ethereum_solidity/libyul/FunctionReferenceResolver.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/optimiser/ASTWalker.h>
namespace solidity::yul
{
/**
* Resolves references to user-defined functions in function calls.
* Assumes the code is correct, i.e. does not check for references to be valid or unique.
*
* Be careful not to iterate over the result - it is not deterministic.
*/
class FunctionReferenceResolver: private ASTWalker
{
public:
explicit FunctionReferenceResolver(Block const& _ast);
std::map<FunctionCall const*, FunctionDefinition const*> const& references() const { return m_functionReferences; }
private:
using ASTWalker::operator();
void operator()(FunctionCall const& _functionCall) override;
void operator()(Block const& _block) override;
std::map<FunctionCall const*, FunctionDefinition const*> m_functionReferences;
std::vector<std::map<YulName, FunctionDefinition const*>> m_scopes;
};
}
| 1,550
|
C++
|
.h
| 37
| 39.972973
| 116
| 0.788282
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,415
|
SSACFGLiveness.h
|
ethereum_solidity/libyul/backends/evm/SSACFGLiveness.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/backends/evm/SSACFGLoopNestingForest.h>
#include <libyul/backends/evm/SSACFGTopologicalSort.h>
#include <libyul/backends/evm/SSAControlFlowGraph.h>
#include <cstddef>
#include <set>
#include <vector>
namespace solidity::yul
{
/// Performs liveness analysis on a reducible SSA CFG following Algorithm 9.1 in [1].
///
/// [1] Rastello, Fabrice, and Florent Bouchez Tichadou, eds. SSA-based Compiler Design. Springer, 2022.
class SSACFGLiveness
{
public:
using LivenessData = std::set<SSACFG::ValueId>;
explicit SSACFGLiveness(SSACFG const& _cfg);
LivenessData const& liveIn(SSACFG::BlockId _blockId) const { return m_liveIns[_blockId.value]; }
LivenessData const& liveOut(SSACFG::BlockId _blockId) const { return m_liveOuts[_blockId.value]; }
std::vector<LivenessData> const& operationsLiveOut(SSACFG::BlockId _blockId) const { return m_operationLiveOuts[_blockId.value]; }
ForwardSSACFGTopologicalSort const& topologicalSort() const { return m_topologicalSort; }
private:
void runDagDfs();
void runLoopTreeDfs(size_t _loopHeader);
void fillOperationsLiveOut();
SSACFG const& m_cfg;
ForwardSSACFGTopologicalSort m_topologicalSort;
SSACFGLoopNestingForest m_loopNestingForest;
std::vector<LivenessData> m_liveIns;
std::vector<LivenessData> m_liveOuts;
std::vector<std::vector<LivenessData>> m_operationLiveOuts;
};
}
| 2,053
|
C++
|
.h
| 47
| 41.87234
| 131
| 0.795386
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,416
|
VariableReferenceCounter.h
|
ethereum_solidity/libyul/backends/evm/VariableReferenceCounter.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Counts the number of references to a variable.
*/
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/Scope.h>
namespace solidity::yul
{
struct AsmAnalysisInfo;
/**
* Counts the number of references to a variable. This includes actual (read) references
* but also assignments to the variable. It does not include the declaration itself or
* function parameters, but it does include function return parameters.
*
* This component can handle multiple variables of the same name.
*
* Can only be applied to strict assembly.
*/
struct VariableReferenceCounter: public yul::ASTWalker
{
public:
static std::map<Scope::Variable const*, unsigned> run(AsmAnalysisInfo const& _assemblyInfo, Block const& _block)
{
VariableReferenceCounter variableReferenceCounter(_assemblyInfo);
variableReferenceCounter(_block);
return std::move(variableReferenceCounter.m_variableReferences);
}
protected:
void operator()(Block const& _block) override;
void operator()(Identifier const& _identifier) override;
void operator()(FunctionDefinition const&) override;
void operator()(ForLoop const&) override;
private:
explicit VariableReferenceCounter(
AsmAnalysisInfo const& _assemblyInfo
): m_info(_assemblyInfo)
{}
void increaseRefIfFound(YulName _variableName);
AsmAnalysisInfo const& m_info;
Scope* m_scope = nullptr;
std::map<Scope::Variable const*, unsigned> m_variableReferences;
};
}
| 2,114
|
C++
|
.h
| 57
| 35.140351
| 113
| 0.792766
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,417
|
SSAControlFlowGraph.h
|
ethereum_solidity/libyul/backends/evm/SSAControlFlowGraph.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Control flow graph and stack layout structures used during code generation.
*/
#pragma once
#include <libyul/AST.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/Dialect.h>
#include <libyul/Exceptions.h>
#include <libyul/Scope.h>
#include <libsolutil/Numeric.h>
#include <range/v3/view/map.hpp>
#include <deque>
#include <functional>
#include <list>
#include <vector>
namespace solidity::yul
{
class SSACFGLiveness;
class SSACFG
{
public:
SSACFG() = default;
SSACFG(SSACFG const&) = delete;
SSACFG(SSACFG&&) = delete;
SSACFG& operator=(SSACFG const&) = delete;
SSACFG& operator=(SSACFG&&) = delete;
~SSACFG() = default;
struct BlockId
{
size_t value = std::numeric_limits<size_t>::max();
bool operator<(BlockId const& _rhs) const { return value < _rhs.value; }
bool operator==(BlockId const& _rhs) const { return value == _rhs.value; }
bool operator!=(BlockId const& _rhs) const { return value != _rhs.value; }
};
struct ValueId
{
size_t value = std::numeric_limits<size_t>::max();
bool hasValue() const { return value != std::numeric_limits<size_t>::max(); }
bool operator<(ValueId const& _rhs) const { return value < _rhs.value; }
bool operator==(ValueId const& _rhs) const { return value == _rhs.value; }
bool operator!=(ValueId const& _rhs) const { return value != _rhs.value; }
};
struct BuiltinCall
{
langutil::DebugData::ConstPtr debugData;
std::reference_wrapper<BuiltinFunction const> builtin;
std::reference_wrapper<FunctionCall const> call;
};
struct Call
{
langutil::DebugData::ConstPtr debugData;
std::reference_wrapper<Scope::Function const> function;
std::reference_wrapper<FunctionCall const> call;
bool const canContinue = true;
};
struct Operation {
std::vector<ValueId> outputs{};
std::variant<BuiltinCall, Call> kind;
std::vector<ValueId> inputs{};
};
struct BasicBlock
{
struct MainExit {};
struct ConditionalJump
{
langutil::DebugData::ConstPtr debugData;
ValueId condition;
BlockId nonZero;
BlockId zero;
};
struct Jump
{
langutil::DebugData::ConstPtr debugData;
BlockId target;
};
struct JumpTable
{
langutil::DebugData::ConstPtr debugData;
ValueId value;
std::map<u256, BlockId> cases;
BlockId defaultCase;
};
struct FunctionReturn
{
langutil::DebugData::ConstPtr debugData;
std::vector<ValueId> returnValues;
};
struct Terminated {};
langutil::DebugData::ConstPtr debugData;
std::set<BlockId> entries;
std::set<ValueId> phis;
std::vector<Operation> operations;
std::variant<MainExit, Jump, ConditionalJump, JumpTable, FunctionReturn, Terminated> exit = MainExit{};
template<typename Callable>
void forEachExit(Callable&& _callable) const
{
if (auto* jump = std::get_if<Jump>(&exit))
_callable(jump->target);
else if (auto* conditionalJump = std::get_if<ConditionalJump>(&exit))
{
_callable(conditionalJump->nonZero);
_callable(conditionalJump->zero);
}
else if (auto* jumpTable = std::get_if<JumpTable>(&exit))
{
for (auto _case: jumpTable->cases | ranges::views::values)
_callable(_case);
_callable(jumpTable->defaultCase);
}
}
};
BlockId makeBlock(langutil::DebugData::ConstPtr _debugData)
{
BlockId blockId { m_blocks.size() };
m_blocks.emplace_back(BasicBlock{std::move(_debugData), {}, {}, {}, BasicBlock::Terminated{}});
return blockId;
}
BasicBlock& block(BlockId _id) { return m_blocks.at(_id.value); }
BasicBlock const& block(BlockId _id) const { return m_blocks.at(_id.value); }
size_t numBlocks() const { return m_blocks.size(); }
private:
std::vector<BasicBlock> m_blocks;
public:
struct LiteralValue {
langutil::DebugData::ConstPtr debugData;
u256 value;
};
struct VariableValue {
langutil::DebugData::ConstPtr debugData;
BlockId definingBlock;
};
struct PhiValue {
langutil::DebugData::ConstPtr debugData;
BlockId block;
std::vector<ValueId> arguments;
};
struct UnreachableValue {};
using ValueInfo = std::variant<UnreachableValue, VariableValue, LiteralValue, PhiValue>;
ValueInfo& valueInfo(ValueId const _var)
{
return m_valueInfos.at(_var.value);
}
ValueInfo const& valueInfo(ValueId const _var) const
{
return m_valueInfos.at(_var.value);
}
ValueId newPhi(BlockId const _definingBlock)
{
ValueId id { m_valueInfos.size() };
auto block = m_blocks.at(_definingBlock.value);
m_valueInfos.emplace_back(PhiValue{debugDataOf(block), _definingBlock, {}});
return id;
}
ValueId newVariable(BlockId const _definingBlock)
{
ValueId id { m_valueInfos.size() };
auto block = m_blocks.at(_definingBlock.value);
m_valueInfos.emplace_back(VariableValue{debugDataOf(block), _definingBlock});
return id;
}
ValueId unreachableValue()
{
if (!m_unreachableValue)
{
m_unreachableValue = ValueId { m_valueInfos.size() };
m_valueInfos.emplace_back(UnreachableValue{});
}
return *m_unreachableValue;
}
ValueId newLiteral(langutil::DebugData::ConstPtr _debugData, u256 _value)
{
auto [it, inserted] = m_literals.emplace(_value, SSACFG::ValueId{m_valueInfos.size()});
if (inserted)
m_valueInfos.emplace_back(LiteralValue{std::move(_debugData), _value});
else
{
yulAssert(_value == it->first);
yulAssert(std::holds_alternative<LiteralValue>(m_valueInfos.at(it->second.value)));
yulAssert(std::get<LiteralValue>(m_valueInfos.at(it->second.value)).value == _value);
}
yulAssert(it->second.value < m_valueInfos.size());
return it->second;
}
std::string toDot(
bool _includeDiGraphDefinition=true,
std::optional<size_t> _functionIndex=std::nullopt,
SSACFGLiveness const* _liveness=nullptr
) const;
private:
std::deque<ValueInfo> m_valueInfos;
std::map<u256, ValueId> m_literals;
std::optional<ValueId> m_unreachableValue;
public:
langutil::DebugData::ConstPtr debugData;
BlockId entry = BlockId{0};
std::set<BlockId> exits;
Scope::Function const* function = nullptr;
bool canContinue = true;
std::vector<std::tuple<std::reference_wrapper<Scope::Variable const>, ValueId>> arguments;
std::vector<std::reference_wrapper<Scope::Variable const>> returns;
std::vector<std::reference_wrapper<Scope::Function const>> functions;
// Container for artificial calls generated for switch statements.
std::list<FunctionCall> ghostCalls;
};
}
| 6,978
|
C++
|
.h
| 219
| 29.26484
| 105
| 0.738621
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,418
|
EVMDialect.h
|
ethereum_solidity/libyul/backends/evm/EVMDialect.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul dialects for EVM.
*/
#pragma once
#include <libyul/Dialect.h>
#include <libyul/backends/evm/AbstractAssembly.h>
#include <libyul/ASTForward.h>
#include <liblangutil/EVMVersion.h>
#include <map>
#include <set>
namespace solidity::yul
{
struct FunctionCall;
class Object;
/**
* Context used during code generation.
*/
struct BuiltinContext
{
Object const* currentObject = nullptr;
/// Mapping from named objects to abstract assembly sub IDs.
std::map<std::string, AbstractAssembly::SubID> subIDs;
};
struct BuiltinFunctionForEVM: public BuiltinFunction
{
std::optional<evmasm::Instruction> instruction;
/// Function to generate code for the given function call and append it to the abstract
/// assembly. Expects all non-literal arguments of the call to be on stack in reverse order
/// (i.e. right-most argument pushed first).
/// Expects the caller to set the source location.
std::function<void(FunctionCall const&, AbstractAssembly&, BuiltinContext&)> generateCode;
};
/**
* Yul dialect for EVM as a backend.
* The main difference is that the builtin functions take an AbstractAssembly for the
* code generation.
*/
class EVMDialect: public Dialect
{
public:
/// Constructor, should only be used internally. Use the factory functions below.
EVMDialect(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion, bool _objectAccess);
std::optional<BuiltinHandle> findBuiltin(std::string_view _name) const override;
BuiltinFunctionForEVM const& builtin(BuiltinHandle const& _handle) const override;
bool reservedIdentifier(std::string_view _name) const override;
std::optional<BuiltinHandle> discardFunctionHandle() const override { return m_discardFunction; }
std::optional<BuiltinHandle> equalityFunctionHandle() const override { return m_equalityFunction; }
std::optional<BuiltinHandle> booleanNegationFunctionHandle() const override { return m_booleanNegationFunction; }
std::optional<BuiltinHandle> memoryStoreFunctionHandle() const override { return m_memoryStoreFunction; }
std::optional<BuiltinHandle> memoryLoadFunctionHandle() const override { return m_memoryLoadFunction; }
std::optional<BuiltinHandle> storageStoreFunctionHandle() const override { return m_storageStoreFunction; }
std::optional<BuiltinHandle> storageLoadFunctionHandle() const override { return m_storageLoadFunction; }
std::optional<BuiltinHandle> hashFunctionHandle() const override { return m_hashFunction; }
static EVMDialect const& strictAssemblyForEVM(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion);
static EVMDialect const& strictAssemblyForEVMObjects(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion);
langutil::EVMVersion evmVersion() const { return m_evmVersion; }
std::optional<uint8_t> eofVersion() const { return m_eofVersion; }
bool providesObjectAccess() const { return m_objectAccess; }
static SideEffects sideEffectsOfInstruction(evmasm::Instruction _instruction);
static size_t constexpr verbatimMaxInputSlots = 100;
static size_t constexpr verbatimMaxOutputSlots = 100;
protected:
static bool constexpr isVerbatimHandle(BuiltinHandle const& _handle) { return _handle.id < verbatimIDOffset; }
static BuiltinFunctionForEVM createVerbatimFunctionFromHandle(BuiltinHandle const& _handle);
static BuiltinFunctionForEVM createVerbatimFunction(size_t _arguments, size_t _returnVariables);
BuiltinHandle verbatimFunction(size_t _arguments, size_t _returnVariables) const;
static size_t constexpr verbatimIDOffset = verbatimMaxInputSlots * verbatimMaxOutputSlots;
bool const m_objectAccess;
langutil::EVMVersion const m_evmVersion;
std::optional<uint8_t> m_eofVersion;
std::unordered_map<std::string_view, BuiltinHandle> m_builtinFunctionsByName;
std::vector<std::optional<BuiltinFunctionForEVM>> m_functions;
std::array<std::unique_ptr<BuiltinFunctionForEVM>, verbatimIDOffset> mutable m_verbatimFunctions{};
std::set<std::string, std::less<>> m_reserved;
std::optional<BuiltinHandle> m_discardFunction;
std::optional<BuiltinHandle> m_equalityFunction;
std::optional<BuiltinHandle> m_booleanNegationFunction;
std::optional<BuiltinHandle> m_memoryStoreFunction;
std::optional<BuiltinHandle> m_memoryLoadFunction;
std::optional<BuiltinHandle> m_storageStoreFunction;
std::optional<BuiltinHandle> m_storageLoadFunction;
std::optional<BuiltinHandle> m_hashFunction;
};
}
| 5,087
|
C++
|
.h
| 98
| 49.928571
| 124
| 0.807537
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,419
|
ControlFlowGraphBuilder.h
|
ethereum_solidity/libyul/backends/evm/ControlFlowGraphBuilder.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Transformation of a Yul AST into a control flow graph.
*/
#pragma once
#include <libyul/backends/evm/ControlFlowGraph.h>
#include <libyul/ControlFlowSideEffects.h>
namespace solidity::yul
{
class ControlFlowGraphBuilder
{
public:
ControlFlowGraphBuilder(ControlFlowGraphBuilder const&) = delete;
ControlFlowGraphBuilder& operator=(ControlFlowGraphBuilder const&) = delete;
static std::unique_ptr<CFG> build(AsmAnalysisInfo const& _analysisInfo, Dialect const& _dialect, Block const& _block);
StackSlot operator()(Expression const& _literal);
StackSlot operator()(Literal const& _literal);
StackSlot operator()(Identifier const& _identifier);
StackSlot operator()(FunctionCall const&);
void operator()(VariableDeclaration const& _varDecl);
void operator()(Assignment const& _assignment);
void operator()(ExpressionStatement const& _statement);
void operator()(Block const& _block);
void operator()(If const& _if);
void operator()(Switch const& _switch);
void operator()(ForLoop const&);
void operator()(Break const&);
void operator()(Continue const&);
void operator()(Leave const&);
void operator()(FunctionDefinition const&);
private:
ControlFlowGraphBuilder(
CFG& _graph,
AsmAnalysisInfo const& _analysisInfo,
std::map<FunctionDefinition const*, ControlFlowSideEffects> const& _functionSideEffects,
Dialect const& _dialect
);
void registerFunction(FunctionDefinition const& _function);
Stack const& visitFunctionCall(FunctionCall const&);
Stack visitAssignmentRightHandSide(Expression const& _expression, size_t _expectedSlotCount);
Scope::Function const& lookupFunction(YulName _name) const;
Scope::Variable const& lookupVariable(YulName _name) const;
/// Resets m_currentBlock to enforce a subsequent explicit reassignment.
void makeConditionalJump(
langutil::DebugData::ConstPtr _debugData,
StackSlot _condition,
CFG::BasicBlock& _nonZero,
CFG::BasicBlock& _zero
);
void jump(
langutil::DebugData::ConstPtr _debugData,
CFG::BasicBlock& _target,
bool _backwards = false
);
CFG& m_graph;
AsmAnalysisInfo const& m_info;
std::map<FunctionDefinition const*, ControlFlowSideEffects> const& m_functionSideEffects;
Dialect const& m_dialect;
CFG::BasicBlock* m_currentBlock = nullptr;
Scope* m_scope = nullptr;
struct ForLoopInfo
{
std::reference_wrapper<CFG::BasicBlock> afterLoop;
std::reference_wrapper<CFG::BasicBlock> post;
};
std::optional<ForLoopInfo> m_forLoopInfo;
std::optional<CFG::FunctionInfo*> m_currentFunction;
};
}
| 3,197
|
C++
|
.h
| 82
| 36.853659
| 119
| 0.787556
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,420
|
OptimizedEVMCodeTransform.h
|
ethereum_solidity/libyul/backends/evm/OptimizedEVMCodeTransform.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Code generator for translating Yul / inline assembly to EVM.
*/
#pragma once
#include <libyul/AST.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/backends/evm/ControlFlowGraph.h>
#include <libyul/Exceptions.h>
#include <libyul/Scope.h>
#include <optional>
#include <stack>
namespace solidity::langutil
{
class ErrorReporter;
}
namespace solidity::yul
{
struct AsmAnalysisInfo;
struct StackLayout;
class OptimizedEVMCodeTransform
{
public:
/// Use named labels for functions 1) Yes and check that the names are unique
/// 2) For none of the functions 3) for the first function of each name.
enum class UseNamedLabels { YesAndForceUnique, Never, ForFirstFunctionOfEachName };
[[nodiscard]] static std::vector<StackTooDeepError> run(
AbstractAssembly& _assembly,
AsmAnalysisInfo& _analysisInfo,
Block const& _block,
EVMDialect const& _dialect,
BuiltinContext& _builtinContext,
UseNamedLabels _useNamedLabelsForFunctions
);
/// Generate code for the function call @a _call. Only public for using with std::visit.
void operator()(CFG::FunctionCall const& _call);
/// Generate code for the builtin call @a _call. Only public for using with std::visit.
void operator()(CFG::BuiltinCall const& _call);
/// Generate code for the assignment @a _assignment. Only public for using with std::visit.
void operator()(CFG::Assignment const& _assignment);
private:
OptimizedEVMCodeTransform(
AbstractAssembly& _assembly,
BuiltinContext& _builtinContext,
UseNamedLabels _useNamedLabelsForFunctions,
CFG const& _dfg,
StackLayout const& _stackLayout
);
/// Assert that it is valid to transition from @a _currentStack to @a _desiredStack.
/// That is @a _currentStack matches each slot in @a _desiredStack that is not a JunkSlot exactly.
static void assertLayoutCompatibility(Stack const& _currentStack, Stack const& _desiredStack);
/// @returns The label of the entry point of the given @a _function.
/// Creates and stores a new label, if none exists already.
AbstractAssembly::LabelID getFunctionLabel(Scope::Function const& _function);
/// Assert that @a _slot contains the value of @a _expression.
static void validateSlot(StackSlot const& _slot, Expression const& _expression);
/// Shuffles m_stack to the desired @a _targetStack while emitting the shuffling code to m_assembly.
/// Sets the source locations to the one in @a _debugData.
void createStackLayout(langutil::DebugData::ConstPtr _debugData, Stack _targetStack);
/// Generate code for the given block @a _block.
/// Expects the current stack layout m_stack to be a stack layout that is compatible with the
/// entry layout expected by the block.
/// Recursively generates code for blocks that are jumped to.
/// The last emitted assembly instruction is always an unconditional jump or terminating.
/// Always exits with an empty stack layout.
void operator()(CFG::BasicBlock const& _block);
/// Generate code for the given function.
/// Resets m_stack.
void operator()(CFG::FunctionInfo const& _functionInfo);
AbstractAssembly& m_assembly;
BuiltinContext& m_builtinContext;
CFG const& m_dfg;
StackLayout const& m_stackLayout;
Stack m_stack;
std::map<yul::FunctionCall const*, AbstractAssembly::LabelID> m_returnLabels;
std::map<CFG::BasicBlock const*, AbstractAssembly::LabelID> m_blockLabels;
std::map<CFG::FunctionInfo const*, AbstractAssembly::LabelID> const m_functionLabels;
/// Set of blocks already generated. If any of the contained blocks is ever jumped to, m_blockLabels should
/// contain a jump label for it.
std::set<CFG::BasicBlock const*> m_generated;
CFG::FunctionInfo const* m_currentFunctionInfo = nullptr;
std::vector<StackTooDeepError> m_stackErrors;
};
}
| 4,415
|
C++
|
.h
| 97
| 43.484536
| 108
| 0.777907
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,421
|
ControlFlowGraph.h
|
ethereum_solidity/libyul/backends/evm/ControlFlowGraph.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Control flow graph and stack layout structures used during code generation.
*/
#pragma once
#include <libyul/AST.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/Dialect.h>
#include <libyul/Exceptions.h>
#include <libyul/Scope.h>
#include <libsolutil/Numeric.h>
#include <functional>
#include <list>
#include <vector>
namespace solidity::yul
{
/// The following structs describe different kinds of stack slots.
/// Each stack slot is equality- and less-than-comparable and
/// specifies an attribute ``canBeFreelyGenerated`` that is true,
/// if a slot of this kind always has a known value at compile time and
/// therefore can safely be removed from the stack at any time and then
/// regenerated later.
/// The label pushed as return label before a function call, i.e. the label the call is supposed to return to.
struct FunctionCallReturnLabelSlot
{
std::reference_wrapper<yul::FunctionCall const> call;
bool operator==(FunctionCallReturnLabelSlot const& _rhs) const { return &call.get() == &_rhs.call.get(); }
bool operator<(FunctionCallReturnLabelSlot const& _rhs) const { return &call.get() < &_rhs.call.get(); }
static constexpr bool canBeFreelyGenerated = true;
};
/// The return jump target of a function while generating the code of the function body.
/// I.e. the caller of a function pushes a ``FunctionCallReturnLabelSlot`` (see above) before jumping to the function and
/// this very slot is viewed as ``FunctionReturnLabelSlot`` inside the function body and jumped to when returning from
/// the function.
struct FunctionReturnLabelSlot
{
std::reference_wrapper<Scope::Function const> function;
bool operator==(FunctionReturnLabelSlot const& _rhs) const
{
// There can never be return label slots of different functions on stack simultaneously.
yulAssert(&function.get() == &_rhs.function.get(), "");
return true;
}
bool operator<(FunctionReturnLabelSlot const& _rhs) const
{
// There can never be return label slots of different functions on stack simultaneously.
yulAssert(&function.get() == &_rhs.function.get(), "");
return false;
}
static constexpr bool canBeFreelyGenerated = false;
};
/// A slot containing the current value of a particular variable.
struct VariableSlot
{
std::reference_wrapper<Scope::Variable const> variable;
langutil::DebugData::ConstPtr debugData{};
bool operator==(VariableSlot const& _rhs) const { return &variable.get() == &_rhs.variable.get(); }
bool operator<(VariableSlot const& _rhs) const { return &variable.get() < &_rhs.variable.get(); }
static constexpr bool canBeFreelyGenerated = false;
};
/// A slot containing a literal value.
struct LiteralSlot
{
u256 value;
langutil::DebugData::ConstPtr debugData{};
bool operator==(LiteralSlot const& _rhs) const { return value == _rhs.value; }
bool operator<(LiteralSlot const& _rhs) const { return value < _rhs.value; }
static constexpr bool canBeFreelyGenerated = true;
};
/// A slot containing the index-th return value of a previous call.
struct TemporarySlot
{
/// The call that returned this slot.
std::reference_wrapper<yul::FunctionCall const> call;
/// Specifies to which of the values returned by the call this slot refers.
/// index == 0 refers to the slot deepest in the stack after the call.
size_t index = 0;
bool operator==(TemporarySlot const& _rhs) const { return &call.get() == &_rhs.call.get() && index == _rhs.index; }
bool operator<(TemporarySlot const& _rhs) const { return std::make_pair(&call.get(), index) < std::make_pair(&_rhs.call.get(), _rhs.index); }
static constexpr bool canBeFreelyGenerated = false;
};
/// A slot containing an arbitrary value that is always eventually popped and never used.
/// Used to maintain stack balance on control flow joins.
struct JunkSlot
{
bool operator==(JunkSlot const&) const { return true; }
bool operator<(JunkSlot const&) const { return false; }
static constexpr bool canBeFreelyGenerated = true;
};
using StackSlot = std::variant<FunctionCallReturnLabelSlot, FunctionReturnLabelSlot, VariableSlot, LiteralSlot, TemporarySlot, JunkSlot>;
/// The stack top is usually the last element of the vector.
using Stack = std::vector<StackSlot>;
/// @returns true if @a _slot can be generated on the stack at any time.
inline bool canBeFreelyGenerated(StackSlot const& _slot)
{
return std::visit([](auto const& _typedSlot) { return std::decay_t<decltype(_typedSlot)>::canBeFreelyGenerated; }, _slot);
}
/// Control flow graph consisting of ``CFG::BasicBlock``s connected by control flow.
struct CFG
{
explicit CFG() {}
CFG(CFG const&) = delete;
CFG(CFG&&) = delete;
CFG& operator=(CFG const&) = delete;
CFG& operator=(CFG&&) = delete;
~CFG() = default;
struct BuiltinCall
{
langutil::DebugData::ConstPtr debugData;
std::reference_wrapper<BuiltinFunction const> builtin;
std::reference_wrapper<yul::FunctionCall const> functionCall;
/// Number of proper arguments with a position on the stack, excluding literal arguments.
/// Literal arguments (like the literal string in ``datasize``) do not have a location on the stack,
/// but are handled internally by the builtin's code generation function.
size_t arguments = 0;
};
struct FunctionCall
{
langutil::DebugData::ConstPtr debugData;
std::reference_wrapper<Scope::Function const> function;
std::reference_wrapper<yul::FunctionCall const> functionCall;
/// True, if the call is recursive, i.e. entering the function involves a control flow path (potentially involving
/// more intermediate function calls) that leads back to this very call.
bool recursive = false;
/// True, if the call can return.
bool canContinue = true;
};
struct Assignment
{
langutil::DebugData::ConstPtr debugData;
/// The variables being assigned to also occur as ``output`` in the ``Operation`` containing
/// the assignment, but are also stored here for convenience.
std::vector<VariableSlot> variables;
};
struct Operation
{
/// Stack slots this operation expects at the top of the stack and consumes.
Stack input;
/// Stack slots this operation leaves on the stack as output.
Stack output;
std::variant<FunctionCall, BuiltinCall, Assignment> operation;
};
struct FunctionInfo;
/// A basic control flow block containing ``Operation``s acting on the stack.
/// Maintains a list of entry blocks and a typed exit.
struct BasicBlock
{
struct MainExit {};
struct ConditionalJump
{
langutil::DebugData::ConstPtr debugData;
StackSlot condition;
BasicBlock* nonZero = nullptr;
BasicBlock* zero = nullptr;
};
struct Jump
{
langutil::DebugData::ConstPtr debugData;
BasicBlock* target = nullptr;
/// The only backwards jumps are jumps from loop post to loop condition.
bool backwards = false;
};
struct FunctionReturn
{
langutil::DebugData::ConstPtr debugData;
CFG::FunctionInfo* info = nullptr;
};
struct Terminated {};
langutil::DebugData::ConstPtr debugData;
std::vector<BasicBlock*> entries;
std::vector<Operation> operations;
/// True, if the block is the beginning of a disconnected subgraph. That is, if no block that is reachable
/// from this block is an ancestor of this block. In other words, this is true, if this block is the target
/// of a cut-edge/bridge in the CFG or if the block itself terminates.
bool isStartOfSubGraph = false;
/// True, if there is a path from this block to a function return.
bool needsCleanStack = false;
/// If the block starts a sub-graph and does not lead to a function return, we are free to add junk to it.
bool allowsJunk() const { return isStartOfSubGraph && !needsCleanStack; }
std::variant<MainExit, Jump, ConditionalJump, FunctionReturn, Terminated> exit = MainExit{};
};
struct FunctionInfo
{
langutil::DebugData::ConstPtr debugData;
Scope::Function const& function;
FunctionDefinition const& functionDefinition;
BasicBlock* entry = nullptr;
std::vector<VariableSlot> parameters;
std::vector<VariableSlot> returnVariables;
std::vector<BasicBlock*> exits;
bool canContinue = true;
};
/// The main entry point, i.e. the start of the outermost Yul block.
BasicBlock* entry = nullptr;
/// Subgraphs for functions.
std::map<Scope::Function const*, FunctionInfo> functionInfo;
/// List of functions in order of declaration.
std::list<Scope::Function const*> functions;
/// Container for blocks for explicit ownership.
std::list<BasicBlock> blocks;
/// Container for generated variables for explicit ownership.
/// Ghost variables are generated to store switch conditions when transforming the control flow
/// of a switch to a sequence of conditional jumps.
std::list<Scope::Variable> ghostVariables;
/// Container for generated calls for explicit ownership.
/// Ghost calls are used for the equality comparisons of the switch condition ghost variable with
/// the switch case literals when transforming the control flow of a switch to a sequence of conditional jumps.
std::list<yul::FunctionCall> ghostCalls;
BasicBlock& makeBlock(langutil::DebugData::ConstPtr _debugData)
{
return blocks.emplace_back(BasicBlock{std::move(_debugData), {}, {}});
}
};
}
| 9,824
|
C++
|
.h
| 227
| 41.101322
| 142
| 0.758379
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,423
|
EVMCodeTransform.h
|
ethereum_solidity/libyul/backends/evm/EVMCodeTransform.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Code generator for translating Yul / inline assembly to EVM.
*/
#pragma once
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/backends/evm/VariableReferenceCounter.h>
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/AST.h>
#include <libyul/Scope.h>
#include <optional>
#include <stack>
namespace solidity::langutil
{
class ErrorReporter;
}
namespace solidity::yul
{
struct AsmAnalysisInfo;
struct CodeTransformContext
{
std::map<Scope::Function const*, AbstractAssembly::LabelID> functionEntryIDs;
std::map<Scope::Variable const*, size_t> variableStackHeights;
std::map<Scope::Variable const*, unsigned> variableReferences;
struct JumpInfo
{
AbstractAssembly::LabelID label; ///< Jump's LabelID to jump to.
int targetStackHeight; ///< Stack height after the jump.
};
struct ForLoopLabels
{
JumpInfo post; ///< Jump info for jumping to post branch.
JumpInfo done; ///< Jump info for jumping to done branch.
};
std::stack<ForLoopLabels> forLoopStack;
};
class CodeTransform
{
public:
/// Use named labels for functions 1) Yes and check that the names are unique
/// 2) For none of the functions 3) for the first function of each name.
enum class UseNamedLabels { YesAndForceUnique, Never, ForFirstFunctionOfEachName };
/// Create the code transformer.
/// @param _identifierAccessCodeGen used to generate code for identifiers external to the inline assembly
/// As a side-effect of its construction, translates the Yul code and appends it to the
/// given assembly.
/// Throws StackTooDeepError if a variable is not accessible or if a function has too
/// many parameters.
CodeTransform(
AbstractAssembly& _assembly,
AsmAnalysisInfo& _analysisInfo,
Block const& _block,
EVMDialect const& _dialect,
BuiltinContext& _builtinContext,
bool _allowStackOpt = false,
ExternalIdentifierAccess::CodeGenerator const& _identifierAccessCodeGen = {},
UseNamedLabels _useNamedLabelsForFunctions = UseNamedLabels::Never
): CodeTransform(
_assembly,
_analysisInfo,
_block,
_allowStackOpt,
_dialect,
_builtinContext,
_identifierAccessCodeGen,
_useNamedLabelsForFunctions,
nullptr,
{},
std::nullopt
)
{
}
std::vector<StackTooDeepError> const& stackErrors() const { return m_stackErrors; }
protected:
using Context = CodeTransformContext;
CodeTransform(
AbstractAssembly& _assembly,
AsmAnalysisInfo& _analysisInfo,
Block const& _block,
bool _allowStackOpt,
EVMDialect const& _dialect,
BuiltinContext& _builtinContext,
ExternalIdentifierAccess::CodeGenerator _identifierAccessCodeGen,
UseNamedLabels _useNamedLabelsForFunctions,
std::shared_ptr<Context> _context,
std::vector<NameWithDebugData> _delayedReturnVariables,
std::optional<AbstractAssembly::LabelID> _functionExitLabel
);
void decreaseReference(YulName _name, Scope::Variable const& _var);
bool unreferenced(Scope::Variable const& _var) const;
/// Marks slots of variables that are not used anymore
/// and were defined in the current scope for reuse.
/// Also POPs unused topmost stack slots,
/// unless @a _popUnusedSlotsAtStackTop is set to false.
void freeUnusedVariables(bool _popUnusedSlotsAtStackTop = true);
/// Marks the stack slot of @a _var to be reused.
void deleteVariable(Scope::Variable const& _var);
public:
void operator()(Literal const& _literal);
void operator()(Identifier const& _identifier);
void operator()(FunctionCall const&);
void operator()(ExpressionStatement const& _statement);
void operator()(Assignment const& _assignment);
void operator()(VariableDeclaration const& _varDecl);
void operator()(If const& _if);
void operator()(Switch const& _switch);
void operator()(FunctionDefinition const&);
void operator()(ForLoop const&);
void operator()(Break const&);
void operator()(Continue const&);
void operator()(Leave const&);
void operator()(Block const& _block);
private:
AbstractAssembly::LabelID labelFromIdentifier(Identifier const& _identifier);
void createFunctionEntryID(FunctionDefinition const& _function);
AbstractAssembly::LabelID functionEntryID(Scope::Function const& _scopeFunction) const;
/// Generates code for an expression that is supposed to return a single value.
void visitExpression(Expression const& _expression);
void visitStatements(std::vector<Statement> const& _statements);
/// Pops all variables declared in the block and checks that the stack height is equal
/// to @a _blockStartStackHeight.
void finalizeBlock(Block const& _block, std::optional<int> _blockStartStackHeight);
void generateMultiAssignment(std::vector<Identifier> const& _variableNames);
void generateAssignment(Identifier const& _variableName);
/// Determines the stack height difference to the given variables. Throws
/// if it is not yet in scope or the height difference is too large. Returns
/// the (positive) stack height difference otherwise.
/// @param _forSwap if true, produces stack error if the difference is invalid for a swap
/// opcode, otherwise checks for validity for a dup opcode.
size_t variableHeightDiff(Scope::Variable const& _var, YulName _name, bool _forSwap);
/// Determines the stack height of the given variable. Throws if the variable is not in scope.
int variableStackHeight(YulName _name) const;
void expectDeposit(int _deposit, int _oldHeight) const;
/// Stores the stack error in the list of errors, appends an invalid opcode
/// and corrects the stack height to the target stack height.
void stackError(StackTooDeepError _error, int _targetStackSize);
/// Ensures stack height is down to @p _targetDepth by appending POP instructions to the output assembly.
/// Returns the number of POP statements that have been appended.
int appendPopUntil(int _targetDepth);
/// Allocates stack slots for remaining delayed return values and sets the function exit stack height.
void setupReturnVariablesAndFunctionExit();
bool returnVariablesAndFunctionExitAreSetup() const
{
return m_functionExitStackHeight.has_value();
}
bool isInsideFunction() const
{
return m_functionExitLabel.has_value();
}
AbstractAssembly& m_assembly;
AsmAnalysisInfo& m_info;
Scope* m_scope = nullptr;
EVMDialect const& m_dialect;
BuiltinContext& m_builtinContext;
bool const m_allowStackOpt = true;
UseNamedLabels const m_useNamedLabelsForFunctions = UseNamedLabels::Never;
std::set<YulName> m_assignedNamedLabels;
ExternalIdentifierAccess::CodeGenerator m_identifierAccessCodeGen;
std::shared_ptr<Context> m_context;
/// Set of variables whose reference counter has reached zero,
/// and whose stack slot will be marked as unused once we reach
/// statement level in the scope where the variable was defined.
std::set<Scope::Variable const*> m_variablesScheduledForDeletion;
std::set<int> m_unusedStackSlots;
/// A list of return variables for which no stack slots have been assigned yet.
std::vector<NameWithDebugData> m_delayedReturnVariables;
/// Function exit label. Used as jump target for ``leave``.
std::optional<AbstractAssembly::LabelID> m_functionExitLabel;
/// The required stack height at the function exit label.
/// This is the minimal stack height covering all return variables. Only set after all
/// return variables were assigned slots.
std::optional<int> m_functionExitStackHeight;
std::vector<StackTooDeepError> m_stackErrors;
};
}
| 8,072
|
C++
|
.h
| 188
| 40.712766
| 106
| 0.783384
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,424
|
EVMObjectCompiler.h
|
ethereum_solidity/libyul/backends/evm/EVMObjectCompiler.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Compiler that transforms Yul Objects to EVM bytecode objects.
*/
#pragma once
#include <optional>
#include <cstdint>
namespace solidity::yul
{
class Object;
class AbstractAssembly;
class EVMDialect;
class EVMObjectCompiler
{
public:
static void compile(
Object const& _object,
AbstractAssembly& _assembly,
EVMDialect const& _dialect,
bool _optimize,
std::optional<uint8_t> _eofVersion
);
private:
EVMObjectCompiler(AbstractAssembly& _assembly, EVMDialect const& _dialect, std::optional<uint8_t> _eofVersion):
m_assembly(_assembly), m_dialect(_dialect), m_eofVersion(_eofVersion)
{}
void run(Object const& _object, bool _optimize);
AbstractAssembly& m_assembly;
EVMDialect const& m_dialect;
std::optional<uint8_t> m_eofVersion;
};
}
| 1,452
|
C++
|
.h
| 45
| 30.311111
| 112
| 0.783107
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,425
|
SSACFGLoopNestingForest.h
|
ethereum_solidity/libyul/backends/evm/SSACFGLoopNestingForest.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/backends/evm/SSACFGTopologicalSort.h>
#include <libyul/backends/evm/SSAControlFlowGraph.h>
#include <libsolutil/DisjointSet.h>
#include <cstddef>
#include <set>
#include <vector>
namespace solidity::yul
{
/// Constructs a loop nesting forest for an SSACFG using Tarjan's algorithm [1].
///
/// [1] Ramalingam, Ganesan. "Identifying loops in almost linear time."
/// ACM Transactions on Programming Languages and Systems (TOPLAS) 21.2 (1999): 175-188.
class SSACFGLoopNestingForest
{
public:
explicit SSACFGLoopNestingForest(ForwardSSACFGTopologicalSort const& _sort);
/// blocks which are not contained in a loop get assigned the loop parent numeric_limit<size_t>::max()
std::vector<size_t> const& loopParents() const { return m_loopParents; }
/// all loop nodes (entry blocks for loops), also nested ones
std::set<size_t> const& loopNodes() const { return m_loopNodes; }
/// root loop nodes in the forest for outer-most loops
std::set<size_t> const& loopRootNodes() const { return m_loopRootNodes; }
private:
void findLoop(size_t _potentialHeader);
void collapse(std::set<size_t> const& _loopBody, size_t _loopHeader);
ForwardSSACFGTopologicalSort const& m_sort;
SSACFG const& m_cfg;
util::ContiguousDisjointSet m_vertexPartition;
std::vector<size_t> m_loopParents;
std::set<size_t> m_loopNodes;
std::set<size_t> m_loopRootNodes;
};
}
| 2,080
|
C++
|
.h
| 48
| 41.520833
| 103
| 0.775632
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,426
|
EthAssemblyAdapter.h
|
ethereum_solidity/libyul/backends/evm/EthAssemblyAdapter.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Adaptor between AbstractAssembly and libevmasm.
*/
#pragma once
#include <libyul/backends/evm/AbstractAssembly.h>
#include <libyul/AsmAnalysis.h>
#include <liblangutil/SourceLocation.h>
#include <functional>
#include <limits>
namespace solidity::evmasm
{
class Assembly;
class AssemblyItem;
}
namespace solidity::yul
{
class EthAssemblyAdapter: public AbstractAssembly
{
public:
explicit EthAssemblyAdapter(evmasm::Assembly& _assembly);
void setSourceLocation(langutil::SourceLocation const& _location) override;
int stackHeight() const override;
void setStackHeight(int height) override;
void appendInstruction(evmasm::Instruction _instruction) override;
void appendConstant(u256 const& _constant) override;
void appendLabel(LabelID _labelId) override;
void appendLabelReference(LabelID _labelId) override;
size_t newLabelId() override;
size_t namedLabel(std::string const& _name, size_t _params, size_t _returns, std::optional<size_t> _sourceID) override;
void appendLinkerSymbol(std::string const& _linkerSymbol) override;
void appendVerbatim(bytes _data, size_t _arguments, size_t _returnVariables) override;
void appendJump(int _stackDiffAfter, JumpType _jumpType) override;
void appendJumpTo(LabelID _labelId, int _stackDiffAfter, JumpType _jumpType) override;
void appendJumpToIf(LabelID _labelId, JumpType _jumpType) override;
void appendAssemblySize() override;
std::pair<std::shared_ptr<AbstractAssembly>, SubID> createSubAssembly(bool _creation, std::string _name = {}) override;
void appendEOFCreate(ContainerID _containerID) override;
void appendReturnContract(ContainerID _containerID) override;
void appendDataOffset(std::vector<SubID> const& _subPath) override;
void appendDataSize(std::vector<SubID> const& _subPath) override;
SubID appendData(bytes const& _data) override;
void appendToAuxiliaryData(bytes const& _data) override;
void appendImmutable(std::string const& _identifier) override;
void appendImmutableAssignment(std::string const& _identifier) override;
void appendAuxDataLoadN(uint16_t _offset) override;
void markAsInvalid() override;
langutil::EVMVersion evmVersion() const override;
private:
static LabelID assemblyTagToIdentifier(evmasm::AssemblyItem const& _tag);
void appendJumpInstruction(evmasm::Instruction _instruction, JumpType _jumpType);
evmasm::Assembly& m_assembly;
std::map<SubID, u256> m_dataHashBySubId;
size_t m_nextDataCounter = std::numeric_limits<size_t>::max() / 2;
};
}
| 3,164
|
C++
|
.h
| 69
| 43.956522
| 120
| 0.805132
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,427
|
SSAControlFlowGraphBuilder.h
|
ethereum_solidity/libyul/backends/evm/SSAControlFlowGraphBuilder.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Transformation of a Yul AST into a control flow graph.
*
* Based on https://doi.org/10.1007/978-3-642-37051-9_6
* Braun, Matthias, et al. "Simple and efficient construction of static single assignment form."
* Compiler Construction: 22nd International Conference, CC 2013,
* ETAPS 2013, Rome, Italy, March 16-24, 2013. Proceedings 22. Springer Berlin Heidelberg, 2013.
*
* We have small deviations in Algorithms 2 and 4, as the paper's presentation leads to trivial phis being spuriously
* removed from not yet sealed blocks via a call to addPhiOperands in Algorithm 4. Instead, we perform the deletion
* of trivial phis only after a block has been sealed, i.e., all block's predecessors are present.
*/
#pragma once
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libyul/backends/evm/ControlFlow.h>
#include <libyul/backends/evm/SSAControlFlowGraph.h>
#include <stack>
namespace solidity::yul
{
class SSAControlFlowGraphBuilder
{
SSAControlFlowGraphBuilder(
ControlFlow& _controlFlow,
SSACFG& _graph,
AsmAnalysisInfo const& _analysisInfo,
ControlFlowSideEffectsCollector const& _sideEffects,
Dialect const& _dialect
);
public:
SSAControlFlowGraphBuilder(SSAControlFlowGraphBuilder const&) = delete;
SSAControlFlowGraphBuilder& operator=(SSAControlFlowGraphBuilder const&) = delete;
static std::unique_ptr<ControlFlow> build(
AsmAnalysisInfo const& _analysisInfo,
Dialect const& _dialect,
Block const& _block
);
void operator()(ExpressionStatement const& _statement);
void operator()(Assignment const& _assignment);
void operator()(VariableDeclaration const& _varDecl);
void operator()(FunctionDefinition const&);
void operator()(If const& _if);
void operator()(Switch const& _switch);
void operator()(ForLoop const&);
void operator()(Break const&);
void operator()(Continue const&);
void operator()(Leave const&);
void operator()(Block const& _block);
SSACFG::ValueId operator()(FunctionCall const& _call);
SSACFG::ValueId operator()(Identifier const& _identifier);
SSACFG::ValueId operator()(Literal const& _literal);
private:
void cleanUnreachable();
SSACFG::ValueId tryRemoveTrivialPhi(SSACFG::ValueId _phi);
void assign(std::vector<std::reference_wrapper<Scope::Variable const>> _variables, Expression const* _expression);
std::vector<SSACFG::ValueId> visitFunctionCall(FunctionCall const& _call);
void registerFunctionDefinition(FunctionDefinition const& _functionDefinition);
void buildFunctionGraph(Scope::Function const* _function, FunctionDefinition const* _functionDefinition);
SSACFG::ValueId zero();
SSACFG::ValueId readVariable(Scope::Variable const& _variable, SSACFG::BlockId _block);
SSACFG::ValueId readVariableRecursive(Scope::Variable const& _variable, SSACFG::BlockId _block);
SSACFG::ValueId addPhiOperands(Scope::Variable const& _variable, SSACFG::ValueId _phi);
void writeVariable(Scope::Variable const& _variable, SSACFG::BlockId _block, SSACFG::ValueId _value);
ControlFlow& m_controlFlow;
SSACFG& m_graph;
AsmAnalysisInfo const& m_info;
ControlFlowSideEffectsCollector const& m_sideEffects;
Dialect const& m_dialect;
std::vector<std::tuple<Scope::Function const*, FunctionDefinition const*>> m_functionDefinitions;
SSACFG::BlockId m_currentBlock;
SSACFG::BasicBlock& currentBlock() { return m_graph.block(m_currentBlock); }
Scope* m_scope = nullptr;
Scope::Function const& lookupFunction(YulName _name) const;
Scope::Variable const& lookupVariable(YulName _name) const;
struct BlockInfo {
bool sealed = false;
std::vector<std::tuple<SSACFG::ValueId, std::reference_wrapper<Scope::Variable const>>> incompletePhis;
};
std::vector<BlockInfo> m_blockInfo;
BlockInfo& blockInfo(SSACFG::BlockId _block)
{
if (_block.value >= m_blockInfo.size())
m_blockInfo.resize(_block.value + 1, {});
return m_blockInfo[_block.value];
}
void sealBlock(SSACFG::BlockId _block);
std::map<
Scope::Variable const*,
std::vector<std::optional<SSACFG::ValueId>>
> m_currentDef;
struct ForLoopInfo {
SSACFG::BlockId breakBlock;
SSACFG::BlockId continueBlock;
};
std::stack<ForLoopInfo> m_forLoopInfo;
std::optional<SSACFG::ValueId>& currentDef(Scope::Variable const& _variable, SSACFG::BlockId _block)
{
auto& varDefs = m_currentDef[&_variable];
if (varDefs.size() <= _block.value)
varDefs.resize(_block.value + 1);
return varDefs.at(_block.value);
}
void conditionalJump(
langutil::DebugData::ConstPtr _debugData,
SSACFG::ValueId _condition,
SSACFG::BlockId _nonZero,
SSACFG::BlockId _zero
);
void jump(
langutil::DebugData::ConstPtr _debugData,
SSACFG::BlockId _target
);
void tableJump(
langutil::DebugData::ConstPtr _debugData,
SSACFG::ValueId _value,
std::map<u256, SSACFG::BlockId> _cases,
SSACFG::BlockId _defaultCase
);
FunctionDefinition const* findFunctionDefinition(Scope::Function const* _function) const;
};
}
| 5,576
|
C++
|
.h
| 134
| 39.402985
| 116
| 0.778557
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,428
|
SSACFGTopologicalSort.h
|
ethereum_solidity/libyul/backends/evm/SSACFGTopologicalSort.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/backends/evm/SSAControlFlowGraph.h>
#include <cstddef>
#include <set>
#include <vector>
namespace solidity::yul
{
/// Performs a topological sort on the forward CFG (no back/cross edges)
class ForwardSSACFGTopologicalSort
{
public:
explicit ForwardSSACFGTopologicalSort(SSACFG const& _cfg);
std::vector<size_t> const& preOrder() const { return m_preOrder; }
std::vector<size_t> const& postOrder() const { return m_postOrder; }
std::set<size_t> const& backEdgeTargets() const { return m_backEdgeTargets; }
SSACFG const& cfg() const { return m_cfg; }
bool backEdge(SSACFG::BlockId const& _block1, SSACFG::BlockId const& _block2) const;
size_t preOrderIndexOf(size_t _block) const { return m_blockWisePreOrder[_block]; }
size_t maxSubtreePreOrderIndexOf(size_t _block) const { return m_blockWiseMaxSubtreePreOrder[_block]; }
private:
void dfs(size_t _vertex);
/// Checks if block1 is an ancestor of block2, ie there's a path from block1 to block2 in the dfs tree
bool ancestor(size_t _block1, size_t _block2) const;
SSACFG const& m_cfg;
std::vector<char> m_explored{};
std::vector<size_t> m_postOrder{};
std::vector<size_t> m_preOrder{};
std::vector<size_t> m_blockWisePreOrder{};
std::vector<size_t> m_blockWiseMaxSubtreePreOrder{};
std::vector<std::tuple<size_t, size_t>> m_potentialBackEdges{};
std::set<size_t> m_backEdgeTargets{};
};
}
| 2,080
|
C++
|
.h
| 47
| 42.382979
| 104
| 0.766568
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,429
|
StackHelpers.h
|
ethereum_solidity/libyul/backends/evm/StackHelpers.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/backends/evm/ControlFlowGraph.h>
#include <libyul/Exceptions.h>
#include <libsolutil/Visitor.h>
#include <range/v3/algorithm/all_of.hpp>
#include <range/v3/algorithm/any_of.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/take.hpp>
namespace solidity::yul
{
inline std::string stackSlotToString(StackSlot const& _slot)
{
return std::visit(util::GenericVisitor{
[](FunctionCallReturnLabelSlot const& _ret) -> std::string { return "RET[" + _ret.call.get().functionName.name.str() + "]"; },
[](FunctionReturnLabelSlot const&) -> std::string { return "RET"; },
[](VariableSlot const& _var) { return _var.variable.get().name.str(); },
[](LiteralSlot const& _lit) { return toCompactHexWithPrefix(_lit.value); },
[](TemporarySlot const& _tmp) -> std::string { return "TMP[" + _tmp.call.get().functionName.name.str() + ", " + std::to_string(_tmp.index) + "]"; },
[](JunkSlot const&) -> std::string { return "JUNK"; }
}, _slot);
}
inline std::string stackToString(Stack const& _stack)
{
std::string result("[ ");
for (auto const& slot: _stack)
result += stackSlotToString(slot) + ' ';
result += ']';
return result;
}
// Abstraction of stack shuffling operations. Can be defined as actual concept once we switch to C++20.
// Used as an interface for the stack shuffler below.
// The shuffle operation class is expected to internally keep track of a current stack layout (the "source layout")
// that the shuffler is supposed to shuffle to a fixed target stack layout.
// The shuffler works iteratively. At each iteration it instantiates an instance of the shuffle operations and
// queries it for various information about the current source stack layout and the target layout, as described
// in the interface below.
// Based on that information the shuffler decides which is the next optimal operation to perform on the stack
// and calls the corresponding entry point in the shuffling operations (swap, pushOrDupTarget or pop).
/*
template<typename ShuffleOperations>
concept ShuffleOperationConcept = requires(ShuffleOperations ops, size_t sourceOffset, size_t targetOffset, size_t depth) {
// Returns true, iff the current slot at sourceOffset in source layout is a suitable slot at targetOffset.
{ ops.isCompatible(sourceOffset, targetOffset) } -> std::convertible_to<bool>;
// Returns true, iff the slots at the two given source offsets are identical.
{ ops.sourceIsSame(sourceOffset, sourceOffset) } -> std::convertible_to<bool>;
// Returns a positive integer n, if the slot at the given source offset needs n more copies.
// Returns a negative integer -n, if the slot at the given source offsets occurs n times too many.
// Returns zero if the amount of occurrences, in the current source layout, of the slot at the given source offset
// matches the desired amount of occurrences in the target.
{ ops.sourceMultiplicity(sourceOffset) } -> std::convertible_to<int>;
// Returns a positive integer n, if the slot at the given target offset needs n more copies.
// Returns a negative integer -n, if the slot at the given target offsets occurs n times too many.
// Returns zero if the amount of occurrences, in the current source layout, of the slot at the given target offset
// matches the desired amount of occurrences in the target.
{ ops.targetMultiplicity(targetOffset) } -> std::convertible_to<int>;
// Returns true, iff any slot is compatible with the given target offset.
{ ops.targetIsArbitrary(targetOffset) } -> std::convertible_to<bool>;
// Returns the number of slots in the source layout.
{ ops.sourceSize() } -> std::convertible_to<size_t>;
// Returns the number of slots in the target layout.
{ ops.targetSize() } -> std::convertible_to<size_t>;
// Swaps the top most slot in the source with the slot `depth` slots below the top.
// In terms of EVM opcodes this is supposed to be a `SWAP<depth>`.
// In terms of vectors this is supposed to be `std::swap(source.at(source.size() - depth - 1, source.top))`.
{ ops.swap(depth) };
// Pops the top most slot in the source, i.e. the slot at offset ops.sourceSize() - 1.
// In terms of EVM opcodes this is `POP`.
// In terms of vectors this is `source.pop();`.
{ ops.pop() };
// Dups or pushes the slot that is supposed to end up at the given target offset.
{ ops.pushOrDupTarget(targetOffset) };
};
*/
/// Helper class that can perform shuffling of a source stack layout to a target stack layout via
/// abstracted shuffle operations.
template</*ShuffleOperationConcept*/ typename ShuffleOperations>
class Shuffler
{
public:
/// Executes the stack shuffling operations. Instantiates an instance of ShuffleOperations
/// in each iteration. Each iteration performs exactly one operation that modifies the stack.
/// After `shuffle`, source and target have the same size and all slots in the source layout are
/// compatible with the slots at the same target offset.
template<typename... Args>
static void shuffle(Args&&... args)
{
bool needsMoreShuffling = true;
// The shuffling algorithm should always terminate in polynomial time, but we provide a limit
// in case it does not terminate due to a bug.
size_t iterationCount = 0;
while (iterationCount < 1000 && (needsMoreShuffling = shuffleStep(std::forward<Args>(args)...)))
++iterationCount;
yulAssert(!needsMoreShuffling, "Could not create stack layout after 1000 iterations.");
}
private:
// If dupping an ideal slot causes a slot that will still be required to become unreachable, then dup
// the latter slot first.
// @returns true, if it performed a dup.
static bool dupDeepSlotIfRequired(ShuffleOperations& _ops)
{
// Check if the stack is large enough for anything to potentially become unreachable.
if (_ops.sourceSize() < 15)
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 (size_t sourceOffset: ranges::views::iota(0u, _ops.sourceSize() - 15))
{
// This slot needs to be moved.
if (!_ops.isCompatible(sourceOffset, sourceOffset))
{
// If the current top fixes the slot, swap it down now.
if (_ops.isCompatible(_ops.sourceSize() - 1, sourceOffset))
{
_ops.swap(_ops.sourceSize() - sourceOffset - 1);
return true;
}
// Bring up a slot to fix this now, if possible.
if (bringUpTargetSlot(_ops, sourceOffset))
return true;
// Otherwise swap up the slot that will fix the offending slot.
for (auto offset: ranges::views::iota(sourceOffset + 1, _ops.sourceSize()))
if (_ops.isCompatible(offset, sourceOffset))
{
_ops.swap(_ops.sourceSize() - offset - 1);
return true;
}
// Otherwise give up - we will need stack compression or stack limit evasion.
}
// We need another copy of this slot.
else if (_ops.sourceMultiplicity(sourceOffset) > 0)
{
// If this slot occurs again later, we skip this occurrence.
if (ranges::any_of(
ranges::views::iota(sourceOffset + 1, _ops.sourceSize()),
[&](size_t _offset) { return _ops.sourceIsSame(sourceOffset, _offset); }
))
continue;
// Bring up the target slot that would otherwise become unreachable.
for (size_t targetOffset: ranges::views::iota(0u, _ops.targetSize()))
if (!_ops.targetIsArbitrary(targetOffset) && _ops.isCompatible(sourceOffset, targetOffset))
{
_ops.pushOrDupTarget(targetOffset);
return true;
}
}
}
return false;
}
/// Finds a slot to dup or push with the aim of eventually fixing @a _targetOffset in the target.
/// In the simplest case, the slot at @a _targetOffset has a multiplicity > 0, i.e. it can directly be dupped or pushed
/// and the next iteration will fix @a _targetOffset.
/// But, in general, there may already be enough copies of the slot that is supposed to end up at @a _targetOffset
/// on stack, s.t. it cannot be dupped again. In that case there has to be a copy of the desired slot on stack already
/// elsewhere that is not yet in place (`nextOffset` below). The fact that ``nextOffset`` is not in place means that
/// we can (recursively) try bringing up the slot that is supposed to end up at ``nextOffset`` in the *target*.
/// When the target slot at ``nextOffset`` is fixed, the current source slot at ``nextOffset`` will be
/// at the stack top, which is the slot required at @a _targetOffset.
static bool bringUpTargetSlot(ShuffleOperations& _ops, size_t _targetOffset)
{
std::list<size_t> toVisit{_targetOffset};
std::set<size_t> visited;
while (!toVisit.empty())
{
auto offset = *toVisit.begin();
toVisit.erase(toVisit.begin());
visited.emplace(offset);
if (_ops.targetMultiplicity(offset) > 0)
{
_ops.pushOrDupTarget(offset);
return true;
}
// There must be another slot we can dup/push that will lead to the target slot at ``offset`` to be fixed.
for (auto nextOffset: ranges::views::iota(0u, std::min(_ops.sourceSize(), _ops.targetSize())))
if (
!_ops.isCompatible(nextOffset, nextOffset) &&
_ops.isCompatible(nextOffset, offset)
)
if (!visited.count(nextOffset))
toVisit.emplace_back(nextOffset);
}
return false;
}
/// Performs a single stack operation, transforming the source layout closer to the target layout.
template<typename... Args>
static bool shuffleStep(Args&&... args)
{
ShuffleOperations ops{std::forward<Args>(args)...};
// All source slots are final.
if (ranges::all_of(
ranges::views::iota(0u, ops.sourceSize()),
[&](size_t _index) { return ops.isCompatible(_index, _index); }
))
{
// Bring up all remaining target slots, if any, or terminate otherwise.
if (ops.sourceSize() < ops.targetSize())
{
if (!dupDeepSlotIfRequired(ops))
yulAssert(bringUpTargetSlot(ops, ops.sourceSize()), "");
return true;
}
return false;
}
size_t sourceTop = ops.sourceSize() - 1;
// If we no longer need the current stack top, we pop it, unless we need an arbitrary slot at this position
// in the target.
if (
ops.sourceMultiplicity(sourceTop) < 0 &&
!ops.targetIsArbitrary(sourceTop)
)
{
ops.pop();
return true;
}
yulAssert(ops.targetSize() > 0, "");
// If the top is not supposed to be exactly what is on top right now, try to find a lower position to swap it to.
if (!ops.isCompatible(sourceTop, sourceTop) || ops.targetIsArbitrary(sourceTop))
for (size_t offset: ranges::views::iota(0u, std::min(ops.sourceSize(), ops.targetSize())))
// It makes sense to swap to a lower position, if
if (
!ops.isCompatible(offset, offset) && // The lower slot is not already in position.
!ops.sourceIsSame(offset, sourceTop) && // We would not just swap identical slots.
ops.isCompatible(sourceTop, offset) // The lower position wants to have this slot.
)
{
// We cannot swap that deep.
if (ops.sourceSize() - offset - 1 > 16)
{
// If there is a reachable slot to be removed, park the current top there.
for (size_t swapDepth: ranges::views::iota(1u, 17u) | ranges::views::reverse)
if (ops.sourceMultiplicity(ops.sourceSize() - 1 - swapDepth) < 0)
{
ops.swap(swapDepth);
if (ops.targetIsArbitrary(sourceTop))
// Usually we keep a slot that is to-be-removed, if the current top is arbitrary.
// However, since we are in a stack-too-deep situation, pop it immediately
// to compress the stack (we can always push back junk in the end).
ops.pop();
return true;
}
// Otherwise we rely on stack compression or stack-to-memory.
}
ops.swap(ops.sourceSize() - offset - 1);
return true;
}
// ops.sourceSize() > ops.targetSize() cannot be true anymore, since if the source top is no longer required,
// we already popped it, and if it is required, we already swapped it down to a suitable target position.
yulAssert(ops.sourceSize() <= ops.targetSize(), "");
// If a lower slot should be removed, try to bring up the slot that should end up there and bring it up.
// Note that after the cases above, there will always be a target slot to duplicate in this case.
for (size_t offset: ranges::views::iota(0u, ops.sourceSize()))
if (
!ops.isCompatible(offset, offset) && // The lower slot is not already in position.
ops.sourceMultiplicity(offset) < 0 && // We have too many copies of this slot.
offset <= ops.targetSize() && // There is a target slot at this position.
!ops.targetIsArbitrary(offset) // And that target slot is not arbitrary.
)
{
if (!dupDeepSlotIfRequired(ops))
yulAssert(bringUpTargetSlot(ops, offset), "");
return true;
}
// At this point we want to keep all slots.
for (size_t i = 0; i < ops.sourceSize(); ++i)
yulAssert(ops.sourceMultiplicity(i) >= 0, "");
yulAssert(ops.sourceSize() <= ops.targetSize(), "");
// If the top is not in position, try to find a slot that wants to be at the top and swap it up.
if (!ops.isCompatible(sourceTop, sourceTop))
for (size_t sourceOffset: ranges::views::iota(0u, ops.sourceSize()))
if (
!ops.isCompatible(sourceOffset, sourceOffset) &&
ops.isCompatible(sourceOffset, sourceTop)
)
{
ops.swap(ops.sourceSize() - sourceOffset - 1);
return true;
}
// If we still need more slots, produce a suitable one.
if (ops.sourceSize() < ops.targetSize())
{
if (!dupDeepSlotIfRequired(ops))
yulAssert(bringUpTargetSlot(ops, ops.sourceSize()), "");
return true;
}
// The stack has the correct size, each slot has the correct number of copies and the top is in position.
yulAssert(ops.sourceSize() == ops.targetSize(), "");
size_t size = ops.sourceSize();
for (size_t i = 0; i < ops.sourceSize(); ++i)
yulAssert(ops.sourceMultiplicity(i) == 0 && (ops.targetIsArbitrary(i) || ops.targetMultiplicity(i) == 0), "");
yulAssert(ops.isCompatible(sourceTop, sourceTop), "");
auto swappableOffsets = ranges::views::iota(size > 17 ? size - 17 : 0u, size);
// If we find a lower slot that is out of position, but also compatible with the top, swap that up.
for (size_t offset: swappableOffsets)
if (!ops.isCompatible(offset, offset) && ops.isCompatible(sourceTop, offset))
{
ops.swap(size - offset - 1);
return true;
}
// Swap up any reachable slot that is still out of position.
for (size_t offset: swappableOffsets)
if (!ops.isCompatible(offset, offset) && !ops.sourceIsSame(offset, sourceTop))
{
ops.swap(size - offset - 1);
return true;
}
// We are in a stack-too-deep situation and try to reduce the stack size.
// If the current top is merely kept since the target slot is arbitrary, pop it.
if (ops.targetIsArbitrary(sourceTop) && ops.sourceMultiplicity(sourceTop) <= 0)
{
ops.pop();
return true;
}
// If any reachable slot is merely kept, since the target slot is arbitrary, swap it up and pop it.
for (size_t offset: swappableOffsets)
if (ops.targetIsArbitrary(offset) && ops.sourceMultiplicity(offset) <= 0)
{
ops.swap(size - offset - 1);
ops.pop();
return true;
}
// We cannot avoid a stack-too-deep error. Repeat the above without restricting to reachable slots.
for (size_t offset: ranges::views::iota(0u, size))
if (!ops.isCompatible(offset, offset) && ops.isCompatible(sourceTop, offset))
{
ops.swap(size - offset - 1);
return true;
}
for (size_t offset: ranges::views::iota(0u, size))
if (!ops.isCompatible(offset, offset) && !ops.sourceIsSame(offset, sourceTop))
{
ops.swap(size - offset - 1);
return true;
}
yulAssert(false, "");
// FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794)
throw std::exception();
}
};
/// A simple optimized map for mapping StackSlots to ints.
class Multiplicity
{
public:
int& operator[](StackSlot const& _slot)
{
if (auto* p = std::get_if<FunctionCallReturnLabelSlot>(&_slot))
return m_functionCallReturnLabelSlotMultiplicity[*p];
if (std::holds_alternative<FunctionReturnLabelSlot>(_slot))
return m_functionReturnLabelSlotMultiplicity;
if (auto* p = std::get_if<VariableSlot>(&_slot))
return m_variableSlotMultiplicity[*p];
if (auto* p = std::get_if<LiteralSlot>(&_slot))
return m_literalSlotMultiplicity[*p];
if (auto* p = std::get_if<TemporarySlot>(&_slot))
return m_temporarySlotMultiplicity[*p];
yulAssert(std::holds_alternative<JunkSlot>(_slot));
return m_junkSlotMultiplicity;
}
int at(StackSlot const& _slot) const
{
if (auto* p = std::get_if<FunctionCallReturnLabelSlot>(&_slot))
return m_functionCallReturnLabelSlotMultiplicity.at(*p);
if (std::holds_alternative<FunctionReturnLabelSlot>(_slot))
return m_functionReturnLabelSlotMultiplicity;
if (auto* p = std::get_if<VariableSlot>(&_slot))
return m_variableSlotMultiplicity.at(*p);
if (auto* p = std::get_if<LiteralSlot>(&_slot))
return m_literalSlotMultiplicity.at(*p);
if (auto* p = std::get_if<TemporarySlot>(&_slot))
return m_temporarySlotMultiplicity.at(*p);
yulAssert(std::holds_alternative<JunkSlot>(_slot));
return m_junkSlotMultiplicity;
}
private:
std::map<FunctionCallReturnLabelSlot, int> m_functionCallReturnLabelSlotMultiplicity;
int m_functionReturnLabelSlotMultiplicity = 0;
std::map<VariableSlot, int> m_variableSlotMultiplicity;
std::map<LiteralSlot, int> m_literalSlotMultiplicity;
std::map<TemporarySlot, int> m_temporarySlotMultiplicity;
int m_junkSlotMultiplicity = 0;
};
/// Transforms @a _currentStack to @a _targetStack, invoking the provided shuffling operations.
/// Modifies @a _currentStack itself after each invocation of the shuffling operations.
/// @a _swap is a function with signature void(unsigned) that is called when the top most slot is swapped with
/// the slot `depth` slots below the top. In terms of EVM opcodes this is supposed to be a `SWAP<depth>`.
/// @a _pushOrDup is a function with signature void(StackSlot const&) that is called to push or dup the slot given as
/// its argument to the stack top.
/// @a _pop is a function with signature void() that is called when the top most slot is popped.
template<typename Swap, typename PushOrDup, typename Pop>
void createStackLayout(Stack& _currentStack, Stack const& _targetStack, Swap _swap, PushOrDup _pushOrDup, Pop _pop)
{
struct ShuffleOperations
{
Stack& currentStack;
Stack const& targetStack;
Swap swapCallback;
PushOrDup pushOrDupCallback;
Pop popCallback;
Multiplicity multiplicity;
ShuffleOperations(
Stack& _currentStack,
Stack const& _targetStack,
Swap _swap,
PushOrDup _pushOrDup,
Pop _pop
):
currentStack(_currentStack),
targetStack(_targetStack),
swapCallback(_swap),
pushOrDupCallback(_pushOrDup),
popCallback(_pop)
{
for (auto const& slot: currentStack)
--multiplicity[slot];
for (auto&& [offset, slot]: targetStack | ranges::views::enumerate)
if (std::holds_alternative<JunkSlot>(slot) && offset < currentStack.size())
++multiplicity[currentStack.at(offset)];
else
++multiplicity[slot];
}
bool isCompatible(size_t _source, size_t _target)
{
return
_source < currentStack.size() &&
_target < targetStack.size() &&
(
std::holds_alternative<JunkSlot>(targetStack.at(_target)) ||
currentStack.at(_source) == targetStack.at(_target)
);
}
bool sourceIsSame(size_t _lhs, size_t _rhs) { return currentStack.at(_lhs) == currentStack.at(_rhs); }
int sourceMultiplicity(size_t _offset) { return multiplicity.at(currentStack.at(_offset)); }
int targetMultiplicity(size_t _offset) { return multiplicity.at(targetStack.at(_offset)); }
bool targetIsArbitrary(size_t offset)
{
return offset < targetStack.size() && std::holds_alternative<JunkSlot>(targetStack.at(offset));
}
void swap(size_t _i)
{
swapCallback(static_cast<unsigned>(_i));
std::swap(currentStack.at(currentStack.size() - _i - 1), currentStack.back());
}
size_t sourceSize() { return currentStack.size(); }
size_t targetSize() { return targetStack.size(); }
void pop()
{
popCallback();
currentStack.pop_back();
}
void pushOrDupTarget(size_t _offset)
{
auto const& targetSlot = targetStack.at(_offset);
pushOrDupCallback(targetSlot);
currentStack.push_back(targetSlot);
}
};
Shuffler<ShuffleOperations>::shuffle(_currentStack, _targetStack, _swap, _pushOrDup, _pop);
yulAssert(_currentStack.size() == _targetStack.size(), "");
for (auto&& [current, target]: ranges::zip_view(_currentStack, _targetStack))
if (std::holds_alternative<JunkSlot>(target))
current = JunkSlot{};
else
yulAssert(current == target, "");
}
}
| 21,481
|
C++
|
.h
| 478
| 41.506276
| 150
| 0.716023
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,430
|
StackLayoutGenerator.h
|
ethereum_solidity/libyul/backends/evm/StackLayoutGenerator.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Stack layout generator for Yul to EVM code generation.
*/
#pragma once
#include <libyul/backends/evm/ControlFlowGraph.h>
#include <map>
namespace solidity::yul
{
struct StackLayout
{
struct BlockInfo
{
/// Complete stack layout that is required for entering a block.
Stack entryLayout;
/// The resulting stack layout after executing the block.
Stack exitLayout;
};
std::map<CFG::BasicBlock const*, BlockInfo> blockInfos;
/// For each operation the complete stack layout that:
/// - has the slots required for the operation at the stack top.
/// - will have the operation result in a layout that makes it easy to achieve the next desired layout.
std::map<CFG::Operation const*, Stack> operationEntryLayout;
};
class StackLayoutGenerator
{
public:
struct StackTooDeep
{
/// Number of slots that need to be saved.
size_t deficit = 0;
/// Set of variables, eliminating which would decrease the stack deficit.
std::vector<YulName> variableChoices;
};
static StackLayout run(CFG const& _cfg);
/// @returns a map from function names to the stack too deep errors occurring in that function.
/// Requires @a _cfg to be a control flow graph generated from disambiguated Yul.
/// The empty string is mapped to the stack too deep errors of the main entry point.
static std::map<YulName, std::vector<StackTooDeep>> reportStackTooDeep(CFG const& _cfg);
/// @returns all stack too deep errors in the function named @a _functionName.
/// Requires @a _cfg to be a control flow graph generated from disambiguated Yul.
/// If @a _functionName is empty, the stack too deep errors of the main entry point are reported instead.
static std::vector<StackTooDeep> reportStackTooDeep(CFG const& _cfg, YulName _functionName);
private:
StackLayoutGenerator(StackLayout& _context, CFG::FunctionInfo const* _functionInfo);
/// @returns the optimal entry stack layout, s.t. @a _operation can be applied to it and
/// the result can be transformed to @a _exitStack with minimal stack shuffling.
/// Simultaneously stores the entry layout required for executing the operation in m_layout.
Stack propagateStackThroughOperation(Stack _exitStack, CFG::Operation const& _operation, bool _aggressiveStackCompression = false);
/// @returns the desired stack layout at the entry of @a _block, assuming the layout after
/// executing the block should be @a _exitStack.
Stack propagateStackThroughBlock(Stack _exitStack, CFG::BasicBlock const& _block, bool _aggressiveStackCompression = false);
/// Main algorithm walking the graph from entry to exit and propagating back the stack layouts to the entries.
/// Iteratively reruns itself along backwards jumps until the layout is stabilized.
void processEntryPoint(CFG::BasicBlock const& _entry, CFG::FunctionInfo const* _functionInfo = nullptr);
/// @returns the best known exit layout of @a _block, if all dependencies are already @a _visited.
/// If not, adds the dependencies to @a _dependencyList and @returns std::nullopt.
std::optional<Stack> getExitLayoutOrStageDependencies(
CFG::BasicBlock const& _block,
std::set<CFG::BasicBlock const*> const& _visited,
std::list<CFG::BasicBlock const*>& _dependencyList
) const;
/// @returns a pair of ``{jumpingBlock, targetBlock}`` for each backwards jump in the graph starting at @a _entry.
std::list<std::pair<CFG::BasicBlock const*, CFG::BasicBlock const*>> collectBackwardsJumps(CFG::BasicBlock const& _entry) const;
/// After the main algorithms, layouts at conditional jumps are merely compatible, i.e. the exit layout of the
/// jumping block is a superset of the entry layout of the target block. This function modifies the entry layouts
/// of conditional jump targets, s.t. the entry layout of target blocks match the exit layout of the jumping block
/// exactly, except that slots not required after the jump are marked as `JunkSlot`s.
void stitchConditionalJumps(CFG::BasicBlock const& _block);
/// Calculates the ideal stack layout, s.t. both @a _stack1 and @a _stack2 can be achieved with minimal
/// stack shuffling when starting from the returned layout.
static Stack combineStack(Stack const& _stack1, Stack const& _stack2);
/// Walks through the CFG and reports any stack too deep errors that would occur when generating code for it
/// without countermeasures.
std::vector<StackTooDeep> reportStackTooDeep(CFG::BasicBlock const& _entry) const;
/// @returns a copy of @a _stack stripped of all duplicates and slots that can be freely generated.
/// Attempts to create a layout that requires a minimal amount of operations to reconstruct the original
/// stack @a _stack.
static Stack compressStack(Stack _stack);
//// Fills in junk when entering branches that do not need a clean stack in case the result is cheaper.
void fillInJunk(CFG::BasicBlock const& _block, CFG::FunctionInfo const* _functionInfo = nullptr);
StackLayout& m_layout;
CFG::FunctionInfo const* m_currentFunctionInfo = nullptr;
};
}
| 5,664
|
C++
|
.h
| 98
| 55.632653
| 132
| 0.772686
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,432
|
AbstractAssembly.h
|
ethereum_solidity/libyul/backends/evm/AbstractAssembly.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @date 2017
* Abstract assembly interface, subclasses of which are to be used with the generic
* bytecode generator.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libsolutil/Common.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Numeric.h>
#include <liblangutil/EVMVersion.h>
#include <functional>
#include <memory>
#include <optional>
namespace solidity::langutil
{
struct SourceLocation;
}
namespace solidity::evmasm
{
enum class Instruction: uint8_t;
}
namespace solidity::yul
{
struct Identifier;
///
/// Assembly class that abstracts both the libevmasm assembly and the new Yul assembly.
///
class AbstractAssembly
{
public:
using LabelID = size_t;
using SubID = size_t;
using ContainerID = uint8_t;
enum class JumpType { Ordinary, IntoFunction, OutOfFunction };
virtual ~AbstractAssembly() = default;
/// Set a new source location valid starting from the next instruction.
virtual void setSourceLocation(langutil::SourceLocation const& _location) = 0;
/// Retrieve the current height of the stack. This does not have to be zero
/// at the beginning.
virtual int stackHeight() const = 0;
virtual void setStackHeight(int height) = 0;
/// Append an EVM instruction.
virtual void appendInstruction(evmasm::Instruction _instruction) = 0;
/// Append a constant.
virtual void appendConstant(u256 const& _constant) = 0;
/// Append a label.
virtual void appendLabel(LabelID _labelId) = 0;
/// Append a label reference.
virtual void appendLabelReference(LabelID _labelId) = 0;
/// Generate a new unique label.
virtual LabelID newLabelId() = 0;
/// Returns a label identified by the given name. Creates it if it does not yet exist.
virtual LabelID namedLabel(std::string const& _name, size_t _params, size_t _returns, std::optional<size_t> _sourceID) = 0;
/// Append a reference to a to-be-linked symbol.
/// Currently, we assume that the value is always a 20 byte number.
virtual void appendLinkerSymbol(std::string const& _name) = 0;
/// Append raw bytes that stay untouched by the optimizer.
virtual void appendVerbatim(bytes _data, size_t _arguments, size_t _returnVariables) = 0;
/// Append a jump instruction.
/// @param _stackDiffAfter the stack adjustment after this instruction.
/// This is helpful to stack height analysis if there is no continuing control flow.
virtual void appendJump(int _stackDiffAfter, JumpType _jumpType = JumpType::Ordinary) = 0;
/// Append a jump-to-immediate operation.
/// @param _stackDiffAfter the stack adjustment after this instruction.
virtual void appendJumpTo(LabelID _labelId, int _stackDiffAfter = 0, JumpType _jumpType = JumpType::Ordinary) = 0;
/// Append a jump-to-if-immediate operation.
virtual void appendJumpToIf(LabelID _labelId, JumpType _jumpType = JumpType::Ordinary) = 0;
/// Append the assembled size as a constant.
virtual void appendAssemblySize() = 0;
/// Creates a new sub-assembly, which can be referenced using dataSize and dataOffset.
virtual std::pair<std::shared_ptr<AbstractAssembly>, SubID> createSubAssembly(bool _creation, std::string _name = "") = 0;
/// Appends the offset of the given sub-assembly or data.
virtual void appendDataOffset(std::vector<SubID> const& _subPath) = 0;
/// Appends the size of the given sub-assembly or data.
virtual void appendDataSize(std::vector<SubID> const& _subPath) = 0;
/// Appends the given data to the assembly and returns its ID.
virtual SubID appendData(bytes const& _data) = 0;
/// Appends loading an immutable variable.
virtual void appendImmutable(std::string const& _identifier) = 0;
/// Appends an assignment to an immutable variable.
virtual void appendImmutableAssignment(std::string const& _identifier) = 0;
/// Appends an operation that loads 32 bytes of data from a known offset relative to the start of the static_aux_data area of the EOF data section.
/// Note that static_aux_data is only a part or the data section.
/// It is preceded by the pre_deploy_data, whose size is not determined before the bytecode is assembled, and which cannot be accessed using this function.
/// The function is meant to allow indexing into static_aux_data in a way that's independent of the size of pre_deploy_data.
virtual void appendAuxDataLoadN(uint16_t _offset) = 0;
/// Appends EOF contract creation instruction which takes creation code from subcontainer with _containerID.
virtual void appendEOFCreate(ContainerID _containerID) = 0;
/// Appends EOF contract return instruction which returns a subcontainer ID (_containerID) with auxiliary data filled in.
virtual void appendReturnContract(ContainerID _containerID) = 0;
/// Appends data to the very end of the bytecode. Repeated calls concatenate.
/// EOF auxiliary data in data section and the auxiliary data are different things.
virtual void appendToAuxiliaryData(bytes const& _data) = 0;
/// Mark this assembly as invalid. Any attempt to request bytecode from it should throw.
virtual void markAsInvalid() = 0;
/// @returns the EVM version the assembly targets.
virtual langutil::EVMVersion evmVersion() const = 0;
};
enum class IdentifierContext { LValue, RValue, VariableDeclaration, NonExternal };
/// Object that is used to resolve references and generate code for access to identifiers external
/// to inline assembly (not used in standalone assembly mode).
struct ExternalIdentifierAccess
{
using Resolver = std::function<bool(Identifier const&, IdentifierContext, bool /*_crossesFunctionBoundary*/)>;
/// Resolve an external reference given by the identifier in the given context.
/// @returns the size of the value (number of stack slots) or size_t(-1) if not found.
Resolver resolve;
using CodeGenerator = std::function<void(Identifier const&, IdentifierContext, yul::AbstractAssembly&)>;
/// Generate code for retrieving the value (rvalue context) or storing the value (lvalue context)
/// of an identifier. The code should be appended to the assembly. In rvalue context, the value is supposed
/// to be put onto the stack, in lvalue context, the value is assumed to be at the top of the stack.
CodeGenerator generateCode;
};
}
| 6,815
|
C++
|
.h
| 129
| 50.930233
| 156
| 0.773307
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,433
|
NoOutputAssembly.h
|
ethereum_solidity/libyul/backends/evm/NoOutputAssembly.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Assembly interface that ignores everything. Can be used as a backend for a compilation dry-run.
*/
#pragma once
#include <libyul/backends/evm/AbstractAssembly.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libevmasm/LinkerObject.h>
#include <map>
namespace solidity::langutil
{
struct SourceLocation;
}
namespace solidity::yul
{
/**
* Assembly class that just ignores everything and only performs stack counting.
* The purpose is to use this assembly for compilation dry-runs.
*/
class NoOutputAssembly: public AbstractAssembly
{
public:
explicit NoOutputAssembly(langutil::EVMVersion _evmVersion): m_evmVersion(_evmVersion) { }
~NoOutputAssembly() override = default;
void setSourceLocation(langutil::SourceLocation const&) override {}
int stackHeight() const override { return m_stackHeight; }
void setStackHeight(int height) override { m_stackHeight = height; }
void appendInstruction(evmasm::Instruction _instruction) override;
void appendConstant(u256 const& _constant) override;
void appendLabel(LabelID _labelId) override;
void appendLabelReference(LabelID _labelId) override;
LabelID newLabelId() override;
LabelID namedLabel(std::string const& _name, size_t _params, size_t _returns, std::optional<size_t> _sourceID) override;
void appendLinkerSymbol(std::string const& _name) override;
void appendVerbatim(bytes _data, size_t _arguments, size_t _returnVariables) override;
void appendJump(int _stackDiffAfter, JumpType _jumpType) override;
void appendJumpTo(LabelID _labelId, int _stackDiffAfter, JumpType _jumpType) override;
void appendJumpToIf(LabelID _labelId, JumpType _jumpType) override;
void appendAssemblySize() override;
std::pair<std::shared_ptr<AbstractAssembly>, SubID> createSubAssembly(bool _creation, std::string _name = "") override;
void appendDataOffset(std::vector<SubID> const& _subPath) override;
void appendDataSize(std::vector<SubID> const& _subPath) override;
SubID appendData(bytes const& _data) override;
void appendToAuxiliaryData(bytes const&) override {}
void appendImmutable(std::string const& _identifier) override;
void appendImmutableAssignment(std::string const& _identifier) override;
void appendAuxDataLoadN(uint16_t) override;
void appendEOFCreate(ContainerID) override;
void appendReturnContract(ContainerID) override;
void markAsInvalid() override {}
langutil::EVMVersion evmVersion() const override { return m_evmVersion; }
private:
int m_stackHeight = 0;
langutil::EVMVersion m_evmVersion;
};
/**
* EVM dialect that does not generate any code.
*/
class NoOutputEVMDialect: public EVMDialect
{
public:
explicit NoOutputEVMDialect(EVMDialect const& _copyFrom);
BuiltinFunctionForEVM const& builtin(BuiltinHandle const& _handle) const override;
};
}
| 3,463
|
C++
|
.h
| 78
| 42.410256
| 121
| 0.799643
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,434
|
ControlFlow.h
|
ethereum_solidity/libyul/backends/evm/ControlFlow.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/AST.h>
#include <libyul/Scope.h>
#include <libyul/backends/evm/SSACFGLiveness.h>
#include <libyul/backends/evm/SSAControlFlowGraph.h>
namespace solidity::yul
{
struct ControlFlow;
struct ControlFlowLiveness{
explicit ControlFlowLiveness(ControlFlow const& _controlFlow);
std::reference_wrapper<ControlFlow const> controlFlow;
std::unique_ptr<SSACFGLiveness> mainLiveness;
std::vector<std::unique_ptr<SSACFGLiveness>> functionLiveness;
};
struct ControlFlow
{
std::unique_ptr<SSACFG> mainGraph{std::make_unique<SSACFG>()};
std::vector<std::unique_ptr<SSACFG>> functionGraphs{};
std::vector<std::tuple<Scope::Function const*, SSACFG const*>> functionGraphMapping{};
SSACFG const* functionGraph(Scope::Function const* _function)
{
auto it = std::find_if(functionGraphMapping.begin(), functionGraphMapping.end(), [_function](auto const& tup) { return _function == std::get<0>(tup); });
if (it != functionGraphMapping.end())
return std::get<1>(*it);
return nullptr;
}
std::string toDot(ControlFlowLiveness const* _liveness=nullptr) const
{
if (_liveness)
yulAssert(&_liveness->controlFlow.get() == this);
std::ostringstream output;
output << "digraph SSACFG {\nnodesep=0.7;\ngraph[fontname=\"DejaVu Sans\"]\nnode[shape=box,fontname=\"DejaVu Sans\"];\n\n";
output << mainGraph->toDot(false, std::nullopt, _liveness ? _liveness->mainLiveness.get() : nullptr);
for (size_t index=0; index < functionGraphs.size(); ++index)
output << functionGraphs[index]->toDot(
false,
index+1,
_liveness ? _liveness->functionLiveness[index].get() : nullptr
);
output << "}\n";
return output.str();
}
};
}
| 2,365
|
C++
|
.h
| 58
| 38.344828
| 155
| 0.752618
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,435
|
AsmCodeGen.h
|
ethereum_solidity/libyul/backends/evm/AsmCodeGen.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Helper to compile Yul code using libevmasm.
*/
#pragma once
#include <libyul/backends/evm/AbstractAssembly.h>
#include <libyul/AsmAnalysis.h>
#include <liblangutil/EVMVersion.h>
namespace solidity::evmasm
{
class Assembly;
}
namespace solidity::yul
{
struct Block;
struct AsmAnalysisInfo;
class CodeGenerator
{
public:
/// Performs code generation and appends generated to _assembly.
static void assemble(
Block const& _parsedData,
AsmAnalysisInfo& _analysisInfo,
evmasm::Assembly& _assembly,
langutil::EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
ExternalIdentifierAccess::CodeGenerator _identifierAccess = {},
bool _useNamedLabelsForFunctions = false,
bool _optimizeStackAllocation = false
);
};
}
| 1,432
|
C++
|
.h
| 45
| 29.933333
| 69
| 0.792603
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,436
|
SimplificationRules.h
|
ethereum_solidity/libyul/optimiser/SimplificationRules.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Module for applying replacement rules against Expressions.
*/
#pragma once
#include <libevmasm/SimplificationRule.h>
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Numeric.h>
#include <liblangutil/EVMVersion.h>
#include <liblangutil/DebugData.h>
#include <functional>
#include <optional>
#include <vector>
namespace solidity::yul
{
struct Dialect;
struct AssignedValue;
class Pattern;
using DebugData = langutil::DebugData;
/**
* Container for all simplification rules.
*/
class SimplificationRules
{
public:
/// Noncopiable.
SimplificationRules(SimplificationRules const&) = delete;
SimplificationRules& operator=(SimplificationRules const&) = delete;
using Rule = evmasm::SimplificationRule<Pattern>;
explicit SimplificationRules(std::optional<langutil::EVMVersion> _evmVersion = std::nullopt);
/// @returns a pointer to the first matching pattern and sets the match
/// groups accordingly.
/// @param _ssaValues values of variables that are assigned exactly once.
static Rule const* findFirstMatch(
Expression const& _expr,
Dialect const& _dialect,
std::function<AssignedValue const*(YulName)> const& _ssaValues
);
/// Checks whether the rulelist is non-empty. This is usually enforced
/// by the constructor, but we had some issues with static initialization.
bool isInitialized() const;
static std::optional<std::pair<evmasm::Instruction, std::vector<Expression> const*>>
instructionAndArguments(Dialect const& _dialect, Expression const& _expr);
private:
void addRules(std::vector<Rule> const& _rules);
void addRule(Rule const& _rule);
void resetMatchGroups() { m_matchGroups.clear(); }
std::map<unsigned, Expression const*> m_matchGroups;
std::vector<evmasm::SimplificationRule<Pattern>> m_rules[256];
};
enum class PatternKind
{
Operation,
Constant,
Any
};
/**
* Pattern to match against an expression.
* Also stores matched expressions to retrieve them later, for constructing new expressions using
* ExpressionTemplate.
*/
class Pattern
{
public:
using Builtins = evmasm::EVMBuiltins<Pattern>;
static constexpr size_t WordSize = 256;
using Word = u256;
/// Matches any expression.
Pattern(PatternKind _kind = PatternKind::Any): m_kind(_kind) {}
// Matches a specific constant value.
Pattern(unsigned _value): Pattern(u256(_value)) {}
Pattern(int _value): Pattern(u256(_value)) {}
Pattern(long unsigned _value): Pattern(u256(_value)) {}
// Matches a specific constant value.
Pattern(u256 const& _value): m_kind(PatternKind::Constant), m_data(std::make_shared<u256>(_value)) {}
// Matches a given instruction with given arguments
Pattern(evmasm::Instruction _instruction, std::initializer_list<Pattern> _arguments = {});
/// Sets this pattern to be part of the match group with the identifier @a _group.
/// Inside one rule, all patterns in the same match group have to match expressions from the
/// same expression equivalence class.
void setMatchGroup(unsigned _group, std::map<unsigned, Expression const*>& _matchGroups);
unsigned matchGroup() const { return m_matchGroup; }
bool matches(
Expression const& _expr,
Dialect const& _dialect,
std::function<AssignedValue const*(YulName)> const& _ssaValues
) const;
std::vector<Pattern> arguments() const { return m_arguments; }
/// @returns the data of the matched expression if this pattern is part of a match group.
u256 d() const;
evmasm::Instruction instruction() const;
/// Turns this pattern into an actual expression. Should only be called
/// for patterns resulting from an action, i.e. with match groups assigned.
Expression toExpression(langutil::DebugData::ConstPtr const& _debugData, langutil::EVMVersion _evmVersion) const;
private:
Expression const& matchGroupValue() const;
PatternKind m_kind = PatternKind::Any;
evmasm::Instruction m_instruction; ///< Only valid if m_kind is Operation
std::shared_ptr<u256> m_data; ///< Only valid if m_kind is Constant
std::vector<Pattern> m_arguments;
unsigned m_matchGroup = 0;
std::map<unsigned, Expression const*>* m_matchGroups = nullptr;
};
}
| 4,821
|
C++
|
.h
| 119
| 38.521008
| 114
| 0.772474
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,444
|
OptimiserStep.h
|
ethereum_solidity/libyul/optimiser/OptimiserStep.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/Exceptions.h>
#include <optional>
#include <string>
#include <set>
namespace solidity::yul
{
struct Dialect;
struct Block;
class NameDispenser;
struct OptimiserStepContext
{
Dialect const& dialect;
NameDispenser& dispenser;
std::set<YulName> const& reservedIdentifiers;
/// The value nullopt represents creation code
std::optional<size_t> expectedExecutionsPerDeployment;
};
/**
* Construction to create dynamically callable objects out of the
* statically callable optimiser steps.
*/
struct OptimiserStep
{
explicit OptimiserStep(std::string _name): name(std::move(_name)) {}
virtual ~OptimiserStep() = default;
virtual void run(OptimiserStepContext&, Block&) const = 0;
/// @returns non-nullopt if the step cannot be run, for example because it requires
/// an SMT solver to be loaded, but none is available. In that case, the string
/// contains a human-readable reason.
virtual std::optional<std::string> invalidInCurrentEnvironment() const = 0;
std::string name;
};
template <class Step>
struct OptimiserStepInstance: public OptimiserStep
{
private:
template<typename T>
struct HasInvalidInCurrentEnvironmentMethod
{
private:
template<typename U> static auto test(int) -> decltype(U::invalidInCurrentEnvironment(), std::true_type());
template<typename> static std::false_type test(...);
public:
static constexpr bool value = decltype(test<T>(0))::value;
};
public:
OptimiserStepInstance(): OptimiserStep{Step::name} {}
void run(OptimiserStepContext& _context, Block& _ast) const override
{
Step::run(_context, _ast);
}
std::optional<std::string> invalidInCurrentEnvironment() const override
{
if constexpr (HasInvalidInCurrentEnvironmentMethod<Step>::value)
return Step::invalidInCurrentEnvironment();
else
return std::nullopt;
}
};
}
| 2,517
|
C++
|
.h
| 75
| 31.56
| 109
| 0.781443
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,445
|
FunctionCallFinder.h
|
ethereum_solidity/libyul/optimiser/FunctionCallFinder.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
/**
* AST walker that finds all calls to a function of a given name.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <vector>
namespace solidity::yul
{
/**
* Finds all calls to a function of a given name using an ASTModifier.
*
* Prerequisite: Disambiguator
*/
std::vector<FunctionCall*> findFunctionCalls(Block& _block, YulName _functionName);
/**
* Finds all calls to a function of a given name using an ASTWalker.
*
* Prerequisite: Disambiguator
*/
std::vector<FunctionCall const*> findFunctionCalls(Block const& _block, YulName _functionName);
}
| 1,252
|
C++
|
.h
| 35
| 33.885714
| 95
| 0.777133
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,447
|
Suite.h
|
ethereum_solidity/libyul/optimiser/Suite.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser suite that combines all steps and also provides the settings for the heuristics.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/NameDispenser.h>
#include <liblangutil/EVMVersion.h>
#include <set>
#include <string>
#include <string_view>
#include <memory>
namespace solidity::yul
{
struct AsmAnalysisInfo;
struct Dialect;
class GasMeter;
class Object;
/**
* Optimiser suite that combines all steps and also provides the settings for the heuristics.
* Only optimizes the code of the provided object, does not descend into the sub-objects.
*/
class OptimiserSuite
{
public:
static constexpr size_t MaxRounds = 12;
/// Special characters that do not represent optimiser steps but are allowed in abbreviation sequences.
/// Some of them (like whitespace) are ignored, others (like brackets) are a part of the syntax.
static constexpr char NonStepAbbreviations[] = " \n[]:";
enum class Debug
{
None,
PrintStep,
PrintChanges
};
OptimiserSuite(OptimiserStepContext& _context, Debug _debug = Debug::None): m_context(_context), m_debug(_debug) {}
/// The value nullopt for `_expectedExecutionsPerDeployment` represents creation code.
static void run(
Dialect const& _dialect,
GasMeter const* _meter,
Object& _object,
bool _optimizeStackAllocation,
std::string_view _optimisationSequence,
std::string_view _optimisationCleanupSequence,
std::optional<size_t> _expectedExecutionsPerDeployment,
std::set<YulName> const& _externallyUsedIdentifiers = {}
);
/// Ensures that specified sequence of step abbreviations is well-formed and can be executed.
/// @throw OptimizerException if the sequence is invalid
static void validateSequence(std::string_view _stepAbbreviations);
/// Check whether the provided sequence is empty provided that the allowed characters are
/// whitespace, newline and :
static bool isEmptyOptimizerSequence(std::string const& _sequence);
void runSequence(std::vector<std::string> const& _steps, Block& _ast);
void runSequence(std::string_view _stepAbbreviations, Block& _ast, bool _repeatUntilStable = false);
static std::map<std::string, std::unique_ptr<OptimiserStep>> const& allSteps();
static std::map<std::string, char> const& stepNameToAbbreviationMap();
static std::map<char, std::string> const& stepAbbreviationToNameMap();
private:
OptimiserStepContext& m_context;
Debug m_debug;
};
}
| 3,169
|
C++
|
.h
| 78
| 38.602564
| 116
| 0.782948
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,448
|
KnowledgeBase.h
|
ethereum_solidity/libyul/optimiser/KnowledgeBase.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Class that can answer questions about values of variables and their relations.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <libsolutil/Common.h>
#include <libsolutil/Numeric.h>
#include <map>
#include <functional>
namespace solidity::yul
{
struct Dialect;
struct AssignedValue;
/**
* Class that can answer questions about values of variables and their relations.
*
* Requires a callback that returns the current value of the variable.
* The value can change any time during the lifetime of the KnowledgeBase,
* it will update its internal data structure accordingly.
*
* This means that the code the KnowledgeBase is used on does not need to be in SSA
* form.
* The only requirement is that the assigned values are movable expressions.
*
* There is a constructor to provide all SSA values right at the beginning.
* If you use this, the KnowledgeBase will be slightly more efficient.
*
* Internally, tries to find groups of variables that have a mutual constant
* difference and stores these differences always relative to a specific
* representative variable of the group.
*
* There is a special group which is the constant values. Those use the
* empty YulName as representative "variable".
*/
class KnowledgeBase
{
public:
/// Constructor for arbitrary value callback that allows for variable values
/// to change in between calls to functions of this class.
explicit KnowledgeBase(std::function<AssignedValue const*(YulName)> _variableValues):
m_variableValues(std::move(_variableValues))
{}
/// Constructor to use if source code is in SSA form and values are constant.
explicit KnowledgeBase(std::map<YulName, AssignedValue> const& _ssaValues);
bool knownToBeDifferent(YulName _a, YulName _b);
std::optional<u256> differenceIfKnownConstant(YulName _a, YulName _b);
bool knownToBeDifferentByAtLeast32(YulName _a, YulName _b);
bool knownToBeZero(YulName _a);
std::optional<u256> valueIfKnownConstant(YulName _a);
std::optional<u256> valueIfKnownConstant(Expression const& _expression);
private:
/**
* Constant offset relative to a reference variable, or absolute constant if the
* reference variable is the empty YulName.
*/
struct VariableOffset
{
YulName reference;
u256 offset;
bool isAbsolute() const
{
return reference.empty();
}
std::optional<u256> absoluteValue() const
{
if (isAbsolute())
return offset;
else
return std::nullopt;
}
};
VariableOffset explore(YulName _var);
std::optional<VariableOffset> explore(Expression const& _value);
/// Retrieves the current value of a variable and potentially resets the variable if it is not up to date.
Expression const* valueOf(YulName _var);
/// Resets all information about the variable and removes it from its group,
/// potentially finding a new representative.
void reset(YulName _var);
VariableOffset setOffset(YulName _variable, VariableOffset _value);
/// If true, we can assume that variable values never change and skip some steps.
bool m_valuesAreSSA = false;
/// Callback to retrieve the current value of a variable.
std::function<AssignedValue const*(YulName)> m_variableValues;
/// Offsets for each variable to one representative per group.
/// The empty string is the representative of the constant value zero.
std::map<YulName, VariableOffset> m_offsets;
/// Last known value of each variable we queried.
std::map<YulName, Expression const*> m_lastKnownValue;
/// For each representative, variables that use it to offset from.
std::map<YulName, std::set<YulName>> m_groupMembers;
};
}
| 4,301
|
C++
|
.h
| 107
| 37.981308
| 107
| 0.778097
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,450
|
StackToMemoryMover.h
|
ethereum_solidity/libyul/optimiser/StackToMemoryMover.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
/**
* Optimisation stage that moves Yul variables from stack to memory.
*/
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <liblangutil/SourceLocation.h>
#include <libsolutil/Common.h>
#include <libsolutil/Numeric.h>
#include <list>
namespace solidity::yul
{
/**
* Optimisation stage that moves Yul variables from stack to memory.
* It takes a map from functions names and variable names to memory offsets.
* It then transforms the AST as follows:
*
* Single variable declarations are replaced by mstore's as follows:
* If a is in the map, replace
* let a
* by
* mstore(<memory offset for a>, 0)
* respectively, replace
* let a := expr
* by
* mstore(<memory offset for a>, expr)
*
* In a multi-variable declaration, variables to be moved are replaced by fresh variables and then moved to memory:
* If b and d are in the map, replace
* let a, b, c, d := f()
* by
* let _1, _2, _3, _4 := f()
* mstore(<memory offset for d>, _4)
* mstore(<memory offset for b>, _2)
* let c := _3
* let a := _1
*
* In case f has return parameters that are moved to memory, fewer variables are returned and the return values read
* from memory instead. Assume the third return parameter of f (i.e. c) has to be moved to memory:
* let a, b, c, d := f()
* then it is replaced by
* let _1, _2, _4 := f()
* mstore(<memory offset for d>, _4)
* mstore(<memory offset for b>, _2)
* let c := mload(<memory offset of third return parameter of f>)
* let a := _1
*
* Assignments to single variables are replaced by mstore's:
* If a is in the map, replace
* a := expr
* by
* mstore(<memory offset for a>, expr)
*
* Assignments to multiple variables are split up similarly to multi-variable declarations:
* If b and d are in the map, replace
* a, b, c, d := f()
* by
* let _1, _2, _3, _4 := f()
* mstore(<memory offset for d>, _4)
* mstore(<memory offset for b>, _2)
* c := _3
* a := _1
*
* Replace all references to a variable ``a`` in the map by ``mload(<memory offset for a>)``.
*
* Function arguments are moved at the beginning of a function body:
* If a1 is in the map, replace
* function f(a1, a2, ..., a17)
* {
* ...
* sstore(a1, a17)
* }
* by
* function f(a1, a2, ..., a17)
* {
* mstore(<memory offset for a1>, a1)
* ...
* sstore(mload(<memory offset for a1>, a17)
* }
* This relies on the code transform popping arguments that are no longer used, if they are on the stack top.
*
* Functions with only one return argument that has to be moved are encapsulated in a wrapper function as follows:
* Suppose b and r need to be moved in:
* function f(a, b) -> r
* {
* ...body of f...
* r := b
* ...body of f continued...
* }
* then replace by:
* function f(a, b) -> r
* {
* mstore(<memory offset of b>, b)
* mstore(<memory offset of r>, 0)
* f_1(a)
* r := mload(<memory offset of r>)
* }
* function f_1(a)
* {
* ...body of f...
* mstore(<memory offset of r>, mload(<memory offset of b>))
* ...body of f continued...
* }
*
* Prerequisite: Disambiguator, ForLoopInitRewriter, FunctionHoister.
*/
class StackToMemoryMover: ASTModifier
{
public:
/**
* Runs the stack to memory mover.
* @param _reservedMemory Is the amount of previously reserved memory,
* i.e. the lowest memory offset to which variables can be moved.
* @param _memorySlots A map from variables to a slot in memory. Based on the slot a unique offset in the memory range
* between _reservedMemory and _reservedMemory + 32 * _numRequiredSlots is calculated for each
* variable.
* @param _numRequiredSlots The number of slots required in total. The maximum value that may occur in @a _memorySlots.
*/
static void run(
OptimiserStepContext& _context,
u256 _reservedMemory,
std::map<YulName, uint64_t> const& _memorySlots,
uint64_t _numRequiredSlots,
Block& _block
);
using ASTModifier::operator();
void operator()(FunctionDefinition& _functionDefinition) override;
void operator()(Block& _block) override;
using ASTModifier::visit;
void visit(Expression& _expression) override;
private:
class VariableMemoryOffsetTracker
{
public:
VariableMemoryOffsetTracker(
u256 _reservedMemory,
std::map<YulName, uint64_t> const& _memorySlots,
uint64_t _numRequiredSlots
): m_reservedMemory(_reservedMemory), m_memorySlots(_memorySlots), m_numRequiredSlots(_numRequiredSlots)
{}
/// @returns a YulName containing the memory offset to be assigned to @a _variable as number literal
/// or std::nullopt if the variable should not be moved.
std::optional<LiteralValue> operator()(YulName const& _variable) const;
/// @returns a YulName containing the memory offset to be assigned to @a _variable as number literal
/// or std::nullopt if the variable should not be moved.
std::optional<LiteralValue> operator()(NameWithDebugData const& _variable) const;
/// @returns a YulName containing the memory offset to be assigned to @a _variable as number literal
/// or std::nullopt if the variable should not be moved.
std::optional<LiteralValue> operator()(Identifier const& _variable) const;
private:
u256 m_reservedMemory;
std::map<YulName, uint64_t> const& m_memorySlots;
uint64_t m_numRequiredSlots = 0;
};
struct FunctionMoveInfo
{
std::vector<std::optional<YulName>> returnVariableSlots;
};
StackToMemoryMover(
OptimiserStepContext& _context,
VariableMemoryOffsetTracker const& _memoryOffsetTracker,
std::map<YulName, std::vector<NameWithDebugData>> _functionReturnVariables
);
OptimiserStepContext& m_context;
VariableMemoryOffsetTracker const& m_memoryOffsetTracker;
NameDispenser& m_nameDispenser;
/// Map from function names to the return variables of the function with that name.
std::map<YulName, std::vector<NameWithDebugData>> m_functionReturnVariables;
/// List of functions generated while running this step that are to be appended to the code in the end.
std::list<Statement> m_newFunctionDefinitions;
};
}
| 7,037
|
C++
|
.h
| 187
| 35.459893
| 120
| 0.69188
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,451
|
NameSimplifier.h
|
ethereum_solidity/libyul/optimiser/NameSimplifier.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/YulName.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <map>
#include <set>
#include <string>
namespace solidity::yul
{
struct Dialect;
/**
* Pass to "simplify" all identifier names.
*
* The purpose of this is to make generated code more readable, but also
* to remove AST identifiers that could lead to a different sorting order
* and thus influence e.g. the order of function inlining.
*
* Prerequisites: Disambiguator, FunctionHoister, FunctionGrouper
*/
class NameSimplifier: public ASTModifier
{
public:
static constexpr char const* name{"NameSimplifier"};
static void run(OptimiserStepContext& _context, Block& _ast)
{
NameSimplifier{_context, _ast}(_ast);
}
using ASTModifier::operator();
void operator()(VariableDeclaration& _varDecl) override;
void operator()(Identifier& _identifier) override;
void operator()(FunctionCall& _funCall) override;
void operator()(FunctionDefinition& _funDef) override;
private:
NameSimplifier(OptimiserStepContext& _context, Block const& _ast);
/// Tries to rename a list of variables.
void renameVariables(std::vector<NameWithDebugData>& _variables);
void findSimplification(YulName const& _name);
void translate(YulName& _name);
OptimiserStepContext& m_context;
std::map<YulName, YulName> m_translations;
};
}
| 2,085
|
C++
|
.h
| 57
| 34.666667
| 73
| 0.785892
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,452
|
FullInliner.h
|
ethereum_solidity/libyul/optimiser/FullInliner.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that performs function inlining for arbitrary functions.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/Exceptions.h>
#include <liblangutil/SourceLocation.h>
#include <optional>
#include <set>
#include <utility>
namespace solidity::yul
{
class NameCollector;
/**
* Optimiser component that modifies an AST in place, inlining functions.
* Expressions are expected to be split, i.e. the component will only inline
* function calls that are at the root of the expression and that only contains
* variables or literals as arguments. More specifically, it will inline
* - let x1, ..., xn := f(a1, ..., am)
* - x1, ..., xn := f(a1, ..., am)
* - f(a1, ..., am)
*
* The transform changes code of the form
*
* function f(a, b) -> c { ... }
* let z := f(x, y)
*
* into
*
* function f(a, b) -> c { ... }
*
* let f_b := y
* let f_a := x
* let f_c
* code of f, with replacements: a -> f_a, b -> f_b, c -> f_c
* let z := f_c
*
* Prerequisites: Disambiguator
* More efficient if run after: Function Hoister, Expression Splitter
*/
class FullInliner: public ASTModifier
{
public:
static constexpr char const* name{"FullInliner"};
static void run(OptimiserStepContext& _context, Block& _ast);
/// Inlining heuristic.
/// @param _callSite the name of the function in which the function call is located.
bool shallInline(FunctionCall const& _funCall, YulName _callSite);
FunctionDefinition* function(YulName _name)
{
auto it = m_functions.find(_name);
if (it != m_functions.end())
return it->second;
return nullptr;
}
/// Adds the size of _funCall to the size of _callSite. This is just
/// a rough estimate that is done during inlining. The proper size
/// should be determined after inlining is completed.
void tentativelyUpdateCodeSize(YulName _function, YulName _callSite);
private:
enum Pass { InlineTiny, InlineRest };
FullInliner(Block& _ast, NameDispenser& _dispenser, Dialect const& _dialect);
void run(Pass _pass);
/// @returns a map containing the maximum depths of a call chain starting at each
/// function. For recursive functions, the value is one larger than for all others.
std::map<YulName, size_t> callDepths() const;
void updateCodeSize(FunctionDefinition const& _fun);
void handleBlock(YulName _currentFunctionName, Block& _block);
bool recursive(FunctionDefinition const& _fun) const;
Pass m_pass;
/// The AST to be modified. The root block itself will not be modified, because
/// we store pointers to functions.
Block& m_ast;
std::map<YulName, FunctionDefinition*> m_functions;
/// Functions not to be inlined (because they contain the ``leave`` statement).
std::set<YulName> m_noInlineFunctions;
/// True, if the code contains a ``memoryguard`` and we can expect to be able to move variables to memory later.
bool m_hasMemoryGuard = false;
/// Set of recursive functions.
std::set<YulName> m_recursiveFunctions;
/// Names of functions to always inline.
std::set<YulName> m_singleUse;
/// Variables that are constants (used for inlining heuristic)
std::set<YulName> m_constants;
std::map<YulName, size_t> m_functionSizes;
NameDispenser& m_nameDispenser;
Dialect const& m_dialect;
};
/**
* Class that walks the AST of a block that does not contain function definitions and perform
* the actual code modifications.
*/
class InlineModifier: public ASTModifier
{
public:
InlineModifier(FullInliner& _driver, NameDispenser& _nameDispenser, YulName _functionName, Dialect const& _dialect):
m_currentFunction(std::move(_functionName)),
m_driver(_driver),
m_nameDispenser(_nameDispenser),
m_dialect(_dialect)
{ }
void operator()(Block& _block) override;
private:
std::optional<std::vector<Statement>> tryInlineStatement(Statement& _statement);
std::vector<Statement> performInline(Statement& _statement, FunctionCall& _funCall);
YulName m_currentFunction;
FullInliner& m_driver;
NameDispenser& m_nameDispenser;
Dialect const& m_dialect;
};
/**
* Creates a copy of a block that is supposed to be the body of a function.
* Applies replacements to referenced variables and creates new names for
* variable declarations.
*/
class BodyCopier: public ASTCopier
{
public:
BodyCopier(
NameDispenser& _nameDispenser,
std::map<YulName, YulName> _variableReplacements
):
m_nameDispenser(_nameDispenser),
m_variableReplacements(std::move(_variableReplacements))
{}
using ASTCopier::operator ();
Statement operator()(VariableDeclaration const& _varDecl) override;
Statement operator()(FunctionDefinition const& _funDef) override;
YulName translateIdentifier(YulName _name) override;
NameDispenser& m_nameDispenser;
std::map<YulName, YulName> m_variableReplacements;
};
}
| 5,598
|
C++
|
.h
| 151
| 35.02649
| 117
| 0.756507
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,453
|
Semantics.h
|
ethereum_solidity/libyul/optimiser/Semantics.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Specific AST walkers that collect semantical facts.
*/
#pragma once
#include <libyul/AST.h>
#include <libyul/Object.h>
#include <libyul/SideEffects.h>
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <set>
namespace solidity::yul
{
struct Dialect;
/**
* Specific AST walker that determines side-effect free-ness and movability of code.
* Enters into function definitions.
*/
class SideEffectsCollector: public ASTWalker
{
public:
explicit SideEffectsCollector(
Dialect const& _dialect,
std::map<YulName, SideEffects> const* _functionSideEffects = nullptr
): m_dialect(_dialect), m_functionSideEffects(_functionSideEffects) {}
SideEffectsCollector(
Dialect const& _dialect,
Expression const& _expression,
std::map<YulName, SideEffects> const* _functionSideEffects = nullptr
);
SideEffectsCollector(Dialect const& _dialect, Statement const& _statement);
SideEffectsCollector(
Dialect const& _dialect,
Block const& _ast,
std::map<YulName, SideEffects> const* _functionSideEffects = nullptr
);
SideEffectsCollector(
Dialect const& _dialect,
ForLoop const& _ast,
std::map<YulName, SideEffects> const* _functionSideEffects = nullptr
);
using ASTWalker::operator();
void operator()(FunctionCall const& _functionCall) override;
bool movable() const { return m_sideEffects.movable; }
bool movableRelativeTo(SideEffects const& _other, bool _codeContainsMSize)
{
if (!m_sideEffects.cannotLoop)
return false;
if (m_sideEffects.movable)
return true;
if (
!m_sideEffects.movableApartFromEffects ||
m_sideEffects.storage == SideEffects::Write ||
m_sideEffects.otherState == SideEffects::Write ||
m_sideEffects.memory == SideEffects::Write ||
m_sideEffects.transientStorage == SideEffects::Write
)
return false;
if (m_sideEffects.otherState == SideEffects::Read)
if (_other.otherState == SideEffects::Write)
return false;
if (m_sideEffects.storage == SideEffects::Read)
if (_other.storage == SideEffects::Write)
return false;
if (m_sideEffects.memory == SideEffects::Read)
if (_codeContainsMSize || _other.memory == SideEffects::Write)
return false;
if (m_sideEffects.transientStorage == SideEffects::Read)
if (_other.transientStorage == SideEffects::Write)
return false;
return true;
}
bool canBeRemoved(bool _allowMSizeModification = false) const
{
if (_allowMSizeModification)
return m_sideEffects.canBeRemovedIfNoMSize;
else
return m_sideEffects.canBeRemoved;
}
bool cannotLoop() const { return m_sideEffects.cannotLoop; }
bool invalidatesStorage() const { return m_sideEffects.storage == SideEffects::Write; }
bool invalidatesMemory() const { return m_sideEffects.memory == SideEffects::Write; }
SideEffects sideEffects() { return m_sideEffects; }
private:
Dialect const& m_dialect;
std::map<YulName, SideEffects> const* m_functionSideEffects = nullptr;
SideEffects m_sideEffects;
};
/**
* This class can be used to determine the side-effects of user-defined functions.
*
* It is given a dialect and a mapping that represents the direct calls from user-defined
* functions to other user-defined functions and built-in functions.
*/
class SideEffectsPropagator
{
public:
static std::map<YulName, SideEffects> sideEffects(
Dialect const& _dialect,
CallGraph const& _directCallGraph
);
};
/**
* Class that can be used to find out if certain code contains the MSize instruction
* or a verbatim bytecode builtin (which is always assumed that it could contain MSize).
*
* Note that this is a purely syntactic property meaning that even if this is false,
* the code can still contain calls to functions that contain the msize instruction.
*
* The only safe way to determine this is by passing the full AST.
*/
class MSizeFinder: public ASTWalker
{
public:
static bool containsMSize(Dialect const& _dialect, Block const& _ast);
static bool containsMSize(Dialect const& _dialect, Object const& _object);
using ASTWalker::operator();
void operator()(FunctionCall const& _funCall) override;
private:
MSizeFinder(Dialect const& _dialect): m_dialect(_dialect) {}
Dialect const& m_dialect;
bool m_msizeFound = false;
};
/**
* Class that can be used to find out if the given function contains the ``leave`` statement.
*
* Returns true even in the case where the function definition contains another function definition
* that contains the leave statement.
*/
class LeaveFinder: public ASTWalker
{
public:
static bool containsLeave(FunctionDefinition const& _fun)
{
LeaveFinder f;
f(_fun);
return f.m_leaveFound;
}
using ASTWalker::operator();
void operator()(Leave const&) override { m_leaveFound = true; }
private:
LeaveFinder() = default;
bool m_leaveFound = false;
};
/**
* Specific AST walker that determines whether an expression is movable
* and collects the referenced variables.
* Can only be used on expressions.
*/
class MovableChecker: public SideEffectsCollector
{
public:
explicit MovableChecker(
Dialect const& _dialect,
std::map<YulName, SideEffects> const* _functionSideEffects = nullptr
): SideEffectsCollector(_dialect, _functionSideEffects) {}
MovableChecker(Dialect const& _dialect, Expression const& _expression);
void operator()(Identifier const& _identifier) override;
/// Disallow visiting anything apart from Expressions (this throws).
void visit(Statement const&) override;
using ASTWalker::visit;
std::set<YulName> const& referencedVariables() const { return m_variableReferences; }
private:
/// Which variables the current expression references.
std::set<YulName> m_variableReferences;
};
struct ControlFlowSideEffects;
/**
* Helper class to find "irregular" control flow.
* This includes termination, break, continue and leave.
* In general, it is applied only to "simple" statements. The control-flow
* of loops, switches and if statements is always "FlowOut" with the assumption
* that the caller will descend into them.
*/
class TerminationFinder
{
public:
/// "Terminate" here means that there is no continuing control-flow.
/// If this is applied to a function that can revert or stop, but can also
/// exit regularly, the property is set to "FlowOut".
enum class ControlFlow { FlowOut, Break, Continue, Terminate, Leave };
TerminationFinder(
Dialect const& _dialect,
std::map<YulName, ControlFlowSideEffects> const* _functionSideEffects = nullptr
): m_dialect(_dialect), m_functionSideEffects(_functionSideEffects) {}
/// @returns the index of the first statement in the provided sequence
/// that is an unconditional ``break``, ``continue``, ``leave`` or a
/// call to a terminating function.
/// If control flow can continue at the end of the list,
/// returns `FlowOut` and ``size_t(-1)``.
/// The function might return ``FlowOut`` even though control
/// flow cannot actually continue.
std::pair<ControlFlow, size_t> firstUnconditionalControlFlowChange(
std::vector<Statement> const& _statements
);
/// @returns the control flow type of the given statement.
/// This function could return FlowOut even if control flow never continues.
ControlFlow controlFlowKind(Statement const& _statement);
/// @returns true if the expression contains a
/// call to a terminating function, i.e. a function that does not have
/// a regular "flow out" control-flow (it might also be recursive).
bool containsNonContinuingFunctionCall(Expression const& _expr);
private:
Dialect const& m_dialect;
std::map<YulName, ControlFlowSideEffects> const* m_functionSideEffects;
};
}
| 8,278
|
C++
|
.h
| 220
| 35.340909
| 99
| 0.770334
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,455
|
UnusedFunctionsCommon.h
|
ethereum_solidity/libyul/optimiser/UnusedFunctionsCommon.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/optimiser/Metrics.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/AST.h>
namespace solidity::yul::unusedFunctionsCommon
{
/// Returns true if applying UnusedFunctionParameterPruner is not helpful or redundant because the
/// inliner will be able to handle it anyway.
inline bool tooSimpleToBePruned(FunctionDefinition const& _f)
{
return _f.body.statements.size() <= 1 && CodeSize::codeSize(_f.body) <= 1;
}
/// Given a function definition `_original`, this function returns a 'linking' function that calls
/// `_originalFunctionName` (with reduced parameters and return values).
///
/// The parameter `_usedParametersAndReturnVariables` is a pair of boolean-vectors. Its `.first`
/// corresponds to function parameters and its `.second` corresponds to function return-variables. A
/// false value at index `i` means that the corresponding function parameter / return-variable at
/// index `i` is unused.
///
/// Example:
///
/// Let `_original` be the function `function f_1() -> y { }`. (In practice, this function usually cannot
/// be inlined and has parameters / return-variables that are unused.)
/// Let `_usedParametersAndReturnVariables` be `({}, {false})`
/// Let `_originalFunctionName` be `f`.
/// Let `_linkingFunctionName` be `f_1`.
///
/// Then the returned linking function would be `function f_1() -> y_1 { f() }`
FunctionDefinition createLinkingFunction(
FunctionDefinition const& _original,
std::pair<std::vector<bool>, std::vector<bool>> const& _usedParametersAndReturns,
YulName const& _originalFunctionName,
YulName const& _linkingFunctionName,
NameDispenser& _nameDispenser
);
}
| 2,345
|
C++
|
.h
| 51
| 44.470588
| 105
| 0.765864
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,461
|
ASTWalker.h
|
ethereum_solidity/libyul/optimiser/ASTWalker.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Generic AST walker.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/Exceptions.h>
#include <libyul/YulName.h>
#include <map>
#include <optional>
#include <set>
#include <vector>
namespace solidity::yul
{
/**
* Generic AST walker.
*/
class ASTWalker
{
public:
virtual ~ASTWalker() = default;
virtual void operator()(Literal const&) {}
virtual void operator()(Identifier const&) {}
virtual void operator()(FunctionCall const& _funCall);
virtual void operator()(ExpressionStatement const& _statement);
virtual void operator()(Assignment const& _assignment);
virtual void operator()(VariableDeclaration const& _varDecl);
virtual void operator()(If const& _if);
virtual void operator()(Switch const& _switch);
virtual void operator()(FunctionDefinition const&);
virtual void operator()(ForLoop const&);
virtual void operator()(Break const&) {}
virtual void operator()(Continue const&) {}
virtual void operator()(Leave const&) {}
virtual void operator()(Block const& _block);
virtual void visit(Statement const& _st);
virtual void visit(Expression const& _e);
protected:
template <class T>
void walkVector(T const& _statements)
{
for (auto const& statement: _statements)
visit(statement);
}
};
/**
* Generic AST modifier (i.e. non-const version of ASTWalker).
*/
class ASTModifier
{
public:
virtual ~ASTModifier() = default;
virtual void operator()(Literal&) {}
virtual void operator()(Identifier&) {}
virtual void operator()(FunctionCall& _funCall);
virtual void operator()(ExpressionStatement& _statement);
virtual void operator()(Assignment& _assignment);
virtual void operator()(VariableDeclaration& _varDecl);
virtual void operator()(If& _if);
virtual void operator()(Switch& _switch);
virtual void operator()(FunctionDefinition&);
virtual void operator()(ForLoop&);
virtual void operator()(Break&);
virtual void operator()(Continue&);
virtual void operator()(Leave&);
virtual void operator()(Block& _block);
virtual void visit(Statement& _st);
virtual void visit(Expression& _e);
protected:
template <class T>
void walkVector(T&& _statements)
{
for (auto& st: _statements)
visit(st);
}
};
namespace detail
{
template <
typename Node,
typename Visitor,
typename Base = std::conditional_t<std::is_const_v<Node>, ASTWalker, ASTModifier>
>
struct ForEach: Base
{
ForEach(Visitor& _visitor): visitor(_visitor) {}
using Base::operator();
void operator()(Node& _node) override
{
visitor(_node);
Base::operator()(_node);
}
Visitor& visitor;
};
}
/// Helper function that traverses the AST and calls the visitor for each
/// node of a specific type.
template<typename Node, typename Entry, typename Visitor>
void forEach(Entry&& _entry, Visitor&& _visitor)
{
detail::ForEach<Node, Visitor&>{_visitor}(_entry);
}
}
| 3,500
|
C++
|
.h
| 116
| 28.293103
| 82
| 0.754235
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,462
|
StackCompressor.h
|
ethereum_solidity/libyul/optimiser/StackCompressor.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimisation stage that aggressively rematerializes certain variables ina a function to free
* space on the stack until it is compilable.
*/
#pragma once
#include <libyul/Object.h>
#include <memory>
namespace solidity::yul
{
struct Dialect;
class Object;
struct FunctionDefinition;
/**
* Optimisation stage that aggressively rematerializes certain variables in a function to free
* space on the stack until it is compilable.
*
* Only runs on the code of the object itself, does not descend into sub-objects.
*
* Prerequisite: Disambiguator, Function Grouper
*/
class StackCompressor
{
public:
/// Try to remove local variables until the AST is compilable.
/// @returns tuple with true if it was successful as first element, second element is the modified AST.
static std::tuple<bool, Block> run(
Dialect const& _dialect,
Object const& _object,
bool _optimizeStackAllocation,
size_t _maxIterations
);
};
}
| 1,625
|
C++
|
.h
| 47
| 32.659574
| 104
| 0.784439
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,463
|
CommonSubexpressionEliminator.h
|
ethereum_solidity/libyul/optimiser/CommonSubexpressionEliminator.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimisation stage that replaces expressions known to be the current value of a variable
* in scope by a reference to that variable.
*/
#pragma once
#include <libyul/optimiser/DataFlowAnalyzer.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/SyntacticalEquality.h>
#include <libyul/optimiser/BlockHasher.h>
#include <set>
namespace solidity::yul
{
struct Dialect;
struct SideEffects;
/**
* Optimisation stage that replaces expressions known to be the current value of a variable
* in scope by a reference to that variable.
*
* Prerequisite: Disambiguator, ForLoopInitRewriter.
*/
class CommonSubexpressionEliminator: public DataFlowAnalyzer
{
public:
static constexpr char const* name{"CommonSubexpressionEliminator"};
static void run(OptimiserStepContext&, Block& _ast);
using DataFlowAnalyzer::operator();
void operator()(FunctionDefinition&) override;
private:
CommonSubexpressionEliminator(
Dialect const& _dialect,
std::map<YulName, SideEffects> _functionSideEffects
);
protected:
using ASTModifier::visit;
void visit(Expression& _e) override;
void assignValue(YulName _variable, Expression const* _value) override;
private:
std::set<YulName> m_returnVariables;
std::unordered_map<
std::reference_wrapper<Expression const>,
std::set<YulName>,
ExpressionHash,
SyntacticallyEqualExpression
> m_replacementCandidates;
};
}
| 2,085
|
C++
|
.h
| 60
| 32.783333
| 91
| 0.801493
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,465
|
NameDispenser.h
|
ethereum_solidity/libyul/optimiser/NameDispenser.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that can create new unique names.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/YulName.h>
#include <set>
namespace solidity::yul
{
struct Dialect;
/**
* Optimizer component that can be used to generate new names that
* do not conflict with existing names.
*
* Tries to keep names short and appends decimals to disambiguate.
*/
class NameDispenser
{
public:
/// Initialize the name dispenser with all the names used in the given AST.
explicit NameDispenser(Dialect const& _dialect, Block const& _ast, std::set<YulName> _reservedNames = {});
/// Initialize the name dispenser with the given used names.
explicit NameDispenser(Dialect const& _dialect, std::set<YulName> _usedNames);
/// @returns a currently unused name that should be similar to _nameHint.
YulName newName(YulName _nameHint);
/// Mark @a _name as used, i.e. the dispenser's newName function will not
/// return it.
void markUsed(YulName _name) { m_usedNames.insert(_name); }
std::set<YulName> const& usedNames() { return m_usedNames; }
/// Returns true if `_name` is either used or is a restricted identifier.
bool illegalName(YulName _name);
/// Resets `m_usedNames` with *only* the names that are used in the AST. Also resets value of
/// `m_counter` to zero.
void reset(Block const& _ast);
private:
Dialect const& m_dialect;
std::set<YulName> m_usedNames;
std::set<YulName> m_reservedNames;
size_t m_counter = 0;
};
}
| 2,153
|
C++
|
.h
| 55
| 37.2
| 107
| 0.759482
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,471
|
DataFlowAnalyzer.h
|
ethereum_solidity/libyul/optimiser/DataFlowAnalyzer.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Base class to perform data flow analysis during AST walks.
* Tracks assignments and is used as base class for both Rematerialiser and
* Common Subexpression Eliminator.
*/
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/KnowledgeBase.h>
#include <libyul/YulName.h>
#include <libyul/AST.h> // Needed for m_zero below.
#include <libyul/SideEffects.h>
#include <libsolutil/Numeric.h>
#include <libsolutil/Common.h>
#include <map>
#include <set>
namespace solidity::yul
{
struct Dialect;
struct SideEffects;
class KnowledgeBase;
/// Value assigned to a variable.
struct AssignedValue
{
Expression const* value{nullptr};
/// Loop nesting depth of the definition of the variable.
size_t loopDepth{0};
};
/**
* Base class to perform data flow analysis during AST walks.
* Tracks assignments and is used as base class for both Rematerialiser and
* Common Subexpression Eliminator.
*
* A special zero constant expression is used for the default value of variables.
*
* The class also tracks contents in storage and memory. Both keys and values
* are names of variables. Whenever such a variable is re-assigned, the knowledge
* is cleared.
*
* For elementary statements, we check if it is an SSTORE(x, y) / MSTORE(x, y)
* If yes, visit the statement. Then record that fact and clear all storage slots t
* where we cannot prove x != t or y == m_storage[t] using the current values of the variables x and t.
* Otherwise, determine if the statement invalidates storage/memory. If yes, clear all knowledge
* about storage/memory before visiting the statement. Then visit the statement.
*
* For forward-joining control flow, storage/memory information from the branches is combined.
* If the keys or values are different or non-existent in one branch, the key is deleted.
* This works also for memory (where addresses overlap) because one branch is always an
* older version of the other and thus overlapping contents would have been deleted already
* at the point of assignment.
*
* The DataFlowAnalyzer currently does not deal with the ``leave`` statement. This is because
* it only matters at the end of a function body, which is a point in the code a derived class
* can not easily deal with.
*
* Prerequisite: Disambiguator, ForLoopInitRewriter.
*/
class DataFlowAnalyzer: public ASTModifier
{
public:
enum class MemoryAndStorage { Analyze, Ignore };
/// @param _functionSideEffects
/// Side-effects of user-defined functions. Worst-case side-effects are assumed
/// if this is not provided or the function is not found.
/// The parameter is mostly used to determine movability of expressions.
explicit DataFlowAnalyzer(
Dialect const& _dialect,
MemoryAndStorage _analyzeStores,
std::map<YulName, SideEffects> _functionSideEffects = {}
);
using ASTModifier::operator();
void operator()(ExpressionStatement& _statement) override;
void operator()(Assignment& _assignment) override;
void operator()(VariableDeclaration& _varDecl) override;
void operator()(If& _if) override;
void operator()(Switch& _switch) override;
void operator()(FunctionDefinition&) override;
void operator()(ForLoop&) override;
void operator()(Block& _block) override;
/// @returns the current value of the given variable, if known - always movable.
AssignedValue const* variableValue(YulName _variable) const { return util::valueOrNullptr(m_state.value, _variable); }
std::set<YulName> const* references(YulName _variable) const { return util::valueOrNullptr(m_state.references, _variable); }
std::map<YulName, AssignedValue> const& allValues() const { return m_state.value; }
std::optional<YulName> storageValue(YulName _key) const;
std::optional<YulName> memoryValue(YulName _key) const;
std::optional<YulName> keccakValue(YulName _start, YulName _length) const;
protected:
/// Registers the assignment.
void handleAssignment(std::set<YulName> const& _names, Expression* _value, bool _isDeclaration);
/// Creates a new inner scope.
void pushScope(bool _functionScope);
/// Removes the innermost scope and clears all variables in it.
void popScope();
/// Clears information about the values assigned to the given variables,
/// for example at points where control flow is merged.
void clearValues(std::set<YulName> _names);
virtual void assignValue(YulName _variable, Expression const* _value);
/// Clears knowledge about storage or memory if they may be modified inside the block.
void clearKnowledgeIfInvalidated(Block const& _block);
/// Clears knowledge about storage or memory if they may be modified inside the expression.
void clearKnowledgeIfInvalidated(Expression const& _expression);
/// Returns true iff the variable is in scope.
bool inScope(YulName _variableName) const;
/// Returns the literal value of the identifier, if it exists.
std::optional<u256> valueOfIdentifier(YulName const& _name) const;
enum class StoreLoadLocation {
Memory = 0,
Storage = 1,
Last = Storage
};
/// Checks if the statement is sstore(a, b) / mstore(a, b)
/// where a and b are variables and returns these variables in that case.
std::optional<std::pair<YulName, YulName>> isSimpleStore(
StoreLoadLocation _location,
ExpressionStatement const& _statement
) const;
/// Checks if the expression is sload(a) / mload(a)
/// where a is a variable and returns the variable in that case.
std::optional<YulName> isSimpleLoad(
StoreLoadLocation _location,
Expression const& _expression
) const;
/// Checks if the expression is keccak256(s, l)
/// where s and l are variables and returns these variables in that case.
std::optional<std::pair<YulName, YulName>> isKeccak(Expression const& _expression) const;
Dialect const& m_dialect;
/// Side-effects of user-defined functions. Worst-case side-effects are assumed
/// if this is not provided or the function is not found.
std::map<YulName, SideEffects> m_functionSideEffects;
private:
struct Environment
{
std::unordered_map<YulName, YulName> storage;
std::unordered_map<YulName, YulName> memory;
/// If keccak[s, l] = y then y := keccak256(s, l) occurs in the code.
std::map<std::pair<YulName, YulName>, YulName> keccak;
};
struct State
{
/// Current values of variables, always movable.
std::map<YulName, AssignedValue> value;
/// m_references[a].contains(b) <=> the current expression assigned to a references b
std::unordered_map<YulName, std::set<YulName>> references;
Environment environment;
};
/// Joins knowledge about storage and memory with an older point in the control-flow.
/// This only works if the current state is a direct successor of the older point,
/// i.e. `_olderState.storage` and `_olderState.memory` cannot have additional changes.
/// Does nothing if memory and storage analysis is disabled / ignored.
void joinKnowledge(Environment const& _olderEnvironment);
static void joinKnowledgeHelper(
std::unordered_map<YulName, YulName>& _thisData,
std::unordered_map<YulName, YulName> const& _olderData
);
State m_state;
protected:
KnowledgeBase m_knowledgeBase;
/// If true, analyzes memory and storage content via mload/mstore and sload/sstore.
bool m_analyzeStores = true;
YulName m_storeFunctionName[static_cast<unsigned>(StoreLoadLocation::Last) + 1];
YulName m_loadFunctionName[static_cast<unsigned>(StoreLoadLocation::Last) + 1];
/// Current nesting depth of loops.
size_t m_loopDepth{0};
struct Scope
{
explicit Scope(bool _isFunction): isFunction(_isFunction) {}
std::set<YulName> variables;
bool isFunction;
};
/// Special expression whose address will be used in m_value.
/// YulName does not need to be reset because DataFlowAnalyzer is short-lived.
Expression const m_zero{Literal{{}, LiteralKind::Number, LiteralValue{0, std::nullopt}}};
/// List of scopes.
std::vector<Scope> m_variableScopes;
};
}
| 8,590
|
C++
|
.h
| 189
| 43.301587
| 125
| 0.766647
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,473
|
FunctionSpecializer.h
|
ethereum_solidity/libyul/optimiser/FunctionSpecializer.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/ASTForward.h>
#include <libyul/Dialect.h>
#include <map>
#include <optional>
#include <vector>
namespace solidity::yul
{
/**
* FunctionSpecializer: Optimiser step that specializes the function with its literal arguments.
*
* If a function, say, `function f(a, b) { sstore (a, b)}`, is called with literal arguments, for
* example, `f(x, 5)`, where `x` is an identifier, it could be specialized by creating a new
* function `f_1` that takes only one argument, i.e.,
*
* function f_1(a_1) {
* let b_1 := 5
* sstore(a_1, b_1)
* }
*
* Other optimization steps will be able to make more simplifications to the function. The
* optimization step is mainly useful for functions that would not be inlined.
*
* Prerequisites: Disambiguator, FunctionHoister
*
* LiteralRematerialiser is recommended as a prerequisite, even though it's not required for
* correctness.
*/
class FunctionSpecializer: public ASTModifier
{
public:
/// A vector of function-call arguments. An element 'has value' if it's a literal, and the
/// corresponding Expression would be the literal.
using LiteralArguments = std::vector<std::optional<Expression>>;
static constexpr char const* name{"FunctionSpecializer"};
static void run(OptimiserStepContext& _context, Block& _ast);
using ASTModifier::operator();
void operator()(FunctionCall& _f) override;
private:
explicit FunctionSpecializer(
std::set<YulName> _recursiveFunctions,
NameDispenser& _nameDispenser,
Dialect const& _dialect
):
m_recursiveFunctions(std::move(_recursiveFunctions)),
m_nameDispenser(_nameDispenser),
m_dialect(_dialect)
{}
/// Returns a vector of Expressions, where the index `i` is an expression if the function's
/// `i`-th argument can be specialized, nullopt otherwise.
LiteralArguments specializableArguments(FunctionCall const& _f);
/// Given a function definition `_f` and its arguments `_arguments`, of which, at least one is a
/// literal, this function returns a new function with the literal arguments specialized.
///
/// Note that the returned function definition will have new (and unique) names, for both the
/// function and variable declarations to retain the properties enforced by the Disambiguator.
///
/// For example, if `_f` is the function `function f(a, b, c) -> d { sstore(a, b) }`,
/// `_arguments` is the vector of literals `{1, 2, nullopt}` and the @param, `_newName` has
/// value `f_1`, the returned function could be:
///
/// function f_1(c_2) -> d_3 {
/// let a_4 := 1
/// let b_5 := 2
/// sstore(a_4, b_5)
/// }
///
FunctionDefinition specialize(
FunctionDefinition const& _f,
YulName _newName,
FunctionSpecializer::LiteralArguments _arguments
);
/// A mapping between the old function name and a pair of new function name and its arguments.
/// Note that at least one of the argument will have a literal value.
std::map<YulName, std::vector<std::pair<YulName, LiteralArguments>>> m_oldToNewMap;
/// We skip specializing recursive functions. Need backtracking to properly deal with them.
std::set<YulName> const m_recursiveFunctions;
NameDispenser& m_nameDispenser;
Dialect const& m_dialect;
};
}
| 4,029
|
C++
|
.h
| 98
| 39.081633
| 97
| 0.746936
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,475
|
CallGraphGenerator.h
|
ethereum_solidity/libyul/optimiser/CallGraphGenerator.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Specific AST walker that generates the call graph.
*/
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <map>
#include <optional>
#include <set>
namespace solidity::yul
{
struct CallGraph
{
std::map<YulName, std::vector<YulName>> functionCalls;
std::set<YulName> functionsWithLoops;
/// @returns the set of functions contained in cycles in the call graph, i.e.
/// functions that are part of a (mutual) recursion.
/// Note that this does not include functions that merely call recursive functions.
std::set<YulName> recursiveFunctions() const;
};
/**
* Specific AST walker that generates the call graph.
*
* It also generates information about which functions contain for loops.
*
* The outermost (non-function) context is denoted by the empty string.
*/
class CallGraphGenerator: public ASTWalker
{
public:
static CallGraph callGraph(Block const& _ast);
using ASTWalker::operator();
void operator()(FunctionCall const& _functionCall) override;
void operator()(ForLoop const& _forLoop) override;
void operator()(FunctionDefinition const& _functionDefinition) override;
private:
CallGraphGenerator();
CallGraph m_callGraph;
/// The name of the function we are currently visiting during traversal.
YulName m_currentFunction;
};
}
| 1,964
|
C++
|
.h
| 55
| 33.854545
| 84
| 0.783228
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,478
|
UnusedStoreEliminator.h
|
ethereum_solidity/libyul/optimiser/UnusedStoreEliminator.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that removes stores to memory and storage slots that are not used
* or overwritten later on.
*/
#pragma once
#include <libyul/ASTForward.h>
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/UnusedStoreBase.h>
#include <libyul/optimiser/KnowledgeBase.h>
#include <libevmasm/SemanticInformation.h>
#include <map>
#include <vector>
namespace solidity::yul
{
struct Dialect;
struct AssignedValue;
/**
* Optimizer component that removes sstore and memory store statements if conditions are met for their removal.
* In case of an sstore, if all outgoing code paths revert (due to an explicit revert(), invalid(),
* or infinite recursion) or lead to another ``sstore`` for which the optimizer can tell that it will overwrite the first store,
* the statement will be removed.
*
* For memory store operations, things are generally simpler, at least in the outermost yul block as all such statements
* will be removed if they are never read from in any code path. At function analysis level however, the approach is similar
* to sstore, as we don't know whether the memory location will be read once we leave the function's scope,
* so the statement will be removed only if all code code paths lead to a memory overwrite.
*
* Best run in SSA form.
*
* Prerequisite: Disambiguator, ForLoopInitRewriter.
*/
class UnusedStoreEliminator: public UnusedStoreBase<UnusedStoreEliminatorKey>
{
public:
static constexpr char const* name{"UnusedStoreEliminator"};
static void run(OptimiserStepContext& _context, Block& _ast);
explicit UnusedStoreEliminator(
Dialect const& _dialect,
std::map<YulName, SideEffects> const& _functionSideEffects,
std::map<YulName, ControlFlowSideEffects> _controlFlowSideEffects,
std::map<YulName, AssignedValue> const& _ssaValues,
bool _ignoreMemory
);
using UnusedStoreBase::operator();
void operator()(FunctionCall const& _functionCall) override;
void operator()(FunctionDefinition const&) override;
void operator()(Leave const&) override;
using UnusedStoreBase::visit;
void visit(Statement const& _statement) override;
using Location = evmasm::SemanticInformation::Location;
using Effect = evmasm::SemanticInformation::Effect;
using OperationLength = std::variant<YulName, u256>;
struct Operation
{
Location location;
Effect effect;
/// Start of affected area. Unknown if not provided.
std::optional<YulName> start;
/// Length of affected area, unknown if not provided.
/// Unused for storage.
std::optional<OperationLength> length;
};
private:
std::set<Statement const*>& activeMemoryStores() { return m_activeStores[UnusedStoreEliminatorKey::Memory]; }
std::set<Statement const*>& activeStorageStores() { return m_activeStores[UnusedStoreEliminatorKey::Storage]; }
std::optional<u256> lengthValue(OperationLength const& _length) const
{
if (YulName const* length = std::get_if<YulName>(&_length))
return m_knowledgeBase.valueIfKnownConstant(*length);
else
return std::get<u256>(_length);
}
void shortcutNestedLoop(ActiveStores const&) override
{
// We might only need to do this for newly introduced stores in the loop.
markActiveAsUsed();
}
void finalizeFunctionDefinition(FunctionDefinition const&) override
{
markActiveAsUsed();
}
std::vector<Operation> operationsFromFunctionCall(FunctionCall const& _functionCall) const;
void applyOperation(Operation const& _operation);
bool knownUnrelated(Operation const& _op1, Operation const& _op2) const;
bool knownCovered(Operation const& _covered, Operation const& _covering) const;
void markActiveAsUsed(std::optional<Location> _onlyLocation = std::nullopt);
void clearActive(std::optional<Location> _onlyLocation = std::nullopt);
std::optional<YulName> identifierNameIfSSA(Expression const& _expression) const;
bool const m_ignoreMemory;
std::map<YulName, SideEffects> const& m_functionSideEffects;
std::map<YulName, ControlFlowSideEffects> m_controlFlowSideEffects;
std::map<YulName, AssignedValue> const& m_ssaValues;
std::map<Statement const*, Operation> m_storeOperations;
KnowledgeBase mutable m_knowledgeBase;
};
}
| 4,912
|
C++
|
.h
| 112
| 41.696429
| 128
| 0.790289
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,479
|
UnusedStoreBase.h
|
ethereum_solidity/libyul/optimiser/UnusedStoreBase.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Base class for both UnusedAssignEliminator and UnusedStoreEliminator.
*/
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/AST.h>
#include <range/v3/action/remove_if.hpp>
#include <variant>
namespace solidity::yul
{
struct Dialect;
/**
* Base class for both UnusedAssignEliminator and UnusedStoreEliminator.
*
* The class tracks the state of abstract "stores" (assignments or mstore/sstore
* statements) across the control-flow. It is the job of the derived class to create
* the stores and track references, but the base class manages control-flow splits and joins.
*
* In general, active stores are those where it has not yet been determined if they are used
* or not. Those are split and joined at control-flow forks. Once a store has been deemed
* used, it is removed from the active set and marked as used and this will never change.
*
* Prerequisite: Disambiguator, ForLoopInitRewriter.
*/
template<typename ActiveStoreKeyType>
class UnusedStoreBase: public ASTWalker
{
public:
explicit UnusedStoreBase(Dialect const& _dialect): m_dialect(_dialect) {}
using ASTWalker::operator();
void operator()(If const& _if) override;
void operator()(Switch const& _switch) override;
void operator()(FunctionDefinition const&) override;
void operator()(ForLoop const&) override;
void operator()(Break const&) override;
void operator()(Continue const&) override;
protected:
using ActiveStores = std::map<ActiveStoreKeyType, std::set<Statement const*>>;
/// This function is called for a loop that is nested too deep to avoid
/// horrible runtime and should just resolve the situation in a pragmatic
/// and correct manner.
virtual void shortcutNestedLoop(ActiveStores const& _beforeLoop) = 0;
/// This function is called right before the scoped restore of the function definition.
virtual void finalizeFunctionDefinition(FunctionDefinition const& /*_functionDefinition*/) {}
/// Joins the assignment mapping of @a _source into @a _target according to the rules laid out
/// above.
/// Will destroy @a _source.
static void merge(ActiveStores& _target, ActiveStores&& _source);
static void merge(ActiveStores& _target, std::vector<ActiveStores>&& _source);
Dialect const& m_dialect;
/// Set of all stores encountered during the traversal (in the current function).
std::set<Statement const*> m_allStores;
/// Set of stores that are marked as being used (in the current function).
std::set<Statement const*> m_usedStores;
/// List of stores that can be removed (globally).
std::vector<Statement const*> m_storesToRemove;
/// Active (undecided) stores in the current branch.
ActiveStores m_activeStores;
/// Working data for traversing for-loops.
struct ForLoopInfo
{
/// Tracked assignment states for each break statement.
std::vector<ActiveStores> pendingBreakStmts;
/// Tracked assignment states for each continue statement.
std::vector<ActiveStores> pendingContinueStmts;
};
ForLoopInfo m_forLoopInfo;
size_t m_forLoopNestingDepth = 0;
};
enum class UnusedStoreEliminatorKey { Memory, Storage };
extern template class UnusedStoreBase<YulString>;
extern template class UnusedStoreBase<UnusedStoreEliminatorKey>;
}
| 3,888
|
C++
|
.h
| 87
| 42.701149
| 95
| 0.782712
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,483
|
OptimizerUtilities.h
|
ethereum_solidity/libyul/optimiser/OptimizerUtilities.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Small useful snippets for the optimiser.
*/
#pragma once
#include <libsolutil/Common.h>
#include <libyul/ASTForward.h>
#include <libyul/Dialect.h>
#include <libyul/YulName.h>
#include <libyul/optimiser/ASTWalker.h>
#include <liblangutil/EVMVersion.h>
#include <optional>
namespace solidity::evmasm
{
enum class Instruction: uint8_t;
}
namespace solidity::yul
{
/// Removes statements that are just empty blocks (non-recursive).
/// If this is run on the outermost block, the FunctionGrouper should be run afterwards to keep
/// the canonical form.
void removeEmptyBlocks(Block& _block);
/// Returns true if a given literal can not be used as an identifier.
/// This includes Yul keywords and builtins of the given dialect.
bool isRestrictedIdentifier(Dialect const& _dialect, YulName const& _identifier);
/// Helper function that returns the instruction, if the `_name` is a BuiltinFunction
std::optional<evmasm::Instruction> toEVMInstruction(Dialect const& _dialect, YulName const& _name);
/// Helper function that returns the EVM version from a dialect.
/// It returns the default EVM version if dialect is not an EVMDialect.
langutil::EVMVersion const evmVersionFromDialect(Dialect const& _dialect);
class StatementRemover: public ASTModifier
{
public:
explicit StatementRemover(std::set<Statement const*> const& _toRemove): m_toRemove(_toRemove) {}
void operator()(Block& _block) override;
private:
std::set<Statement const*> const& m_toRemove;
};
}
| 2,162
|
C++
|
.h
| 52
| 39.980769
| 99
| 0.788067
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,484
|
LoadResolver.h
|
ethereum_solidity/libyul/optimiser/LoadResolver.h
|
/*
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 <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimisation stage that replaces expressions of type ``sload(x)`` by the value
* currently stored in storage, if known.
*/
#pragma once
#include <libyul/optimiser/DataFlowAnalyzer.h>
#include <libyul/optimiser/OptimiserStep.h>
namespace solidity::yul
{
/**
* Optimisation stage that replaces expressions of type ``sload(x)`` and ``mload(x)`` by the value
* currently stored in storage resp. memory, if known.
*
* Also evaluates simple ``keccak256(a, c)`` when the value at memory location `a` is known and `c`
* is a constant `<= 32`.
*
* Works best if the code is in SSA form.
*
* Prerequisite: Disambiguator, ForLoopInitRewriter.
*/
class LoadResolver: public DataFlowAnalyzer
{
public:
static constexpr char const* name{"LoadResolver"};
/// Run the load resolver on the given complete AST.
static void run(OptimiserStepContext&, Block& _ast);
private:
LoadResolver(
Dialect const& _dialect,
std::map<YulName, SideEffects> _functionSideEffects,
bool _containsMSize,
std::optional<size_t> _expectedExecutionsPerDeployment
):
DataFlowAnalyzer(_dialect, MemoryAndStorage::Analyze, std::move(_functionSideEffects)),
m_containsMSize(_containsMSize),
m_expectedExecutionsPerDeployment(std::move(_expectedExecutionsPerDeployment))
{}
protected:
using ASTModifier::visit;
void visit(Expression& _e) override;
void tryResolve(
Expression& _e,
StoreLoadLocation _location,
std::vector<Expression> const& _arguments
);
/// Evaluates simple ``keccak256(a, c)`` when the value at memory location ``a`` is known and
/// `c` is a constant `<= 32`.
void tryEvaluateKeccak(
Expression& _e,
std::vector<Expression> const& _arguments
);
/// If the AST contains `msize`, then we skip resolving `mload` and `keccak256`.
bool m_containsMSize = false;
/// The --optimize-runs parameter. Value `nullopt` represents creation code.
std::optional<size_t> m_expectedExecutionsPerDeployment;
};
}
| 2,626
|
C++
|
.h
| 71
| 34.873239
| 99
| 0.764359
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.