/*
	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 .
*/
/**
 * Component that translates Solidity code into Yul at statement level and below.
 */
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
using namespace solidity;
using namespace solidity::util;
using namespace solidity::frontend;
using namespace std::string_literals;
namespace
{
struct CopyTranslate: public yul::ASTCopier
{
	using ExternalRefsMap = std::map;
	CopyTranslate(yul::Dialect const& _dialect, IRGenerationContext& _context, ExternalRefsMap const& _references):
		m_dialect(_dialect), m_context(_context), m_references(_references) {}
	using ASTCopier::operator();
	yul::Expression operator()(yul::Identifier const& _identifier) override
	{
		if (m_references.count(&_identifier))
		{
			auto const& reference = m_references.at(&_identifier);
			auto const varDecl = dynamic_cast(reference.declaration);
			solUnimplementedAssert(varDecl, "");
			if (reference.isOffset || reference.isSlot)
			{
				solAssert(reference.isOffset != reference.isSlot, "");
				pair slot_offset = m_context.storageLocationOfVariable(*varDecl);
				string const value = reference.isSlot ?
					slot_offset.first.str() :
					to_string(slot_offset.second);
				return yul::Literal{
					_identifier.location,
					yul::LiteralKind::Number,
					yul::YulString{value},
					{}
				};
			}
		}
		return ASTCopier::operator()(_identifier);
	}
	yul::YulString translateIdentifier(yul::YulString _name) override
	{
		// Strictly, the dialect used by inline assembly (m_dialect) could be different
		// from the Yul dialect we are compiling to. So we are assuming here that the builtin
		// functions are identical. This should not be a problem for now since everything
		// is EVM anyway.
		if (m_dialect.builtin(_name))
			return _name;
		else
			return yul::YulString{"usr$" + _name.str()};
	}
	yul::Identifier translate(yul::Identifier const& _identifier) override
	{
		if (!m_references.count(&_identifier))
			return ASTCopier::translate(_identifier);
		auto const& reference = m_references.at(&_identifier);
		auto const varDecl = dynamic_cast(reference.declaration);
		solUnimplementedAssert(varDecl, "");
		solAssert(
			reference.isOffset == false && reference.isSlot == false,
			"Should not be called for offset/slot"
		);
		return yul::Identifier{
			_identifier.location,
			yul::YulString{m_context.localVariable(*varDecl).name()}
		};
	}
private:
	yul::Dialect const& m_dialect;
	IRGenerationContext& m_context;
	ExternalRefsMap const& m_references;
};
}
string IRGeneratorForStatements::code() const
{
	solAssert(!m_currentLValue, "LValue not reset!");
	return m_code.str();
}
void IRGeneratorForStatements::initializeStateVar(VariableDeclaration const& _varDecl)
{
	solAssert(m_context.isStateVariable(_varDecl), "Must be a state variable.");
	solAssert(!_varDecl.isConstant(), "");
	solAssert(!_varDecl.immutable(), "");
	if (_varDecl.value())
	{
		_varDecl.value()->accept(*this);
		writeToLValue(IRLValue{
			*_varDecl.annotation().type,
			IRLValue::Storage{
				util::toCompactHexWithPrefix(m_context.storageLocationOfVariable(_varDecl).first),
				m_context.storageLocationOfVariable(_varDecl).second
			}
		}, *_varDecl.value());
	}
}
void IRGeneratorForStatements::initializeLocalVar(VariableDeclaration const& _varDecl)
{
	solAssert(m_context.isLocalVariable(_varDecl), "Must be a local variable.");
	auto const* type = _varDecl.type();
	if (auto const* refType = dynamic_cast(type))
		if (refType->dataStoredIn(DataLocation::Storage) && refType->isPointer())
			return;
	IRVariable zero = zeroValue(*type);
	assign(m_context.localVariable(_varDecl), zero);
}
IRVariable IRGeneratorForStatements::evaluateExpression(Expression const& _expression, Type const& _targetType)
{
	_expression.accept(*this);
	IRVariable variable{m_context.newYulVariable(), _targetType};
	define(variable, _expression);
	return variable;
}
void IRGeneratorForStatements::endVisit(VariableDeclarationStatement const& _varDeclStatement)
{
	if (Expression const* expression = _varDeclStatement.initialValue())
	{
		if (_varDeclStatement.declarations().size() > 1)
		{
			auto const* tupleType = dynamic_cast(expression->annotation().type);
			solAssert(tupleType, "Expected expression of tuple type.");
			solAssert(_varDeclStatement.declarations().size() == tupleType->components().size(), "Invalid number of tuple components.");
			for (size_t i = 0; i < _varDeclStatement.declarations().size(); ++i)
				if (auto const& decl = _varDeclStatement.declarations()[i])
				{
					solAssert(tupleType->components()[i], "");
					define(m_context.addLocalVariable(*decl), IRVariable(*expression).tupleComponent(i));
				}
		}
		else
		{
			VariableDeclaration const& varDecl = *_varDeclStatement.declarations().front();
			define(m_context.addLocalVariable(varDecl), *expression);
		}
	}
	else
		for (auto const& decl: _varDeclStatement.declarations())
			if (decl)
			{
				declare(m_context.addLocalVariable(*decl));
				initializeLocalVar(*decl);
			}
}
bool IRGeneratorForStatements::visit(Conditional const& _conditional)
{
	_conditional.condition().accept(*this);
	string condition = expressionAsType(_conditional.condition(), *TypeProvider::boolean());
	declare(_conditional);
	m_code << "switch " << condition << "\n" "case 0 {\n";
	_conditional.falseExpression().accept(*this);
	assign(_conditional, _conditional.falseExpression());
	m_code << "}\n" "default {\n";
	_conditional.trueExpression().accept(*this);
	assign(_conditional, _conditional.trueExpression());
	m_code << "}\n";
	return false;
}
bool IRGeneratorForStatements::visit(Assignment const& _assignment)
{
	_assignment.rightHandSide().accept(*this);
	Type const* intermediateType = type(_assignment.rightHandSide()).closestTemporaryType(
		&type(_assignment.leftHandSide())
	);
	IRVariable value = convert(_assignment.rightHandSide(), *intermediateType);
	_assignment.leftHandSide().accept(*this);
	solAssert(!!m_currentLValue, "LValue not retrieved.");
	if (_assignment.assignmentOperator() != Token::Assign)
	{
		solAssert(type(_assignment.leftHandSide()) == *intermediateType, "");
		solAssert(intermediateType->isValueType(), "Compound operators only available for value types.");
		IRVariable leftIntermediate = readFromLValue(*m_currentLValue);
		m_code << value.name() << " := " << binaryOperation(
			TokenTraits::AssignmentToBinaryOp(_assignment.assignmentOperator()),
			*intermediateType,
			leftIntermediate.name(),
			value.name()
		);
	}
	writeToLValue(*m_currentLValue, value);
	m_currentLValue.reset();
	if (*_assignment.annotation().type != *TypeProvider::emptyTuple())
		define(_assignment, value);
	return false;
}
bool IRGeneratorForStatements::visit(TupleExpression const& _tuple)
{
	if (_tuple.isInlineArray())
		solUnimplementedAssert(false, "");
	else
	{
		bool willBeWrittenTo = _tuple.annotation().willBeWrittenTo;
		if (willBeWrittenTo)
			solAssert(!m_currentLValue, "");
		if (_tuple.components().size() == 1)
		{
			solAssert(_tuple.components().front(), "");
			_tuple.components().front()->accept(*this);
			if (willBeWrittenTo)
				solAssert(!!m_currentLValue, "");
			else
				define(_tuple, *_tuple.components().front());
		}
		else
		{
			vector> lvalues;
			for (size_t i = 0; i < _tuple.components().size(); ++i)
				if (auto const& component = _tuple.components()[i])
				{
					component->accept(*this);
					if (willBeWrittenTo)
					{
						solAssert(!!m_currentLValue, "");
						lvalues.emplace_back(std::move(m_currentLValue));
						m_currentLValue.reset();
					}
					else
						define(IRVariable(_tuple).tupleComponent(i), *component);
				}
				else if (willBeWrittenTo)
					lvalues.emplace_back();
			if (_tuple.annotation().willBeWrittenTo)
				m_currentLValue.emplace(IRLValue{
					*_tuple.annotation().type,
					IRLValue::Tuple{std::move(lvalues)}
				});
		}
	}
	return false;
}
bool IRGeneratorForStatements::visit(IfStatement const& _ifStatement)
{
	_ifStatement.condition().accept(*this);
	string condition = expressionAsType(_ifStatement.condition(), *TypeProvider::boolean());
	if (_ifStatement.falseStatement())
	{
		m_code << "switch " << condition << "\n" "case 0 {\n";
		_ifStatement.falseStatement()->accept(*this);
		m_code << "}\n" "default {\n";
	}
	else
		m_code << "if " << condition << " {\n";
	_ifStatement.trueStatement().accept(*this);
	m_code << "}\n";
	return false;
}
bool IRGeneratorForStatements::visit(ForStatement const& _forStatement)
{
	generateLoop(
		_forStatement.body(),
		_forStatement.condition(),
		_forStatement.initializationExpression(),
		_forStatement.loopExpression()
	);
	return false;
}
bool IRGeneratorForStatements::visit(WhileStatement const& _whileStatement)
{
	generateLoop(
		_whileStatement.body(),
		&_whileStatement.condition(),
		nullptr,
		nullptr,
		_whileStatement.isDoWhile()
	);
	return false;
}
bool IRGeneratorForStatements::visit(Continue const&)
{
	m_code << "continue\n";
	return false;
}
bool IRGeneratorForStatements::visit(Break const&)
{
	m_code << "break\n";
	return false;
}
void IRGeneratorForStatements::endVisit(Return const& _return)
{
	if (Expression const* value = _return.expression())
	{
		solAssert(_return.annotation().functionReturnParameters, "Invalid return parameters pointer.");
		vector> const& returnParameters =
			_return.annotation().functionReturnParameters->parameters();
		if (returnParameters.size() > 1)
			for (size_t i = 0; i < returnParameters.size(); ++i)
				assign(m_context.localVariable(*returnParameters[i]), IRVariable(*value).tupleComponent(i));
		else if (returnParameters.size() == 1)
			assign(m_context.localVariable(*returnParameters.front()), *value);
	}
	m_code << "leave\n";
}
void IRGeneratorForStatements::endVisit(UnaryOperation const& _unaryOperation)
{
	Type const& resultType = type(_unaryOperation);
	Token const op = _unaryOperation.getOperator();
	if (op == Token::Delete)
	{
		solAssert(!!m_currentLValue, "LValue not retrieved.");
		std::visit(
			util::GenericVisitor{
				[&](IRLValue::Storage const& _storage) {
					m_code <<
						m_utils.storageSetToZeroFunction(m_currentLValue->type) <<
						"(" <<
						_storage.slot <<
						", " <<
						_storage.offsetString() <<
						")\n";
					m_currentLValue.reset();
				},
				[&](auto const&) {
					IRVariable zeroValue(m_context.newYulVariable(), m_currentLValue->type);
					define(zeroValue) << m_utils.zeroValueFunction(m_currentLValue->type) << "()\n";
					writeToLValue(*m_currentLValue, zeroValue);
					m_currentLValue.reset();
				}
			},
			m_currentLValue->kind
		);
	}
	else if (resultType.category() == Type::Category::RationalNumber)
		define(_unaryOperation) << formatNumber(resultType.literalValue(nullptr)) << "\n";
	else if (resultType.category() == Type::Category::Integer)
	{
		solAssert(resultType == type(_unaryOperation.subExpression()), "Result type doesn't match!");
		if (op == Token::Inc || op == Token::Dec)
		{
			solAssert(!!m_currentLValue, "LValue not retrieved.");
			IRVariable modifiedValue(m_context.newYulVariable(), resultType);
			IRVariable originalValue = readFromLValue(*m_currentLValue);
			define(modifiedValue) <<
				(op == Token::Inc ?
					m_utils.incrementCheckedFunction(resultType) :
					m_utils.decrementCheckedFunction(resultType)
				) <<
				"(" <<
				originalValue.name() <<
				")\n";
			writeToLValue(*m_currentLValue, modifiedValue);
			m_currentLValue.reset();
			define(_unaryOperation, _unaryOperation.isPrefixOperation() ? modifiedValue : originalValue);
		}
		else if (op == Token::BitNot)
			appendSimpleUnaryOperation(_unaryOperation, _unaryOperation.subExpression());
		else if (op == Token::Add)
			// According to SyntaxChecker...
			solAssert(false, "Use of unary + is disallowed.");
		else if (op == Token::Sub)
		{
			IntegerType const& intType = *dynamic_cast(&resultType);
			define(_unaryOperation) <<
				m_utils.negateNumberCheckedFunction(intType) <<
				"(" <<
				IRVariable(_unaryOperation.subExpression()).name() <<
				")\n";
		}
		else
			solUnimplementedAssert(false, "Unary operator not yet implemented");
	}
	else if (resultType.category() == Type::Category::Bool)
	{
		solAssert(
			_unaryOperation.getOperator() != Token::BitNot,
			"Bitwise Negation can't be done on bool!"
		);
		appendSimpleUnaryOperation(_unaryOperation, _unaryOperation.subExpression());
	}
	else
		solUnimplementedAssert(false, "Unary operator not yet implemented");
}
bool IRGeneratorForStatements::visit(BinaryOperation const& _binOp)
{
	solAssert(!!_binOp.annotation().commonType, "");
	TypePointer commonType = _binOp.annotation().commonType;
	langutil::Token op = _binOp.getOperator();
	if (op == Token::And || op == Token::Or)
	{
		// This can short-circuit!
		appendAndOrOperatorCode(_binOp);
		return false;
	}
	_binOp.leftExpression().accept(*this);
	_binOp.rightExpression().accept(*this);
	if (commonType->category() == Type::Category::RationalNumber)
		define(_binOp) << toCompactHexWithPrefix(commonType->literalValue(nullptr)) << "\n";
	else if (TokenTraits::isCompareOp(op))
	{
		if (auto type = dynamic_cast(commonType))
		{
			solAssert(op == Token::Equal || op == Token::NotEqual, "Invalid function pointer comparison!");
			solAssert(type->kind() != FunctionType::Kind::External, "External function comparison not allowed!");
		}
		solAssert(commonType->isValueType(), "");
		bool isSigned = false;
		if (auto type = dynamic_cast(commonType))
			isSigned = type->isSigned();
		string args =
			expressionAsType(_binOp.leftExpression(), *commonType) +
			", " +
			expressionAsType(_binOp.rightExpression(), *commonType);
		string expr;
		if (op == Token::Equal)
			expr = "eq(" + move(args) + ")";
		else if (op == Token::NotEqual)
			expr = "iszero(eq(" + move(args) + "))";
		else if (op == Token::GreaterThanOrEqual)
			expr = "iszero(" + string(isSigned ? "slt(" : "lt(") + move(args) + "))";
		else if (op == Token::LessThanOrEqual)
			expr = "iszero(" + string(isSigned ? "sgt(" : "gt(") + move(args) + "))";
		else if (op == Token::GreaterThan)
			expr = (isSigned ? "sgt(" : "gt(") + move(args) + ")";
		else if (op == Token::LessThan)
			expr = (isSigned ? "slt(" : "lt(") + move(args) + ")";
		else
			solAssert(false, "Unknown comparison operator.");
		define(_binOp) << expr << "\n";
	}
	else
	{
		string left = expressionAsType(_binOp.leftExpression(), *commonType);
		string right = expressionAsType(_binOp.rightExpression(), *commonType);
		define(_binOp) << binaryOperation(_binOp.getOperator(), *commonType, left, right) << "\n";
	}
	return false;
}
void IRGeneratorForStatements::endVisit(FunctionCall const& _functionCall)
{
	solUnimplementedAssert(
		_functionCall.annotation().kind == FunctionCallKind::FunctionCall ||
		_functionCall.annotation().kind == FunctionCallKind::TypeConversion,
		"This type of function call is not yet implemented"
	);
	Type const& funcType = type(_functionCall.expression());
	if (_functionCall.annotation().kind == FunctionCallKind::TypeConversion)
	{
		solAssert(funcType.category() == Type::Category::TypeType, "Expected category to be TypeType");
		solAssert(_functionCall.arguments().size() == 1, "Expected one argument for type conversion");
		define(_functionCall, *_functionCall.arguments().front());
		return;
	}
	FunctionTypePointer functionType = dynamic_cast(&funcType);
	TypePointers parameterTypes = functionType->parameterTypes();
	vector> const& callArguments = _functionCall.arguments();
	vector> const& callArgumentNames = _functionCall.names();
	if (!functionType->takesArbitraryParameters())
		solAssert(callArguments.size() == parameterTypes.size(), "");
	vector> arguments;
	if (callArgumentNames.empty())
		// normal arguments
		arguments = callArguments;
	else
		// named arguments
		for (auto const& parameterName: functionType->parameterNames())
		{
			auto const it = std::find_if(callArgumentNames.cbegin(), callArgumentNames.cend(), [&](ASTPointer const& _argName) {
				return *_argName == parameterName;
			});
			solAssert(it != callArgumentNames.cend(), "");
			arguments.push_back(callArguments[std::distance(callArgumentNames.begin(), it)]);
		}
	if (auto memberAccess = dynamic_cast(&_functionCall.expression()))
		if (auto expressionType = dynamic_cast(memberAccess->expression().annotation().type))
			if (auto contractType = dynamic_cast(expressionType->actualType()))
				solUnimplementedAssert(
					!contractType->contractDefinition().isLibrary() || functionType->kind() == FunctionType::Kind::Internal,
					"Only internal function calls implemented for libraries"
				);
	solUnimplementedAssert(!functionType->bound(), "");
	switch (functionType->kind())
	{
	case FunctionType::Kind::Declaration:
		solAssert(false, "Attempted to generate code for calling a function definition.");
		break;
	case FunctionType::Kind::Internal:
	{
		vector args;
		for (unsigned i = 0; i < arguments.size(); ++i)
			if (functionType->takesArbitraryParameters())
				args.emplace_back(IRVariable(*arguments[i]).commaSeparatedList());
			else
				args.emplace_back(convert(*arguments[i], *parameterTypes[i]).commaSeparatedList());
		optional functionDef;
		if (auto memberAccess = dynamic_cast(&_functionCall.expression()))
		{
			solUnimplementedAssert(!functionType->bound(), "Internal calls to bound functions are not yet implemented for libraries and not allowed for contracts");
			functionDef = dynamic_cast(memberAccess->annotation().referencedDeclaration);
			if (functionDef.value() != nullptr)
				solAssert(functionType->declaration() == *memberAccess->annotation().referencedDeclaration, "");
			else
			{
				solAssert(dynamic_cast(memberAccess->annotation().referencedDeclaration), "");
				solAssert(!functionType->hasDeclaration(), "");
			}
		}
		else if (auto identifier = dynamic_cast(&_functionCall.expression()))
		{
			solAssert(!functionType->bound(), "");
			if (auto unresolvedFunctionDef = dynamic_cast(identifier->annotation().referencedDeclaration))
			{
				functionDef = &unresolvedFunctionDef->resolveVirtual(m_context.mostDerivedContract());
				solAssert(functionType->declaration() == *identifier->annotation().referencedDeclaration, "");
			}
			else
			{
				functionDef = nullptr;
				solAssert(dynamic_cast(identifier->annotation().referencedDeclaration), "");
				solAssert(!functionType->hasDeclaration(), "");
			}
		}
		else
			// Not a simple expression like x or A.x
			functionDef = nullptr;
		solAssert(functionDef.has_value(), "");
		solAssert(functionDef.value() == nullptr || functionDef.value()->isImplemented(), "");
		if (functionDef.value() != nullptr)
			define(_functionCall) <<
				m_context.enqueueFunctionForCodeGeneration(*functionDef.value()) <<
				"(" <<
				joinHumanReadable(args) <<
				")\n";
		else
			define(_functionCall) <<
				// NOTE: internalDispatch() takes care of adding the function to function generation queue
				m_context.internalDispatch(
					TupleType(functionType->parameterTypes()).sizeOnStack(),
					TupleType(functionType->returnParameterTypes()).sizeOnStack()
				) <<
				"(" <<
				IRVariable(_functionCall.expression()).part("functionIdentifier").name() <<
				joinHumanReadablePrefixed(args) <<
				")\n";
		break;
	}
	case FunctionType::Kind::External:
	case FunctionType::Kind::DelegateCall:
	case FunctionType::Kind::BareCall:
	case FunctionType::Kind::BareDelegateCall:
	case FunctionType::Kind::BareStaticCall:
		appendExternalFunctionCall(_functionCall, arguments);
		break;
	case FunctionType::Kind::BareCallCode:
		solAssert(false, "Callcode has been removed.");
	case FunctionType::Kind::Event:
	{
		auto const& event = dynamic_cast(functionType->declaration());
		TypePointers paramTypes = functionType->parameterTypes();
		ABIFunctions abi(m_context.evmVersion(), m_context.revertStrings(), m_context.functionCollector());
		vector indexedArgs;
		string nonIndexedArgs;
		TypePointers nonIndexedArgTypes;
		TypePointers nonIndexedParamTypes;
		if (!event.isAnonymous())
			define(indexedArgs.emplace_back(m_context.newYulVariable(), *TypeProvider::uint256())) <<
				formatNumber(u256(h256::Arith(keccak256(functionType->externalSignature())))) << "\n";
		for (size_t i = 0; i < event.parameters().size(); ++i)
		{
			Expression const& arg = *arguments[i];
			if (event.parameters()[i]->isIndexed())
			{
				string value;
				if (auto const& referenceType = dynamic_cast(paramTypes[i]))
					define(indexedArgs.emplace_back(m_context.newYulVariable(), *TypeProvider::uint256())) <<
						m_utils.packedHashFunction({arg.annotation().type}, {referenceType}) <<
						"(" <<
						IRVariable(arg).commaSeparatedList() <<
						")";
				else
					indexedArgs.emplace_back(convert(arg, *paramTypes[i]));
			}
			else
			{
				string vars = IRVariable(arg).commaSeparatedList();
				if (!vars.empty())
					// In reverse because abi_encode expects it like that.
					nonIndexedArgs = ", " + move(vars) + nonIndexedArgs;
				nonIndexedArgTypes.push_back(arg.annotation().type);
				nonIndexedParamTypes.push_back(paramTypes[i]);
			}
		}
		solAssert(indexedArgs.size() <= 4, "Too many indexed arguments.");
		Whiskers templ(R"({
			let  := 
			let  := ( )
			(, sub(, ) )
		})");
		templ("pos", m_context.newYulVariable());
		templ("end", m_context.newYulVariable());
		templ("freeMemory", freeMemory());
		templ("encode", abi.tupleEncoder(nonIndexedArgTypes, nonIndexedParamTypes));
		templ("nonIndexedArgs", nonIndexedArgs);
		templ("log", "log" + to_string(indexedArgs.size()));
		templ("indexedArgs", joinHumanReadablePrefixed(indexedArgs | boost::adaptors::transformed([&](auto const& _arg) {
			return _arg.commaSeparatedList();
		})));
		m_code << templ.render();
		break;
	}
	case FunctionType::Kind::Assert:
	case FunctionType::Kind::Require:
	{
		solAssert(arguments.size() > 0, "Expected at least one parameter for require/assert");
		solAssert(arguments.size() <= 2, "Expected no more than two parameters for require/assert");
		Type const* messageArgumentType = arguments.size() > 1 ? arguments[1]->annotation().type : nullptr;
		string requireOrAssertFunction = m_utils.requireOrAssertFunction(
			functionType->kind() == FunctionType::Kind::Assert,
			messageArgumentType
		);
		m_code << move(requireOrAssertFunction) << "(" << IRVariable(*arguments[0]).name();
		if (messageArgumentType && messageArgumentType->sizeOnStack() > 0)
			m_code << ", " << IRVariable(*arguments[1]).commaSeparatedList();
		m_code << ")\n";
		break;
	}
	// Array creation using new
	case FunctionType::Kind::ObjectCreation:
	{
		ArrayType const& arrayType = dynamic_cast(*_functionCall.annotation().type);
		solAssert(arguments.size() == 1, "");
		IRVariable value = convert(*arguments[0], *TypeProvider::uint256());
		define(_functionCall) <<
			m_utils.allocateAndInitializeMemoryArrayFunction(arrayType) <<
			"(" <<
			value.commaSeparatedList() <<
			")\n";
		break;
	}
	case FunctionType::Kind::KECCAK256:
	{
		solAssert(arguments.size() == 1, "");
		ArrayType const* arrayType = TypeProvider::bytesMemory();
		auto array = convert(*arguments[0], *arrayType);
		define(_functionCall) <<
			"keccak256(" <<
			m_utils.arrayDataAreaFunction(*arrayType) <<
			"(" <<
			array.commaSeparatedList() <<
			"), " <<
			m_utils.arrayLengthFunction(*arrayType) <<
			"(" <<
			array.commaSeparatedList() <<
			"))\n";
		break;
	}
	case FunctionType::Kind::ECRecover:
	case FunctionType::Kind::SHA256:
	case FunctionType::Kind::RIPEMD160:
	{
		solAssert(!_functionCall.annotation().tryCall, "");
		appendExternalFunctionCall(_functionCall, arguments);
		break;
	}
	case FunctionType::Kind::ArrayPop:
	{
		auto const& memberAccessExpression = dynamic_cast(_functionCall.expression()).expression();
		ArrayType const& arrayType = dynamic_cast(*memberAccessExpression.annotation().type);
		define(_functionCall) <<
			m_utils.storageArrayPopFunction(arrayType) <<
			"(" <<
			IRVariable(_functionCall.expression()).commaSeparatedList() <<
			")\n";
		break;
	}
	case FunctionType::Kind::ArrayPush:
	{
		auto const& memberAccessExpression = dynamic_cast(_functionCall.expression()).expression();
		ArrayType const& arrayType = dynamic_cast(*memberAccessExpression.annotation().type);
		if (arguments.empty())
		{
			auto slotName = m_context.newYulVariable();
			auto offsetName = m_context.newYulVariable();
			m_code << "let " << slotName << ", " << offsetName << " := " <<
				m_utils.storageArrayPushZeroFunction(arrayType) <<
				"(" << IRVariable(_functionCall.expression()).commaSeparatedList() << ")\n";
			setLValue(_functionCall, IRLValue{
				*arrayType.baseType(),
				IRLValue::Storage{
					slotName,
					offsetName,
				}
			});
		}
		else
		{
			IRVariable argument = convert(*arguments.front(), *arrayType.baseType());
			m_code <<
				m_utils.storageArrayPushFunction(arrayType) <<
				"(" <<
				IRVariable(_functionCall.expression()).commaSeparatedList() <<
				", " <<
				argument.commaSeparatedList() <<
				")\n";
		}
		break;
	}
	case FunctionType::Kind::MetaType:
	{
		break;
	}
	case FunctionType::Kind::GasLeft:
	{
		define(_functionCall) << "gas()\n";
		break;
	}
	case FunctionType::Kind::Selfdestruct:
	{
		solAssert(arguments.size() == 1, "");
		define(_functionCall) << "selfdestruct(" << expressionAsType(*arguments.front(), *parameterTypes.front()) << ")\n";
		break;
	}
	case FunctionType::Kind::Log0:
	case FunctionType::Kind::Log1:
	case FunctionType::Kind::Log2:
	case FunctionType::Kind::Log3:
	case FunctionType::Kind::Log4:
	{
		unsigned logNumber = int(functionType->kind()) - int(FunctionType::Kind::Log0);
		solAssert(arguments.size() == logNumber + 1, "");
		ABIFunctions abi(m_context.evmVersion(), m_context.revertStrings(), m_context.functionCollector());
		string indexedArgs;
		for (unsigned arg = 0; arg < logNumber; ++arg)
			indexedArgs += ", " + expressionAsType(*arguments[arg + 1], *(parameterTypes[arg + 1]));
		Whiskers templ(R"({
			let  := 
			let  := (, )
			(, sub(, ) )
		})");
		templ("pos", m_context.newYulVariable());
		templ("end", m_context.newYulVariable());
		templ("freeMemory", freeMemory());
		templ("encode", abi.tupleEncoder({arguments.front()->annotation().type}, {parameterTypes.front()}));
		templ("nonIndexedArgs", IRVariable(*arguments.front()).commaSeparatedList());
		templ("log", "log" + to_string(logNumber));
		templ("indexedArgs", indexedArgs);
		m_code << templ.render();
		break;
	}
	case FunctionType::Kind::Creation:
	{
		solAssert(!functionType->gasSet(), "Gas limit set for contract creation.");
		solAssert(
			functionType->returnParameterTypes().size() == 1,
			"Constructor should return only one type"
		);
		TypePointers argumentTypes;
		string constructorParams;
		for (ASTPointer const& arg: arguments)
		{
			argumentTypes.push_back(arg->annotation().type);
			constructorParams += ", " + IRVariable{*arg}.commaSeparatedList();
		}
		ContractDefinition const* contract =
			&dynamic_cast(*functionType->returnParameterTypes().front()).contractDefinition();
		m_context.subObjectsCreated().insert(contract);
		Whiskers t(R"(
			let  := ()
			let  := add(, datasize("