Implemented FunctionSpecializer

Optimiser step that specializes the function with its literal arguments.
This commit is contained in:
hrkrshnn 2020-11-20 22:56:28 +01:00
parent 8564d08228
commit 22ebdc7438
4 changed files with 260 additions and 4 deletions

View File

@ -93,10 +93,8 @@ template <class T>
inline std::vector<T> operator+(std::vector<T>&& _a, std::vector<T>&& _b)
{
std::vector<T> ret(std::move(_a));
if (&_a == &_b)
ret += ret;
else
ret += std::move(_b);
assert(&_a != &_b);
ret += std::move(_b);
return ret;
}

View File

@ -131,6 +131,8 @@ add_library(yul
optimiser/FunctionGrouper.h
optimiser/FunctionHoister.cpp
optimiser/FunctionHoister.h
optimiser/FunctionSpecializer.cpp
optimiser/FunctionSpecializer.h
optimiser/InlinableExpressionFunctionFinder.cpp
optimiser/InlinableExpressionFunctionFinder.h
optimiser/KnowledgeBase.cpp

View File

@ -0,0 +1,150 @@
/*
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 <libyul/optimiser/FunctionSpecializer.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/AST.h>
#include <libyul/YulString.h>
#include <libsolutil/CommonData.h>
#include <range/v3/algorithm/any_of.hpp>
#include <range/v3/view/enumerate.hpp>
#include <variant>
using namespace std;
using namespace solidity::util;
using namespace solidity::yul;
FunctionSpecializer::LiteralArguments FunctionSpecializer::specializableArguments(
FunctionCall const& _f
)
{
auto heuristic = [&](Expression const& _e) -> optional<Expression>
{
if (holds_alternative<Literal>(_e))
return ASTCopier{}.translate(_e);
return nullopt;
};
return applyMap(_f.arguments, heuristic);
}
void FunctionSpecializer::operator()(FunctionCall& _f)
{
ASTModifier::operator()(_f);
if (m_dialect.builtin(_f.functionName.name))
return;
LiteralArguments arguments = specializableArguments(_f);
if (ranges::any_of(arguments, [](auto& _a) { return _a.has_value(); }))
{
YulString oldName = move(_f.functionName.name);
auto newName = m_nameDispenser.newName(oldName);
m_oldToNewMap[oldName].emplace_back(make_pair(newName, arguments));
_f.functionName.name = newName;
_f.arguments = util::filter(
_f.arguments,
applyMap(arguments, [](auto& _a) { return !_a; })
);
}
}
FunctionDefinition FunctionSpecializer::specialize(
FunctionDefinition const& _f,
YulString _newName,
FunctionSpecializer::LiteralArguments _arguments
)
{
yulAssert(_arguments.size() == _f.parameters.size(), "");
map<YulString, YulString> translatedNames = applyMap(
NameCollector{_f, NameCollector::OnlyVariables}.names(),
[&](auto& _name) -> pair<YulString, YulString>
{
return make_pair(_name, m_nameDispenser.newName(_name));
},
map<YulString, YulString>{}
);
FunctionDefinition newFunction = get<FunctionDefinition>(FunctionCopier{translatedNames}(_f));
// Function parameters that will be specialized inside the body are converted into variable
// declarations.
vector<Statement> missingVariableDeclarations;
for (auto&& [index, argument]: _arguments | ranges::views::enumerate)
if (argument)
missingVariableDeclarations.emplace_back(
VariableDeclaration{
_f.location,
vector<TypedName>{newFunction.parameters[index]},
make_unique<Expression>(move(*argument))
}
);
newFunction.body.statements =
move(missingVariableDeclarations) + move(newFunction.body.statements);
// Only take those indices where optional in arguments in nullopt
newFunction.parameters =
util::filter(
newFunction.parameters,
applyMap(_arguments, [&](auto const& _v) { return !_v; })
);
newFunction.name = move(_newName);
return newFunction;
}
void FunctionSpecializer::run(OptimiserStepContext& _context, Block& _ast)
{
// Finds all function calls that can be replaced.
FunctionSpecializer f{_context.dispenser, _context.dialect};
f(_ast);
iterateReplacing(_ast.statements, [&](Statement& _s) -> optional<vector<Statement>>
{
if (holds_alternative<FunctionDefinition>(_s))
{
auto& functionDefinition = get<FunctionDefinition>(_s);
if (f.m_oldToNewMap.count(functionDefinition.name))
{
vector<Statement> out = applyMap(
f.m_oldToNewMap.at(functionDefinition.name),
[&](auto& _p) -> Statement
{
return f.specialize(functionDefinition, move(_p.first), move(_p.second));
}
);
return move(out) + make_vector<Statement>(move(functionDefinition));
}
}
return nullopt;
});
}

View File

@ -0,0 +1,106 @@
/*
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(NameDispenser& _nameDispenser, Dialect const& _dialect):
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,
YulString _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<YulString, std::vector<std::pair<YulString, LiteralArguments>>> m_oldToNewMap;
NameDispenser& m_nameDispenser;
Dialect const& m_dialect;
};
}