From 10e6d2897d09511ca3253287694a28d05fa6b9e0 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 23 Nov 2018 11:16:52 +0100 Subject: Moving files from libsolidity/inlineasm/*.{cpp,h} to libyul/. --- libsolidity/inlineasm/AsmAnalysis.cpp | 631 ------------------------------ libsolidity/inlineasm/AsmAnalysis.h | 128 ------ libsolidity/inlineasm/AsmAnalysisInfo.cpp | 26 -- libsolidity/inlineasm/AsmAnalysisInfo.h | 52 --- libsolidity/inlineasm/AsmCodeGen.cpp | 162 -------- libsolidity/inlineasm/AsmCodeGen.h | 56 --- libsolidity/inlineasm/AsmData.h | 104 ----- libsolidity/inlineasm/AsmDataForward.h | 65 --- libsolidity/inlineasm/AsmParser.cpp | 617 ----------------------------- libsolidity/inlineasm/AsmParser.h | 95 ----- libsolidity/inlineasm/AsmPrinter.cpp | 250 ------------ libsolidity/inlineasm/AsmPrinter.h | 68 ---- libsolidity/inlineasm/AsmScope.cpp | 98 ----- libsolidity/inlineasm/AsmScope.h | 105 ----- libsolidity/inlineasm/AsmScopeFiller.cpp | 181 --------- libsolidity/inlineasm/AsmScopeFiller.h | 88 ----- libyul/AsmAnalysis.cpp | 631 ++++++++++++++++++++++++++++++ libyul/AsmAnalysis.h | 128 ++++++ libyul/AsmAnalysisInfo.cpp | 26 ++ libyul/AsmAnalysisInfo.h | 52 +++ libyul/AsmCodeGen.cpp | 162 ++++++++ libyul/AsmCodeGen.h | 56 +++ libyul/AsmData.h | 104 +++++ libyul/AsmDataForward.h | 65 +++ libyul/AsmParser.cpp | 617 +++++++++++++++++++++++++++++ libyul/AsmParser.h | 95 +++++ libyul/AsmPrinter.cpp | 250 ++++++++++++ libyul/AsmPrinter.h | 68 ++++ libyul/AsmScope.cpp | 98 +++++ libyul/AsmScope.h | 105 +++++ libyul/AsmScopeFiller.cpp | 181 +++++++++ libyul/AsmScopeFiller.h | 88 +++++ 32 files changed, 2726 insertions(+), 2726 deletions(-) delete mode 100644 libsolidity/inlineasm/AsmAnalysis.cpp delete mode 100644 libsolidity/inlineasm/AsmAnalysis.h delete mode 100644 libsolidity/inlineasm/AsmAnalysisInfo.cpp delete mode 100644 libsolidity/inlineasm/AsmAnalysisInfo.h delete mode 100644 libsolidity/inlineasm/AsmCodeGen.cpp delete mode 100644 libsolidity/inlineasm/AsmCodeGen.h delete mode 100644 libsolidity/inlineasm/AsmData.h delete mode 100644 libsolidity/inlineasm/AsmDataForward.h delete mode 100644 libsolidity/inlineasm/AsmParser.cpp delete mode 100644 libsolidity/inlineasm/AsmParser.h delete mode 100644 libsolidity/inlineasm/AsmPrinter.cpp delete mode 100644 libsolidity/inlineasm/AsmPrinter.h delete mode 100644 libsolidity/inlineasm/AsmScope.cpp delete mode 100644 libsolidity/inlineasm/AsmScope.h delete mode 100644 libsolidity/inlineasm/AsmScopeFiller.cpp delete mode 100644 libsolidity/inlineasm/AsmScopeFiller.h create mode 100644 libyul/AsmAnalysis.cpp create mode 100644 libyul/AsmAnalysis.h create mode 100644 libyul/AsmAnalysisInfo.cpp create mode 100644 libyul/AsmAnalysisInfo.h create mode 100644 libyul/AsmCodeGen.cpp create mode 100644 libyul/AsmCodeGen.h create mode 100644 libyul/AsmData.h create mode 100644 libyul/AsmDataForward.h create mode 100644 libyul/AsmParser.cpp create mode 100644 libyul/AsmParser.h create mode 100644 libyul/AsmPrinter.cpp create mode 100644 libyul/AsmPrinter.h create mode 100644 libyul/AsmScope.cpp create mode 100644 libyul/AsmScope.h create mode 100644 libyul/AsmScopeFiller.cpp create mode 100644 libyul/AsmScopeFiller.h diff --git a/libsolidity/inlineasm/AsmAnalysis.cpp b/libsolidity/inlineasm/AsmAnalysis.cpp deleted file mode 100644 index fb96f73c..00000000 --- a/libsolidity/inlineasm/AsmAnalysis.cpp +++ /dev/null @@ -1,631 +0,0 @@ -/* - 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 . -*/ -/** - * Analyzer part of inline assembly. - */ - -#include - -#include -#include -#include -#include - -#include - -#include -#include - -#include -#include - -using namespace std; -using namespace dev; -using namespace langutil; -using namespace dev::solidity; -using namespace dev::solidity::assembly; - -namespace { - -set const builtinTypes{"bool", "u8", "s8", "u32", "s32", "u64", "s64", "u128", "s128", "u256", "s256"}; - -} - -bool AsmAnalyzer::analyze(Block const& _block) -{ - if (!(ScopeFiller(m_info, m_errorReporter))(_block)) - return false; - - return (*this)(_block); -} - -bool AsmAnalyzer::operator()(Label const& _label) -{ - solAssert(!_label.name.empty(), ""); - checkLooseFeature( - _label.location, - "The use of labels is disallowed. Please use \"if\", \"switch\", \"for\" or function calls instead." - ); - m_info.stackHeightInfo[&_label] = m_stackHeight; - warnOnInstructions(solidity::Instruction::JUMPDEST, _label.location); - return true; -} - -bool AsmAnalyzer::operator()(assembly::Instruction const& _instruction) -{ - checkLooseFeature( - _instruction.location, - "The use of non-functional instructions is disallowed. Please use functional notation instead." - ); - auto const& info = instructionInfo(_instruction.instruction); - m_stackHeight += info.ret - info.args; - m_info.stackHeightInfo[&_instruction] = m_stackHeight; - warnOnInstructions(_instruction.instruction, _instruction.location); - return true; -} - -bool AsmAnalyzer::operator()(assembly::Literal const& _literal) -{ - expectValidType(_literal.type.str(), _literal.location); - ++m_stackHeight; - if (_literal.kind == assembly::LiteralKind::String && _literal.value.str().size() > 32) - { - m_errorReporter.typeError( - _literal.location, - "String literal too long (" + to_string(_literal.value.str().size()) + " > 32)" - ); - return false; - } - else if (_literal.kind == assembly::LiteralKind::Number && bigint(_literal.value.str()) > u256(-1)) - { - m_errorReporter.typeError( - _literal.location, - "Number literal too large (> 256 bits)" - ); - return false; - } - else if (_literal.kind == assembly::LiteralKind::Boolean) - { - solAssert(m_flavour == AsmFlavour::Yul, ""); - solAssert(_literal.value == YulString{string("true")} || _literal.value == YulString{string("false")}, ""); - } - m_info.stackHeightInfo[&_literal] = m_stackHeight; - return true; -} - -bool AsmAnalyzer::operator()(assembly::Identifier const& _identifier) -{ - solAssert(!_identifier.name.empty(), ""); - size_t numErrorsBefore = m_errorReporter.errors().size(); - bool success = true; - if (m_currentScope->lookup(_identifier.name, Scope::Visitor( - [&](Scope::Variable const& _var) - { - if (!m_activeVariables.count(&_var)) - { - m_errorReporter.declarationError( - _identifier.location, - "Variable " + _identifier.name.str() + " used before it was declared." - ); - success = false; - } - ++m_stackHeight; - }, - [&](Scope::Label const&) - { - ++m_stackHeight; - }, - [&](Scope::Function const&) - { - m_errorReporter.typeError( - _identifier.location, - "Function " + _identifier.name.str() + " used without being called." - ); - success = false; - } - ))) - { - } - else - { - size_t stackSize(-1); - if (m_resolver) - { - bool insideFunction = m_currentScope->insideFunction(); - stackSize = m_resolver(_identifier, yul::IdentifierContext::RValue, insideFunction); - } - if (stackSize == size_t(-1)) - { - // Only add an error message if the callback did not do it. - if (numErrorsBefore == m_errorReporter.errors().size()) - m_errorReporter.declarationError(_identifier.location, "Identifier not found."); - success = false; - } - m_stackHeight += stackSize == size_t(-1) ? 1 : stackSize; - } - m_info.stackHeightInfo[&_identifier] = m_stackHeight; - return success; -} - -bool AsmAnalyzer::operator()(FunctionalInstruction const& _instr) -{ - solAssert(m_flavour != AsmFlavour::Yul, ""); - bool success = true; - for (auto const& arg: _instr.arguments | boost::adaptors::reversed) - if (!expectExpression(arg)) - success = false; - // Parser already checks that the number of arguments is correct. - auto const& info = instructionInfo(_instr.instruction); - solAssert(info.args == int(_instr.arguments.size()), ""); - m_stackHeight += info.ret - info.args; - m_info.stackHeightInfo[&_instr] = m_stackHeight; - warnOnInstructions(_instr.instruction, _instr.location); - return success; -} - -bool AsmAnalyzer::operator()(assembly::ExpressionStatement const& _statement) -{ - int initialStackHeight = m_stackHeight; - bool success = boost::apply_visitor(*this, _statement.expression); - if (m_stackHeight != initialStackHeight && (m_flavour != AsmFlavour::Loose || m_errorTypeForLoose)) - { - Error::Type errorType = m_flavour == AsmFlavour::Loose ? *m_errorTypeForLoose : Error::Type::TypeError; - string msg = - "Top-level expressions are not supposed to return values (this expression returns " + - to_string(m_stackHeight - initialStackHeight) + - " value" + - (m_stackHeight - initialStackHeight == 1 ? "" : "s") + - "). Use ``pop()`` or assign them."; - m_errorReporter.error(errorType, _statement.location, msg); - if (errorType != Error::Type::Warning) - success = false; - } - m_info.stackHeightInfo[&_statement] = m_stackHeight; - return success; -} - -bool AsmAnalyzer::operator()(assembly::StackAssignment const& _assignment) -{ - checkLooseFeature( - _assignment.location, - "The use of stack assignment is disallowed. Please use assignment in functional notation instead." - ); - bool success = checkAssignment(_assignment.variableName, size_t(-1)); - m_info.stackHeightInfo[&_assignment] = m_stackHeight; - return success; -} - -bool AsmAnalyzer::operator()(assembly::Assignment const& _assignment) -{ - solAssert(_assignment.value, ""); - int const expectedItems = _assignment.variableNames.size(); - solAssert(expectedItems >= 1, ""); - int const stackHeight = m_stackHeight; - bool success = boost::apply_visitor(*this, *_assignment.value); - if ((m_stackHeight - stackHeight) != expectedItems) - { - m_errorReporter.declarationError( - _assignment.location, - "Variable count does not match number of values (" + - to_string(expectedItems) + - " vs. " + - to_string(m_stackHeight - stackHeight) + - ")" - ); - return false; - } - for (auto const& variableName: _assignment.variableNames) - if (!checkAssignment(variableName, 1)) - success = false; - m_info.stackHeightInfo[&_assignment] = m_stackHeight; - return success; -} - -bool AsmAnalyzer::operator()(assembly::VariableDeclaration const& _varDecl) -{ - bool success = true; - int const numVariables = _varDecl.variables.size(); - if (_varDecl.value) - { - int const stackHeight = m_stackHeight; - success = boost::apply_visitor(*this, *_varDecl.value); - if ((m_stackHeight - stackHeight) != numVariables) - { - m_errorReporter.declarationError(_varDecl.location, "Variable count mismatch."); - return false; - } - } - else - m_stackHeight += numVariables; - - for (auto const& variable: _varDecl.variables) - { - expectValidType(variable.type.str(), variable.location); - m_activeVariables.insert(&boost::get(m_currentScope->identifiers.at(variable.name))); - } - m_info.stackHeightInfo[&_varDecl] = m_stackHeight; - return success; -} - -bool AsmAnalyzer::operator()(assembly::FunctionDefinition const& _funDef) -{ - solAssert(!_funDef.name.empty(), ""); - Block const* virtualBlock = m_info.virtualBlocks.at(&_funDef).get(); - solAssert(virtualBlock, ""); - Scope& varScope = scope(virtualBlock); - for (auto const& var: _funDef.parameters + _funDef.returnVariables) - { - expectValidType(var.type.str(), var.location); - m_activeVariables.insert(&boost::get(varScope.identifiers.at(var.name))); - } - - int const stackHeight = m_stackHeight; - m_stackHeight = _funDef.parameters.size() + _funDef.returnVariables.size(); - - bool success = (*this)(_funDef.body); - - m_stackHeight = stackHeight; - m_info.stackHeightInfo[&_funDef] = m_stackHeight; - return success; -} - -bool AsmAnalyzer::operator()(assembly::FunctionCall const& _funCall) -{ - solAssert(!_funCall.functionName.name.empty(), ""); - bool success = true; - size_t arguments = 0; - size_t returns = 0; - if (!m_currentScope->lookup(_funCall.functionName.name, Scope::Visitor( - [&](Scope::Variable const&) - { - m_errorReporter.typeError( - _funCall.functionName.location, - "Attempt to call variable instead of function." - ); - success = false; - }, - [&](Scope::Label const&) - { - m_errorReporter.typeError( - _funCall.functionName.location, - "Attempt to call label instead of function." - ); - success = false; - }, - [&](Scope::Function const& _fun) - { - /// TODO: compare types too - arguments = _fun.arguments.size(); - returns = _fun.returns.size(); - } - ))) - { - m_errorReporter.declarationError(_funCall.functionName.location, "Function not found."); - success = false; - } - if (success) - { - if (_funCall.arguments.size() != arguments) - { - m_errorReporter.typeError( - _funCall.functionName.location, - "Expected " + to_string(arguments) + " arguments but got " + - to_string(_funCall.arguments.size()) + "." - ); - success = false; - } - } - for (auto const& arg: _funCall.arguments | boost::adaptors::reversed) - if (!expectExpression(arg)) - success = false; - m_stackHeight += int(returns) - int(arguments); - m_info.stackHeightInfo[&_funCall] = m_stackHeight; - return success; -} - -bool AsmAnalyzer::operator()(If const& _if) -{ - bool success = true; - - if (!expectExpression(*_if.condition)) - success = false; - m_stackHeight--; - - if (!(*this)(_if.body)) - success = false; - - m_info.stackHeightInfo[&_if] = m_stackHeight; - - return success; -} - -bool AsmAnalyzer::operator()(Switch const& _switch) -{ - solAssert(_switch.expression, ""); - - bool success = true; - - if (!expectExpression(*_switch.expression)) - success = false; - - set> cases; - for (auto const& _case: _switch.cases) - { - if (_case.value) - { - int const initialStackHeight = m_stackHeight; - // We cannot use "expectExpression" here because *_case.value is not a - // Statement and would be converted to a Statement otherwise. - if (!(*this)(*_case.value)) - success = false; - expectDeposit(1, initialStackHeight, _case.value->location); - m_stackHeight--; - - /// Note: the parser ensures there is only one default case - auto val = make_tuple(_case.value->kind, _case.value->value); - if (!cases.insert(val).second) - { - m_errorReporter.declarationError( - _case.location, - "Duplicate case defined" - ); - success = false; - } - } - - if (!(*this)(_case.body)) - success = false; - } - - m_stackHeight--; - m_info.stackHeightInfo[&_switch] = m_stackHeight; - - return success; -} - -bool AsmAnalyzer::operator()(assembly::ForLoop const& _for) -{ - solAssert(_for.condition, ""); - - Scope* originalScope = m_currentScope; - - bool success = true; - if (!(*this)(_for.pre)) - success = false; - // The block was closed already, but we re-open it again and stuff the - // condition, the body and the post part inside. - m_stackHeight += scope(&_for.pre).numberOfVariables(); - m_currentScope = &scope(&_for.pre); - - if (!expectExpression(*_for.condition)) - success = false; - m_stackHeight--; - if (!(*this)(_for.body)) - success = false; - if (!(*this)(_for.post)) - success = false; - - m_stackHeight -= scope(&_for.pre).numberOfVariables(); - m_info.stackHeightInfo[&_for] = m_stackHeight; - m_currentScope = originalScope; - - return success; -} - -bool AsmAnalyzer::operator()(Block const& _block) -{ - bool success = true; - auto previousScope = m_currentScope; - m_currentScope = &scope(&_block); - - int const initialStackHeight = m_stackHeight; - - for (auto const& s: _block.statements) - if (!boost::apply_visitor(*this, s)) - success = false; - - m_stackHeight -= scope(&_block).numberOfVariables(); - - int const stackDiff = m_stackHeight - initialStackHeight; - if (stackDiff != 0) - { - m_errorReporter.declarationError( - _block.location, - "Unbalanced stack at the end of a block: " + - ( - stackDiff > 0 ? - to_string(stackDiff) + string(" surplus item(s).") : - to_string(-stackDiff) + string(" missing item(s).") - ) - ); - success = false; - } - - m_info.stackHeightInfo[&_block] = m_stackHeight; - m_currentScope = previousScope; - return success; -} - -bool AsmAnalyzer::expectExpression(Expression const& _expr) -{ - bool success = true; - int const initialHeight = m_stackHeight; - if (!boost::apply_visitor(*this, _expr)) - success = false; - if (!expectDeposit(1, initialHeight, locationOf(_expr))) - success = false; - return success; -} - -bool AsmAnalyzer::expectDeposit(int _deposit, int _oldHeight, SourceLocation const& _location) -{ - if (m_stackHeight - _oldHeight != _deposit) - { - m_errorReporter.typeError( - _location, - "Expected expression to return one item to the stack, but did return " + - to_string(m_stackHeight - _oldHeight) + - " items." - ); - return false; - } - return true; -} - -bool AsmAnalyzer::checkAssignment(assembly::Identifier const& _variable, size_t _valueSize) -{ - solAssert(!_variable.name.empty(), ""); - bool success = true; - size_t numErrorsBefore = m_errorReporter.errors().size(); - size_t variableSize(-1); - if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name)) - { - // Check that it is a variable - if (var->type() != typeid(Scope::Variable)) - { - m_errorReporter.typeError(_variable.location, "Assignment requires variable."); - success = false; - } - else if (!m_activeVariables.count(&boost::get(*var))) - { - m_errorReporter.declarationError( - _variable.location, - "Variable " + _variable.name.str() + " used before it was declared." - ); - success = false; - } - variableSize = 1; - } - else if (m_resolver) - { - bool insideFunction = m_currentScope->insideFunction(); - variableSize = m_resolver(_variable, yul::IdentifierContext::LValue, insideFunction); - } - if (variableSize == size_t(-1)) - { - // Only add message if the callback did not. - if (numErrorsBefore == m_errorReporter.errors().size()) - m_errorReporter.declarationError(_variable.location, "Variable not found or variable not lvalue."); - success = false; - } - if (_valueSize == size_t(-1)) - _valueSize = variableSize == size_t(-1) ? 1 : variableSize; - - m_stackHeight -= _valueSize; - - if (_valueSize != variableSize && variableSize != size_t(-1)) - { - m_errorReporter.typeError( - _variable.location, - "Variable size (" + - to_string(variableSize) + - ") and value size (" + - to_string(_valueSize) + - ") do not match." - ); - success = false; - } - return success; -} - -Scope& AsmAnalyzer::scope(Block const* _block) -{ - solAssert(m_info.scopes.count(_block) == 1, "Scope requested but not present."); - auto scopePtr = m_info.scopes.at(_block); - solAssert(scopePtr, "Scope requested but not present."); - return *scopePtr; -} -void AsmAnalyzer::expectValidType(string const& type, SourceLocation const& _location) -{ - if (m_flavour != AsmFlavour::Yul) - return; - - if (!builtinTypes.count(type)) - m_errorReporter.typeError( - _location, - "\"" + type + "\" is not a valid type (user defined types are not yet supported)." - ); -} - -void AsmAnalyzer::warnOnInstructions(solidity::Instruction _instr, SourceLocation const& _location) -{ - // We assume that returndatacopy, returndatasize and staticcall are either all available - // or all not available. - solAssert(m_evmVersion.supportsReturndata() == m_evmVersion.hasStaticCall(), ""); - // Similarly we assume bitwise shifting and create2 go together. - solAssert(m_evmVersion.hasBitwiseShifting() == m_evmVersion.hasCreate2(), ""); - - if (_instr == solidity::Instruction::EXTCODEHASH) - m_errorReporter.warning( - _location, - "The \"" + - boost::to_lower_copy(instructionInfo(_instr).name) - + "\" instruction is not supported by the VM version \"" + - "" + m_evmVersion.name() + - "\" you are currently compiling for. " + - "It will be interpreted as an invalid instruction on this VM." - ); - else if (( - _instr == solidity::Instruction::RETURNDATACOPY || - _instr == solidity::Instruction::RETURNDATASIZE || - _instr == solidity::Instruction::STATICCALL - ) && !m_evmVersion.supportsReturndata()) - m_errorReporter.warning( - _location, - "The \"" + - boost::to_lower_copy(instructionInfo(_instr).name) - + "\" instruction is only available for Byzantium-compatible VMs. " + - "You are currently compiling for \"" + - m_evmVersion.name() + - "\", where it will be interpreted as an invalid instruction." - ); - else if (( - _instr == solidity::Instruction::SHL || - _instr == solidity::Instruction::SHR || - _instr == solidity::Instruction::SAR || - _instr == solidity::Instruction::CREATE2 - ) && !m_evmVersion.hasBitwiseShifting()) - m_errorReporter.warning( - _location, - "The \"" + - boost::to_lower_copy(instructionInfo(_instr).name) - + "\" instruction is only available for Constantinople-compatible VMs. " + - "You are currently compiling for \"" + - m_evmVersion.name() + - "\", where it will be interpreted as an invalid instruction." - ); - - if (_instr == solidity::Instruction::JUMP || _instr == solidity::Instruction::JUMPI || _instr == solidity::Instruction::JUMPDEST) - { - solAssert(m_flavour == AsmFlavour::Loose, ""); - m_errorReporter.error( - m_errorTypeForLoose ? *m_errorTypeForLoose : Error::Type::Warning, - _location, - "Jump instructions and labels are low-level EVM features that can lead to " - "incorrect stack access. Because of that they are discouraged. " - "Please consider using \"switch\", \"if\" or \"for\" statements instead." - ); - } -} - -void AsmAnalyzer::checkLooseFeature(SourceLocation const& _location, string const& _description) -{ - if (m_flavour != AsmFlavour::Loose) - solAssert(false, _description); - else if (m_errorTypeForLoose) - m_errorReporter.error(*m_errorTypeForLoose, _location, _description); -} diff --git a/libsolidity/inlineasm/AsmAnalysis.h b/libsolidity/inlineasm/AsmAnalysis.h deleted file mode 100644 index 194f736e..00000000 --- a/libsolidity/inlineasm/AsmAnalysis.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - 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 . -*/ -/** - * Analysis part of inline assembly. - */ - -#pragma once - -#include -#include - -#include - -#include - -#include - -#include -#include - -#include -#include - -namespace langutil -{ -class ErrorReporter; -struct SourceLocation; -} - -namespace dev -{ -namespace solidity -{ -namespace assembly -{ - -struct AsmAnalysisInfo; - -/** - * Performs the full analysis stage, calls the ScopeFiller internally, then resolves - * references and performs other checks. - * If all these checks pass, code generation should not throw errors. - */ -class AsmAnalyzer: public boost::static_visitor -{ -public: - explicit AsmAnalyzer( - AsmAnalysisInfo& _analysisInfo, - langutil::ErrorReporter& _errorReporter, - EVMVersion _evmVersion, - boost::optional _errorTypeForLoose, - AsmFlavour _flavour = AsmFlavour::Loose, - yul::ExternalIdentifierAccess::Resolver const& _resolver = yul::ExternalIdentifierAccess::Resolver() - ): - m_resolver(_resolver), - m_info(_analysisInfo), - m_errorReporter(_errorReporter), - m_evmVersion(_evmVersion), - m_flavour(_flavour), - m_errorTypeForLoose(_errorTypeForLoose) - {} - - bool analyze(assembly::Block const& _block); - - bool operator()(assembly::Instruction const&); - bool operator()(assembly::Literal const& _literal); - bool operator()(assembly::Identifier const&); - bool operator()(assembly::FunctionalInstruction const& _functionalInstruction); - bool operator()(assembly::Label const& _label); - bool operator()(assembly::ExpressionStatement const&); - bool operator()(assembly::StackAssignment const&); - bool operator()(assembly::Assignment const& _assignment); - bool operator()(assembly::VariableDeclaration const& _variableDeclaration); - bool operator()(assembly::FunctionDefinition const& _functionDefinition); - bool operator()(assembly::FunctionCall const& _functionCall); - bool operator()(assembly::If const& _if); - bool operator()(assembly::Switch const& _switch); - bool operator()(assembly::ForLoop const& _forLoop); - bool operator()(assembly::Block const& _block); - -private: - /// Visits the statement and expects it to deposit one item onto the stack. - bool expectExpression(Expression const& _expr); - bool expectDeposit(int _deposit, int _oldHeight, langutil::SourceLocation const& _location); - - /// Verifies that a variable to be assigned to exists and has the same size - /// as the value, @a _valueSize, unless that is equal to -1. - bool checkAssignment(assembly::Identifier const& _assignment, size_t _valueSize = size_t(-1)); - - Scope& scope(assembly::Block const* _block); - void expectValidType(std::string const& type, langutil::SourceLocation const& _location); - void warnOnInstructions(solidity::Instruction _instr, langutil::SourceLocation const& _location); - - /// Depending on @a m_flavour and @a m_errorTypeForLoose, throws an internal compiler - /// exception (if the flavour is not Loose), reports an error/warning - /// (if m_errorTypeForLoose is set) or does nothing. - void checkLooseFeature(langutil::SourceLocation const& _location, std::string const& _description); - - int m_stackHeight = 0; - yul::ExternalIdentifierAccess::Resolver m_resolver; - Scope* m_currentScope = nullptr; - /// Variables that are active at the current point in assembly (as opposed to - /// "part of the scope but not yet declared") - std::set m_activeVariables; - AsmAnalysisInfo& m_info; - langutil::ErrorReporter& m_errorReporter; - EVMVersion m_evmVersion; - AsmFlavour m_flavour = AsmFlavour::Loose; - boost::optional m_errorTypeForLoose; -}; - -} -} -} diff --git a/libsolidity/inlineasm/AsmAnalysisInfo.cpp b/libsolidity/inlineasm/AsmAnalysisInfo.cpp deleted file mode 100644 index 22318b12..00000000 --- a/libsolidity/inlineasm/AsmAnalysisInfo.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - 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 . -*/ -/** - * Information generated during analyzer part of inline assembly. - */ - -#include - -#include - -#include - diff --git a/libsolidity/inlineasm/AsmAnalysisInfo.h b/libsolidity/inlineasm/AsmAnalysisInfo.h deleted file mode 100644 index bd3b28c4..00000000 --- a/libsolidity/inlineasm/AsmAnalysisInfo.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - 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 . -*/ -/** - * Information generated during analyzer part of inline assembly. - */ - -#pragma once - -#include - -#include - -#include -#include -#include - -namespace dev -{ -namespace solidity -{ -namespace assembly -{ - -struct Scope; - -struct AsmAnalysisInfo -{ - using StackHeightInfo = std::map; - using Scopes = std::map>; - Scopes scopes; - StackHeightInfo stackHeightInfo; - /// Virtual blocks which will be used for scopes for function arguments and return values. - std::map> virtualBlocks; -}; - -} -} -} diff --git a/libsolidity/inlineasm/AsmCodeGen.cpp b/libsolidity/inlineasm/AsmCodeGen.cpp deleted file mode 100644 index 2800cc7b..00000000 --- a/libsolidity/inlineasm/AsmCodeGen.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* - 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 . -*/ -/** - * @author Christian - * @date 2016 - * Code-generating part of inline assembly. - */ - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -#include - -#include -#include -#include - -#include -#include - -using namespace std; -using namespace dev; -using namespace langutil; -using namespace dev::solidity; -using namespace dev::solidity::assembly; - -class EthAssemblyAdapter: public yul::AbstractAssembly -{ -public: - explicit EthAssemblyAdapter(eth::Assembly& _assembly): - m_assembly(_assembly) - { - } - virtual void setSourceLocation(SourceLocation const& _location) override - { - m_assembly.setSourceLocation(_location); - } - virtual int stackHeight() const override { return m_assembly.deposit(); } - virtual void appendInstruction(solidity::Instruction _instruction) override - { - m_assembly.append(_instruction); - } - virtual void appendConstant(u256 const& _constant) override - { - m_assembly.append(_constant); - } - /// Append a label. - virtual void appendLabel(LabelID _labelId) override - { - m_assembly.append(eth::AssemblyItem(eth::Tag, _labelId)); - } - /// Append a label reference. - virtual void appendLabelReference(LabelID _labelId) override - { - m_assembly.append(eth::AssemblyItem(eth::PushTag, _labelId)); - } - virtual size_t newLabelId() override - { - return assemblyTagToIdentifier(m_assembly.newTag()); - } - virtual size_t namedLabel(std::string const& _name) override - { - return assemblyTagToIdentifier(m_assembly.namedTag(_name)); - } - virtual void appendLinkerSymbol(std::string const& _linkerSymbol) override - { - m_assembly.appendLibraryAddress(_linkerSymbol); - } - virtual void appendJump(int _stackDiffAfter) override - { - appendInstruction(solidity::Instruction::JUMP); - m_assembly.adjustDeposit(_stackDiffAfter); - } - virtual void appendJumpTo(LabelID _labelId, int _stackDiffAfter) override - { - appendLabelReference(_labelId); - appendJump(_stackDiffAfter); - } - virtual void appendJumpToIf(LabelID _labelId) override - { - appendLabelReference(_labelId); - appendInstruction(solidity::Instruction::JUMPI); - } - virtual void appendBeginsub(LabelID, int) override - { - // TODO we could emulate that, though - solAssert(false, "BEGINSUB not implemented for EVM 1.0"); - } - /// Call a subroutine. - virtual void appendJumpsub(LabelID, int, int) override - { - // TODO we could emulate that, though - solAssert(false, "JUMPSUB not implemented for EVM 1.0"); - } - - /// Return from a subroutine. - virtual void appendReturnsub(int, int) override - { - // TODO we could emulate that, though - solAssert(false, "RETURNSUB not implemented for EVM 1.0"); - } - - virtual void appendAssemblySize() override - { - m_assembly.appendProgramSize(); - } - -private: - static LabelID assemblyTagToIdentifier(eth::AssemblyItem const& _tag) - { - u256 id = _tag.data(); - solAssert(id <= std::numeric_limits::max(), "Tag id too large."); - return LabelID(id); - } - - eth::Assembly& m_assembly; -}; - -void assembly::CodeGenerator::assemble( - Block const& _parsedData, - AsmAnalysisInfo& _analysisInfo, - eth::Assembly& _assembly, - yul::ExternalIdentifierAccess const& _identifierAccess, - bool _useNamedLabelsForFunctions -) -{ - EthAssemblyAdapter assemblyAdapter(_assembly); - yul::CodeTransform( - assemblyAdapter, - _analysisInfo, - false, - false, - _identifierAccess, - _useNamedLabelsForFunctions - )(_parsedData); -} diff --git a/libsolidity/inlineasm/AsmCodeGen.h b/libsolidity/inlineasm/AsmCodeGen.h deleted file mode 100644 index bbc31397..00000000 --- a/libsolidity/inlineasm/AsmCodeGen.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - 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 . -*/ -/** - * @author Christian - * @date 2016 - * Code-generating part of inline assembly. - */ - -#pragma once - -#include - -#include - -namespace dev -{ -namespace eth -{ -class Assembly; -} -namespace solidity -{ -namespace assembly -{ -struct Block; - -class CodeGenerator -{ -public: - /// Performs code generation and appends generated to _assembly. - static void assemble( - Block const& _parsedData, - AsmAnalysisInfo& _analysisInfo, - eth::Assembly& _assembly, - yul::ExternalIdentifierAccess const& _identifierAccess = yul::ExternalIdentifierAccess(), - bool _useNamedLabelsForFunctions = false - ); -}; - -} -} -} diff --git a/libsolidity/inlineasm/AsmData.h b/libsolidity/inlineasm/AsmData.h deleted file mode 100644 index 23a9db75..00000000 --- a/libsolidity/inlineasm/AsmData.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - 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 . -*/ -/** - * @author Christian - * @date 2016 - * Parsed inline assembly to be used by the AST - */ - -#pragma once - -#include - -#include -#include - -#include - -#include -#include - -#include -#include - -namespace dev -{ -namespace solidity -{ -namespace assembly -{ - -using YulString = dev::yul::YulString; -using Type = YulString; - -struct TypedName { langutil::SourceLocation location; YulString name; Type type; }; -using TypedNameList = std::vector; - -/// Direct EVM instruction (except PUSHi and JUMPDEST) -struct Instruction { langutil::SourceLocation location; solidity::Instruction instruction; }; -/// Literal number or string (up to 32 bytes) -enum class LiteralKind { Number, Boolean, String }; -struct Literal { langutil::SourceLocation location; LiteralKind kind; YulString value; Type type; }; -/// External / internal identifier or label reference -struct Identifier { langutil::SourceLocation location; YulString name; }; -/// Jump label ("name:") -struct Label { langutil::SourceLocation location; YulString name; }; -/// Assignment from stack (":= x", moves stack top into x, potentially multiple slots) -struct StackAssignment { langutil::SourceLocation location; Identifier variableName; }; -/// 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::SourceLocation location; std::vector variableNames; std::shared_ptr value; }; -/// Functional instruction, e.g. "mul(mload(20:u256), add(2:u256, x))" -struct FunctionalInstruction { langutil::SourceLocation location; solidity::Instruction instruction; std::vector arguments; }; -struct FunctionCall { langutil::SourceLocation location; Identifier functionName; std::vector arguments; }; -/// Statement that contains only a single expression -struct ExpressionStatement { langutil::SourceLocation location; Expression expression; }; -/// Block-scope variable declaration ("let x:u256 := mload(20:u256)"), non-hoisted -struct VariableDeclaration { langutil::SourceLocation location; TypedNameList variables; std::shared_ptr value; }; -/// Block that creates a scope (frees declared stack variables) -struct Block { langutil::SourceLocation location; std::vector statements; }; -/// Function definition ("function f(a, b) -> (d, e) { ... }") -struct FunctionDefinition { langutil::SourceLocation location; YulString name; TypedNameList parameters; TypedNameList returnVariables; Block body; }; -/// Conditional execution without "else" part. -struct If { langutil::SourceLocation location; std::shared_ptr condition; Block body; }; -/// Switch case or default case -struct Case { langutil::SourceLocation location; std::shared_ptr value; Block body; }; -/// Switch statement -struct Switch { langutil::SourceLocation location; std::shared_ptr expression; std::vector cases; }; -struct ForLoop { langutil::SourceLocation location; Block pre; std::shared_ptr condition; Block post; Block body; }; - -struct LocationExtractor: boost::static_visitor -{ - template langutil::SourceLocation operator()(T const& _node) const - { - return _node.location; - } -}; - -/// Extracts the source location from an inline assembly node. -template inline langutil::SourceLocation locationOf(T const& _node) -{ - return boost::apply_visitor(LocationExtractor(), _node); -} - -} -} -} diff --git a/libsolidity/inlineasm/AsmDataForward.h b/libsolidity/inlineasm/AsmDataForward.h deleted file mode 100644 index 69cf8f1d..00000000 --- a/libsolidity/inlineasm/AsmDataForward.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - 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 . -*/ -/** - * @author Christian - * @date 2016 - * Forward declaration of classes for inline assembly / Yul AST - */ - -#pragma once - -#include - -namespace dev -{ -namespace solidity -{ -namespace assembly -{ - -struct Instruction; -struct Literal; -struct Label; -struct StackAssignment; -struct Identifier; -struct Assignment; -struct VariableDeclaration; -struct FunctionalInstruction; -struct FunctionDefinition; -struct FunctionCall; -struct If; -struct Switch; -struct Case; -struct ForLoop; -struct ExpressionStatement; -struct Block; - -struct TypedName; - -using Expression = boost::variant; -using Statement = boost::variant; - -enum class AsmFlavour -{ - Loose, // no types, EVM instructions as function, jumps and direct stack manipulations - Strict, // no types, EVM instructions as functions, but no jumps and no direct stack manipulations - Yul // same as Strict mode with types -}; - -} -} -} diff --git a/libsolidity/inlineasm/AsmParser.cpp b/libsolidity/inlineasm/AsmParser.cpp deleted file mode 100644 index b11f70e0..00000000 --- a/libsolidity/inlineasm/AsmParser.cpp +++ /dev/null @@ -1,617 +0,0 @@ -/* - 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 . -*/ -/** - * @author Christian - * @date 2016 - * Solidity inline assembly parser. - */ - -#include -#include -#include - -#include - -#include -#include - -using namespace std; -using namespace dev; -using namespace langutil; -using namespace dev::solidity; -using namespace dev::solidity::assembly; - -shared_ptr Parser::parse(std::shared_ptr const& _scanner, bool _reuseScanner) -{ - m_recursionDepth = 0; - try - { - m_scanner = _scanner; - auto block = make_shared(parseBlock()); - if (!_reuseScanner) - expectToken(Token::EOS); - return block; - } - catch (FatalError const&) - { - if (m_errorReporter.errors().empty()) - throw; // Something is weird here, rather throw again. - } - return nullptr; -} - -assembly::Block Parser::parseBlock() -{ - RecursionGuard recursionGuard(*this); - assembly::Block block = createWithLocation(); - expectToken(Token::LBrace); - while (currentToken() != Token::RBrace) - block.statements.emplace_back(parseStatement()); - block.location.end = endPosition(); - advance(); - return block; -} - -assembly::Statement Parser::parseStatement() -{ - RecursionGuard recursionGuard(*this); - switch (currentToken()) - { - case Token::Let: - return parseVariableDeclaration(); - case Token::Function: - return parseFunctionDefinition(); - case Token::LBrace: - return parseBlock(); - case Token::If: - { - assembly::If _if = createWithLocation(); - m_scanner->next(); - _if.condition = make_shared(parseExpression()); - _if.body = parseBlock(); - return _if; - } - case Token::Switch: - { - assembly::Switch _switch = createWithLocation(); - m_scanner->next(); - _switch.expression = make_shared(parseExpression()); - while (m_scanner->currentToken() == Token::Case) - _switch.cases.emplace_back(parseCase()); - if (m_scanner->currentToken() == Token::Default) - _switch.cases.emplace_back(parseCase()); - if (m_scanner->currentToken() == Token::Default) - fatalParserError("Only one default case allowed."); - else if (m_scanner->currentToken() == Token::Case) - fatalParserError("Case not allowed after default case."); - if (_switch.cases.empty()) - fatalParserError("Switch statement without any cases."); - _switch.location.end = _switch.cases.back().body.location.end; - return _switch; - } - case Token::For: - return parseForLoop(); - case Token::Assign: - { - if (m_flavour != AsmFlavour::Loose) - break; - assembly::StackAssignment assignment = createWithLocation(); - advance(); - expectToken(Token::Colon); - assignment.variableName.location = location(); - assignment.variableName.name = YulString(currentLiteral()); - if (instructions().count(assignment.variableName.name.str())) - fatalParserError("Identifier expected, got instruction name."); - assignment.location.end = endPosition(); - expectToken(Token::Identifier); - return assignment; - } - default: - break; - } - // Options left: - // Simple instruction (might turn into functional), - // literal, - // identifier (might turn into label or functional assignment) - ElementaryOperation elementary(parseElementaryOperation()); - switch (currentToken()) - { - case Token::LParen: - { - Expression expr = parseCall(std::move(elementary)); - return ExpressionStatement{locationOf(expr), expr}; - } - case Token::Comma: - { - // if a comma follows, a multiple assignment is assumed - - if (elementary.type() != typeid(assembly::Identifier)) - fatalParserError("Label name / variable name must precede \",\" (multiple assignment)."); - assembly::Identifier const& identifier = boost::get(elementary); - - Assignment assignment = createWithLocation(identifier.location); - assignment.variableNames.emplace_back(identifier); - - do - { - expectToken(Token::Comma); - elementary = parseElementaryOperation(); - if (elementary.type() != typeid(assembly::Identifier)) - fatalParserError("Variable name expected in multiple assignment."); - assignment.variableNames.emplace_back(boost::get(elementary)); - } - while (currentToken() == Token::Comma); - - expectToken(Token::Colon); - expectToken(Token::Assign); - - assignment.value.reset(new Expression(parseExpression())); - assignment.location.end = locationOf(*assignment.value).end; - return assignment; - } - case Token::Colon: - { - if (elementary.type() != typeid(assembly::Identifier)) - fatalParserError("Label name / variable name must precede \":\"."); - assembly::Identifier const& identifier = boost::get(elementary); - advance(); - // identifier:=: should be parsed as identifier: =: (i.e. a label), - // while identifier:= (being followed by a non-colon) as identifier := (assignment). - if (currentToken() == Token::Assign && peekNextToken() != Token::Colon) - { - assembly::Assignment assignment = createWithLocation(identifier.location); - if (m_flavour != AsmFlavour::Yul && instructions().count(identifier.name.str())) - fatalParserError("Cannot use instruction names for identifier names."); - advance(); - assignment.variableNames.emplace_back(identifier); - assignment.value.reset(new Expression(parseExpression())); - assignment.location.end = locationOf(*assignment.value).end; - return assignment; - } - else - { - // label - if (m_flavour != AsmFlavour::Loose) - fatalParserError("Labels are not supported."); - Label label = createWithLocation