solidity/libsolidity/Compiler.cpp

771 lines
27 KiB
C++
Raw Normal View History

2014-10-20 10:41:56 +00:00
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Solidity compiler.
2014-10-20 10:41:56 +00:00
*/
#include <libsolidity/Compiler.h>
#include <algorithm>
2015-01-15 19:04:24 +00:00
#include <boost/range/adaptor/reversed.hpp>
2014-11-07 01:06:37 +00:00
#include <libevmcore/Instruction.h>
#include <libevmasm/Assembly.h>
2015-07-31 17:23:31 +00:00
#include <libevmcore/Params.h>
2014-10-20 10:41:56 +00:00
#include <libsolidity/AST.h>
#include <libsolidity/ExpressionCompiler.h>
#include <libsolidity/CompilerUtils.h>
2014-10-20 10:41:56 +00:00
using namespace std;
using namespace dev;
using namespace dev::solidity;
2014-10-20 10:41:56 +00:00
2015-02-22 17:38:32 +00:00
/**
* Simple helper class to ensure that the stack height is the same at certain places in the code.
*/
class StackHeightChecker
{
public:
StackHeightChecker(CompilerContext const& _context):
2015-08-31 16:44:29 +00:00
m_context(_context), stackHeight(m_context.stackHeight()) {}
void check() { solAssert(m_context.stackHeight() == stackHeight, "I sense a disturbance in the stack."); }
2015-02-22 17:38:32 +00:00
private:
CompilerContext const& m_context;
unsigned stackHeight;
};
void Compiler::compileContract(
ContractDefinition const& _contract,
2015-09-11 13:25:00 +00:00
std::map<const ContractDefinition*, eth::Assembly const*> const& _contracts
)
2014-10-20 10:41:56 +00:00
{
m_context = CompilerContext();
2015-01-26 15:58:54 +00:00
{
CompilerContext::LocationSetter locationSetterRunTime(m_context, _contract);
initializeContext(_contract, _contracts);
appendFunctionSelector(_contract);
2015-07-31 17:23:31 +00:00
appendFunctionsWithoutCode();
2015-01-26 15:58:54 +00:00
}
2014-12-15 21:57:39 +00:00
// Swap the runtime context with the creation-time context
swap(m_context, m_runtimeContext);
CompilerContext::LocationSetter locationSetterCreationTime(m_context, _contract);
initializeContext(_contract, _contracts);
packIntoContractCreator(_contract, m_runtimeContext);
2015-06-01 10:32:59 +00:00
if (m_optimize)
m_context.optimise(m_optimizeRuns);
2015-10-06 12:13:07 +00:00
if (_contract.isLibrary())
{
solAssert(m_runtimeSub != size_t(-1), "");
m_context.injectVersionStampIntoSub(m_runtimeSub);
}
2014-12-15 21:57:39 +00:00
}
2014-11-19 09:24:22 +00:00
2015-07-31 17:23:31 +00:00
void Compiler::compileClone(
ContractDefinition const& _contract,
map<ContractDefinition const*, eth::Assembly const*> const& _contracts
2015-07-31 17:23:31 +00:00
)
{
m_context = CompilerContext(); // clear it just in case
initializeContext(_contract, _contracts);
appendInitAndConstructorCode(_contract);
//@todo determine largest return size of all runtime functions
2015-08-31 16:44:29 +00:00
eth::AssemblyItem runtimeSub = m_context.addSubroutine(cloneRuntime());
2015-07-31 17:23:31 +00:00
solAssert(runtimeSub.data() < numeric_limits<size_t>::max(), "");
m_runtimeSub = size_t(runtimeSub.data());
// stack contains sub size
m_context << eth::Instruction::DUP1 << runtimeSub << u256(0) << eth::Instruction::CODECOPY;
m_context << u256(0) << eth::Instruction::RETURN;
appendFunctionsWithoutCode();
if (m_optimize)
m_context.optimise(m_optimizeRuns);
}
2015-08-31 16:44:29 +00:00
eth::AssemblyItem Compiler::functionEntryLabel(FunctionDefinition const& _function) const
2015-05-26 09:27:59 +00:00
{
2015-08-31 16:44:29 +00:00
return m_runtimeContext.functionEntryLabelIfExists(_function);
2015-05-26 09:27:59 +00:00
}
void Compiler::initializeContext(
ContractDefinition const& _contract,
map<ContractDefinition const*, eth::Assembly const*> const& _compiledContracts
)
2014-12-15 21:57:39 +00:00
{
m_context.setCompiledContracts(_compiledContracts);
m_context.setInheritanceHierarchy(_contract.annotation().linearizedBaseContracts);
CompilerUtils(m_context).initialiseFreeMemoryPointer();
2014-11-19 09:24:22 +00:00
registerStateVariables(_contract);
m_context.resetVisitedNodes(&_contract);
2014-12-15 21:57:39 +00:00
}
2014-11-19 09:24:22 +00:00
2015-07-31 17:23:31 +00:00
void Compiler::appendInitAndConstructorCode(ContractDefinition const& _contract)
2014-12-15 21:57:39 +00:00
{
2015-01-27 13:32:59 +00:00
// Determine the arguments that are used for the base constructors.
std::vector<ContractDefinition const*> const& bases = _contract.annotation().linearizedBaseContracts;
2015-01-19 22:08:48 +00:00
for (ContractDefinition const* contract: bases)
{
2015-08-31 16:44:29 +00:00
if (FunctionDefinition const* constructor = contract->constructor())
for (auto const& modifier: constructor->modifiers())
{
auto baseContract = dynamic_cast<ContractDefinition const*>(
modifier->name()->annotation().referencedDeclaration);
if (baseContract)
2015-08-31 16:44:29 +00:00
if (m_baseArguments.count(baseContract->constructor()) == 0)
m_baseArguments[baseContract->constructor()] = &modifier->arguments();
}
2015-08-31 16:44:29 +00:00
for (ASTPointer<InheritanceSpecifier> const& base: contract->baseContracts())
2015-01-19 22:08:48 +00:00
{
ContractDefinition const* baseContract = dynamic_cast<ContractDefinition const*>(
base->name().annotation().referencedDeclaration
);
2015-01-19 22:08:48 +00:00
solAssert(baseContract, "");
2014-11-19 09:24:22 +00:00
2015-08-31 16:44:29 +00:00
if (m_baseArguments.count(baseContract->constructor()) == 0)
m_baseArguments[baseContract->constructor()] = &base->arguments();
}
2015-01-19 22:08:48 +00:00
}
// Initialization of state variables in base-to-derived order.
for (ContractDefinition const* contract: boost::adaptors::reverse(bases))
initializeStateVariables(*contract);
2015-08-31 16:44:29 +00:00
if (FunctionDefinition const* constructor = _contract.constructor())
appendConstructor(*constructor);
2015-08-31 16:44:29 +00:00
else if (auto c = m_context.nextConstructor(_contract))
appendBaseConstructor(*c);
2015-07-31 17:23:31 +00:00
}
void Compiler::packIntoContractCreator(ContractDefinition const& _contract, CompilerContext const& _runtimeContext)
{
appendInitAndConstructorCode(_contract);
2014-12-15 21:57:39 +00:00
2015-08-31 16:44:29 +00:00
eth::AssemblyItem runtimeSub = m_context.addSubroutine(_runtimeContext.assembly());
2015-06-01 10:32:59 +00:00
solAssert(runtimeSub.data() < numeric_limits<size_t>::max(), "");
m_runtimeSub = size_t(runtimeSub.data());
2015-07-31 17:23:31 +00:00
2014-12-15 21:57:39 +00:00
// stack contains sub size
2015-06-01 10:32:59 +00:00
m_context << eth::Instruction::DUP1 << runtimeSub << u256(0) << eth::Instruction::CODECOPY;
2014-11-19 09:24:22 +00:00
m_context << u256(0) << eth::Instruction::RETURN;
2014-12-15 21:57:39 +00:00
2015-01-27 13:32:59 +00:00
// note that we have to include the functions again because of absolute jump labels
2015-07-31 17:23:31 +00:00
appendFunctionsWithoutCode();
2014-12-15 21:57:39 +00:00
}
void Compiler::appendBaseConstructor(FunctionDefinition const& _constructor)
2015-01-19 22:08:48 +00:00
{
CompilerContext::LocationSetter locationSetter(m_context, _constructor);
2015-01-19 22:08:48 +00:00
FunctionType constructorType(_constructor);
2015-08-31 16:44:29 +00:00
if (!constructorType.parameterTypes().empty())
{
solAssert(m_baseArguments.count(&_constructor), "");
std::vector<ASTPointer<Expression>> const* arguments = m_baseArguments[&_constructor];
solAssert(arguments, "");
for (unsigned i = 0; i < arguments->size(); ++i)
2015-08-31 16:44:29 +00:00
compileExpression(*(arguments->at(i)), constructorType.parameterTypes()[i]);
}
_constructor.accept(*this);
2015-01-19 22:08:48 +00:00
}
void Compiler::appendConstructor(FunctionDefinition const& _constructor)
2014-12-15 21:57:39 +00:00
{
CompilerContext::LocationSetter locationSetter(m_context, _constructor);
2014-12-15 21:57:39 +00:00
// copy constructor arguments from code to memory and then to stack, they are supplied after the actual program
2015-08-31 16:44:29 +00:00
if (!_constructor.parameters().empty())
2014-12-15 21:57:39 +00:00
{
unsigned argumentSize = 0;
2015-08-31 16:44:29 +00:00
for (ASTPointer<VariableDeclaration> const& var: _constructor.parameters())
if (var->annotation().type->isDynamicallySized())
{
argumentSize = 0;
break;
}
else
argumentSize += var->annotation().type->calldataEncodedSize();
CompilerUtils(m_context).fetchFreeMemoryPointer();
if (argumentSize == 0)
{
// argument size is dynamic, use CODESIZE to determine it
m_context.appendProgramSize(); // program itself
// CODESIZE is program plus manually added arguments
m_context << eth::Instruction::CODESIZE << eth::Instruction::SUB;
}
else
m_context << u256(argumentSize);
2015-06-22 18:50:29 +00:00
// stack: <memptr> <argument size>
m_context << eth::Instruction::DUP1;
2014-12-15 21:57:39 +00:00
m_context.appendProgramSize();
m_context << eth::Instruction::DUP4 << eth::Instruction::CODECOPY;
m_context << eth::Instruction::DUP2 << eth::Instruction::ADD;
CompilerUtils(m_context).storeFreeMemoryPointer();
// stack: <memptr>
appendCalldataUnpacker(FunctionType(_constructor).parameterTypes(), true);
2014-12-15 21:57:39 +00:00
}
_constructor.accept(*this);
2014-12-15 21:57:39 +00:00
}
2014-11-19 09:24:22 +00:00
void Compiler::appendFunctionSelector(ContractDefinition const& _contract)
2014-10-20 10:41:56 +00:00
{
2015-08-31 16:44:29 +00:00
map<FixedHash<4>, FunctionTypePointer> interfaceFunctions = _contract.interfaceFunctions();
map<FixedHash<4>, const eth::AssemblyItem> callDataUnpackerEntryPoints;
2015-08-31 16:44:29 +00:00
FunctionDefinition const* fallback = _contract.fallbackFunction();
eth::AssemblyItem notFound = m_context.newTag();
// shortcut messages without data if we have many functions in order to be able to receive
// ether with constant gas
if (interfaceFunctions.size() > 5 || fallback)
{
m_context << eth::Instruction::CALLDATASIZE << eth::Instruction::ISZERO;
m_context.appendConditionalJumpTo(notFound);
}
// retrieve the function signature hash from the calldata
2015-01-29 21:50:20 +00:00
if (!interfaceFunctions.empty())
2015-02-14 23:11:51 +00:00
CompilerUtils(m_context).loadFromMemory(0, IntegerType(CompilerUtils::dataStartOffset * 8), true);
// stack now is: 1 0 <funhash>
for (auto const& it: interfaceFunctions)
{
callDataUnpackerEntryPoints.insert(std::make_pair(it.first, m_context.newTag()));
m_context << eth::dupInstruction(1) << u256(FixedHash<4>::Arith(it.first)) << eth::Instruction::EQ;
m_context.appendConditionalJumpTo(callDataUnpackerEntryPoints.at(it.first));
}
m_context.appendJumpTo(notFound);
m_context << notFound;
if (fallback)
2015-01-29 21:50:20 +00:00
{
eth::AssemblyItem returnTag = m_context.pushNewTag();
fallback->accept(*this);
m_context << returnTag;
2015-10-02 20:34:47 +00:00
appendReturnValuePacker(FunctionType(*fallback).returnParameterTypes(), _contract.isLibrary());
2015-01-29 21:50:20 +00:00
}
2015-10-06 20:55:38 +00:00
else if (_contract.isLibrary())
// Reject invalid library calls and ether sent to a library.
m_context.appendJumpTo(m_context.errorTag());
2015-01-29 21:50:20 +00:00
else
m_context << eth::Instruction::STOP; // function not found
for (auto const& it: interfaceFunctions)
{
2015-01-29 16:28:14 +00:00
FunctionTypePointer const& functionType = it.second;
solAssert(functionType->hasDeclaration(), "");
2015-08-31 16:44:29 +00:00
CompilerContext::LocationSetter locationSetter(m_context, functionType->declaration());
m_context << callDataUnpackerEntryPoints.at(it.first);
eth::AssemblyItem returnTag = m_context.pushNewTag();
m_context << CompilerUtils::dataStartOffset;
2015-08-31 16:44:29 +00:00
appendCalldataUnpacker(functionType->parameterTypes());
m_context.appendJumpTo(m_context.functionEntryLabel(functionType->declaration()));
m_context << returnTag;
2015-10-02 20:34:47 +00:00
appendReturnValuePacker(functionType->returnParameterTypes(), _contract.isLibrary());
}
}
void Compiler::appendCalldataUnpacker(TypePointers const& _typeParameters, bool _fromMemory)
{
// We do not check the calldata size, everything is zero-padded
2015-06-26 18:27:56 +00:00
//@todo this does not yet support nested dynamic arrays
2015-06-17 10:01:39 +00:00
// Retain the offset pointer as base_offset, the point from which the data offsets are computed.
m_context << eth::Instruction::DUP1;
for (TypePointer const& parameterType: _typeParameters)
2015-03-03 10:28:56 +00:00
{
// stack: v1 v2 ... v(k-1) base_offset current_offset
2015-10-02 20:34:47 +00:00
TypePointer type = parameterType->decodingType();
if (type->category() == Type::Category::Array)
{
2015-06-05 15:32:13 +00:00
auto const& arrayType = dynamic_cast<ArrayType const&>(*type);
2015-08-31 16:44:29 +00:00
solAssert(!arrayType.baseType()->isDynamicallySized(), "Nested arrays not yet implemented.");
2015-06-17 10:01:39 +00:00
if (_fromMemory)
{
2015-06-26 18:27:56 +00:00
solAssert(
2015-08-31 16:44:29 +00:00
arrayType.baseType()->isValueType(),
2015-06-26 18:27:56 +00:00
"Nested memory arrays not yet implemented here."
);
// @todo If base type is an array or struct, it is still calldata-style encoded, so
// we would have to convert it like below.
2015-06-17 10:01:39 +00:00
solAssert(arrayType.location() == DataLocation::Memory, "");
// compute data pointer
2015-06-22 18:50:29 +00:00
m_context << eth::Instruction::DUP1 << eth::Instruction::MLOAD;
m_context << eth::Instruction::DUP3 << eth::Instruction::ADD;
m_context << eth::Instruction::SWAP2 << eth::Instruction::SWAP1;
m_context << u256(0x20) << eth::Instruction::ADD;
2015-06-17 10:01:39 +00:00
}
else
2015-03-03 10:28:56 +00:00
{
2015-06-17 10:01:39 +00:00
// first load from calldata and potentially convert to memory if arrayType is memory
TypePointer calldataType = arrayType.copyForLocation(DataLocation::CallData, false);
if (calldataType->isDynamicallySized())
2015-06-05 15:32:13 +00:00
{
// put on stack: data_pointer length
CompilerUtils(m_context).loadFromMemoryDynamic(IntegerType(256), !_fromMemory);
// stack: base_offset data_offset next_pointer
m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP3 << eth::Instruction::ADD;
// stack: base_offset next_pointer data_pointer
2015-06-05 15:32:13 +00:00
// retrieve length
CompilerUtils(m_context).loadFromMemoryDynamic(IntegerType(256), !_fromMemory, true);
// stack: base_offset next_pointer length data_pointer
2015-06-05 15:32:13 +00:00
m_context << eth::Instruction::SWAP2;
// stack: base_offset data_pointer length next_pointer
2015-06-05 15:32:13 +00:00
}
else
{
// leave the pointer on the stack
m_context << eth::Instruction::DUP1;
2015-08-31 16:44:29 +00:00
m_context << u256(calldataType->calldataEncodedSize()) << eth::Instruction::ADD;
2015-06-17 10:01:39 +00:00
}
if (arrayType.location() == DataLocation::Memory)
{
// stack: base_offset calldata_ref [length] next_calldata
2015-06-17 10:01:39 +00:00
// copy to memory
// move calldata type up again
2015-08-31 16:44:29 +00:00
CompilerUtils(m_context).moveIntoStack(calldataType->sizeOnStack());
2015-06-17 10:01:39 +00:00
CompilerUtils(m_context).convertType(*calldataType, arrayType);
// fetch next pointer again
2015-08-31 16:44:29 +00:00
CompilerUtils(m_context).moveToStackTop(arrayType.sizeOnStack());
2015-06-05 15:32:13 +00:00
}
// move base_offset up
CompilerUtils(m_context).moveToStackTop(1 + arrayType.sizeOnStack());
m_context << eth::Instruction::SWAP1;
2015-03-03 10:28:56 +00:00
}
2015-06-05 15:32:13 +00:00
}
else
{
2015-03-03 10:28:56 +00:00
solAssert(!type->isDynamicallySized(), "Unknown dynamically sized type: " + type->toString());
2015-05-08 14:54:39 +00:00
CompilerUtils(m_context).loadFromMemoryDynamic(*type, !_fromMemory, true);
CompilerUtils(m_context).moveToStackTop(1 + type->sizeOnStack());
m_context << eth::Instruction::SWAP1;
}
// stack: v1 v2 ... v(k-1) v(k) base_offset mem_offset
2015-03-03 10:28:56 +00:00
}
m_context << eth::Instruction::POP << eth::Instruction::POP;
}
2015-10-02 20:34:47 +00:00
void Compiler::appendReturnValuePacker(TypePointers const& _typeParameters, bool _isLibrary)
{
CompilerUtils utils(m_context);
if (_typeParameters.empty())
2015-06-12 09:06:05 +00:00
m_context << eth::Instruction::STOP;
else
{
utils.fetchFreeMemoryPointer();
//@todo optimization: if we return a single memory array, there should be enough space before
// its data to add the needed parts and we avoid a memory copy.
2015-10-02 20:34:47 +00:00
utils.encodeToMemory(_typeParameters, _typeParameters, true, false, _isLibrary);
utils.toSizeAfterFreeMemoryPointer();
m_context << eth::Instruction::RETURN;
}
2014-10-20 10:41:56 +00:00
}
2014-11-19 09:24:22 +00:00
void Compiler::registerStateVariables(ContractDefinition const& _contract)
{
2015-08-31 16:44:29 +00:00
for (auto const& var: ContractType(_contract).stateVariables())
m_context.addStateVariable(*get<0>(var), get<1>(var), get<2>(var));
2014-11-19 09:24:22 +00:00
}
void Compiler::initializeStateVariables(ContractDefinition const& _contract)
{
2015-08-31 16:44:29 +00:00
for (ASTPointer<VariableDeclaration> const& variable: _contract.stateVariables())
if (variable->value() && !variable->isConstant())
2015-02-25 14:14:22 +00:00
ExpressionCompiler(m_context, m_optimize).appendStateVariableInitialization(*variable);
}
2015-01-27 13:32:59 +00:00
bool Compiler::visit(VariableDeclaration const& _variableDeclaration)
2015-01-26 15:58:54 +00:00
{
2015-01-27 13:32:59 +00:00
solAssert(_variableDeclaration.isStateVariable(), "Compiler visit to non-state variable declaration.");
CompilerContext::LocationSetter locationSetter(m_context, _variableDeclaration);
2015-01-27 13:32:59 +00:00
m_context.startFunction(_variableDeclaration);
2015-01-26 15:58:54 +00:00
m_breakTags.clear();
m_continueTags.clear();
if (_variableDeclaration.isConstant())
ExpressionCompiler(m_context, m_optimize).appendConstStateVariableAccessor(_variableDeclaration);
else
ExpressionCompiler(m_context, m_optimize).appendStateVariableAccessor(_variableDeclaration);
2015-01-27 13:32:59 +00:00
return false;
2015-01-26 15:58:54 +00:00
}
2014-12-06 00:06:24 +00:00
bool Compiler::visit(FunctionDefinition const& _function)
2014-10-20 10:41:56 +00:00
{
CompilerContext::LocationSetter locationSetter(m_context, _function);
2014-10-25 14:52:22 +00:00
2015-01-27 13:32:59 +00:00
m_context.startFunction(_function);
2014-10-25 14:52:22 +00:00
// stack upon entry: [return address] [arg0] [arg1] ... [argn]
// reserve additional slots: [retarg0] ... [retargm] [localvar0] ... [localvarp]
2014-10-20 10:41:56 +00:00
2015-08-31 16:44:29 +00:00
unsigned parametersSize = CompilerUtils::sizeOnStack(_function.parameters());
if (!_function.isConstructor())
// adding 1 for return address.
m_context.adjustStackOffset(parametersSize + 1);
2015-08-31 16:44:29 +00:00
for (ASTPointer<VariableDeclaration const> const& variable: _function.parameters())
{
2015-02-14 23:11:51 +00:00
m_context.addVariable(*variable, parametersSize);
parametersSize -= variable->annotation().type->sizeOnStack();
2015-01-23 01:35:27 +00:00
}
2015-08-31 16:44:29 +00:00
for (ASTPointer<VariableDeclaration const> const& variable: _function.returnParameters())
2015-06-24 15:25:36 +00:00
appendStackVariableInitialisation(*variable);
2015-08-31 16:44:29 +00:00
for (VariableDeclaration const* localVariable: _function.localVariables())
2015-06-24 15:25:36 +00:00
appendStackVariableInitialisation(*localVariable);
2014-10-20 10:41:56 +00:00
if (_function.isConstructor())
2015-08-31 16:44:29 +00:00
if (auto c = m_context.nextConstructor(dynamic_cast<ContractDefinition const&>(*_function.scope())))
appendBaseConstructor(*c);
m_returnTag = m_context.newTag();
m_breakTags.clear();
m_continueTags.clear();
m_stackCleanupForReturn = 0;
m_currentFunction = &_function;
m_modifierDepth = 0;
2015-01-23 01:35:27 +00:00
appendModifierOrFunctionCode();
2014-10-20 10:41:56 +00:00
m_context << m_returnTag;
2014-10-20 10:41:56 +00:00
// Now we need to re-shuffle the stack. For this we keep a record of the stack layout
// that shows the target positions of the elements, where "-1" denotes that this element needs
// to be removed from the stack.
// Note that the fact that the return arguments are of increasing index is vital for this
// algorithm to work.
2014-10-20 10:41:56 +00:00
2015-08-31 16:44:29 +00:00
unsigned const c_argumentsSize = CompilerUtils::sizeOnStack(_function.parameters());
unsigned const c_returnValuesSize = CompilerUtils::sizeOnStack(_function.returnParameters());
unsigned const c_localVariablesSize = CompilerUtils::sizeOnStack(_function.localVariables());
2014-12-08 17:19:25 +00:00
vector<int> stackLayout;
stackLayout.push_back(c_returnValuesSize); // target of return address
stackLayout += vector<int>(c_argumentsSize, -1); // discard all arguments
for (unsigned i = 0; i < c_returnValuesSize; ++i)
stackLayout.push_back(i);
stackLayout += vector<int>(c_localVariablesSize, -1);
2014-10-20 10:41:56 +00:00
solAssert(stackLayout.size() <= 17, "Stack too deep, try removing local variables.");
while (stackLayout.back() != int(stackLayout.size() - 1))
if (stackLayout.back() < 0)
{
m_context << eth::Instruction::POP;
stackLayout.pop_back();
}
else
{
m_context << eth::swapInstruction(stackLayout.size() - stackLayout.back() - 1);
swap(stackLayout[stackLayout.back()], stackLayout.back());
}
//@todo assert that everything is in place now
2014-10-20 10:41:56 +00:00
2015-08-31 16:44:29 +00:00
for (ASTPointer<VariableDeclaration const> const& variable: _function.parameters() + _function.returnParameters())
m_context.removeVariable(*variable);
2015-08-31 16:44:29 +00:00
for (VariableDeclaration const* localVariable: _function.localVariables())
m_context.removeVariable(*localVariable);
2014-10-20 10:41:56 +00:00
2015-03-08 10:43:17 +00:00
m_context.adjustStackOffset(-(int)c_returnValuesSize);
if (!_function.isConstructor())
m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction);
return false;
2014-10-20 10:41:56 +00:00
}
2014-12-06 00:06:24 +00:00
bool Compiler::visit(IfStatement const& _ifStatement)
2014-10-20 10:41:56 +00:00
{
2015-02-22 17:38:32 +00:00
StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _ifStatement);
2015-08-31 16:44:29 +00:00
compileExpression(_ifStatement.condition());
2015-05-12 15:50:41 +00:00
m_context << eth::Instruction::ISZERO;
eth::AssemblyItem falseTag = m_context.appendConditionalJump();
eth::AssemblyItem endTag = falseTag;
2015-08-31 16:44:29 +00:00
_ifStatement.trueStatement().accept(*this);
if (_ifStatement.falseStatement())
2015-05-12 15:50:41 +00:00
{
endTag = m_context.appendJumpToNew();
m_context << falseTag;
2015-08-31 16:44:29 +00:00
_ifStatement.falseStatement()->accept(*this);
2015-05-12 15:50:41 +00:00
}
m_context << endTag;
2015-02-22 17:38:32 +00:00
checker.check();
return false;
2014-10-20 10:41:56 +00:00
}
2014-12-06 00:06:24 +00:00
bool Compiler::visit(WhileStatement const& _whileStatement)
2014-10-20 10:41:56 +00:00
{
2015-02-22 17:38:32 +00:00
StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _whileStatement);
eth::AssemblyItem loopStart = m_context.newTag();
eth::AssemblyItem loopEnd = m_context.newTag();
m_continueTags.push_back(loopStart);
m_breakTags.push_back(loopEnd);
2014-10-20 10:41:56 +00:00
m_context << loopStart;
2015-08-31 16:44:29 +00:00
compileExpression(_whileStatement.condition());
m_context << eth::Instruction::ISZERO;
m_context.appendConditionalJumpTo(loopEnd);
2014-10-20 10:41:56 +00:00
2015-08-31 16:44:29 +00:00
_whileStatement.body().accept(*this);
2014-10-20 10:41:56 +00:00
m_context.appendJumpTo(loopStart);
m_context << loopEnd;
2014-10-20 10:41:56 +00:00
m_continueTags.pop_back();
m_breakTags.pop_back();
2015-02-22 17:38:32 +00:00
checker.check();
return false;
2014-10-20 10:41:56 +00:00
}
bool Compiler::visit(ForStatement const& _forStatement)
{
2015-02-22 17:38:32 +00:00
StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _forStatement);
eth::AssemblyItem loopStart = m_context.newTag();
eth::AssemblyItem loopEnd = m_context.newTag();
eth::AssemblyItem loopNext = m_context.newTag();
m_continueTags.push_back(loopNext);
m_breakTags.push_back(loopEnd);
2015-08-31 16:44:29 +00:00
if (_forStatement.initializationExpression())
_forStatement.initializationExpression()->accept(*this);
m_context << loopStart;
// if there is no terminating condition in for, default is to always be true
2015-08-31 16:44:29 +00:00
if (_forStatement.condition())
{
2015-08-31 16:44:29 +00:00
compileExpression(*_forStatement.condition());
m_context << eth::Instruction::ISZERO;
m_context.appendConditionalJumpTo(loopEnd);
}
2015-08-31 16:44:29 +00:00
_forStatement.body().accept(*this);
m_context << loopNext;
// for's loop expression if existing
2015-08-31 16:44:29 +00:00
if (_forStatement.loopExpression())
_forStatement.loopExpression()->accept(*this);
m_context.appendJumpTo(loopStart);
m_context << loopEnd;
m_continueTags.pop_back();
m_breakTags.pop_back();
2015-02-22 17:38:32 +00:00
checker.check();
return false;
}
bool Compiler::visit(Continue const& _continueStatement)
2014-10-20 10:41:56 +00:00
{
CompilerContext::LocationSetter locationSetter(m_context, _continueStatement);
if (!m_continueTags.empty())
m_context.appendJumpTo(m_continueTags.back());
return false;
2014-10-20 10:41:56 +00:00
}
bool Compiler::visit(Break const& _breakStatement)
2014-10-20 10:41:56 +00:00
{
CompilerContext::LocationSetter locationSetter(m_context, _breakStatement);
if (!m_breakTags.empty())
m_context.appendJumpTo(m_breakTags.back());
return false;
2014-10-20 10:41:56 +00:00
}
2014-12-06 00:06:24 +00:00
bool Compiler::visit(Return const& _return)
2014-10-20 10:41:56 +00:00
{
CompilerContext::LocationSetter locationSetter(m_context, _return);
//@todo modifications are needed to make this work with functions returning multiple values
2015-08-31 16:44:29 +00:00
if (Expression const* expression = _return.expression())
2014-10-20 10:41:56 +00:00
{
solAssert(_return.annotation().functionReturnParameters, "Invalid return parameters pointer.");
VariableDeclaration const& firstVariable = *_return.annotation().functionReturnParameters->parameters().front();
compileExpression(*expression, firstVariable.annotation().type);
CompilerUtils(m_context).moveToStackVariable(firstVariable);
2014-10-20 10:41:56 +00:00
}
2015-01-23 01:35:27 +00:00
for (unsigned i = 0; i < m_stackCleanupForReturn; ++i)
m_context << eth::Instruction::POP;
m_context.appendJumpTo(m_returnTag);
2015-01-23 01:35:27 +00:00
m_context.adjustStackOffset(m_stackCleanupForReturn);
return false;
2014-10-20 10:41:56 +00:00
}
2015-09-15 14:33:14 +00:00
bool Compiler::visit(Throw const& _throw)
{
CompilerContext::LocationSetter locationSetter(m_context, _throw);
m_context.appendJumpTo(m_context.errorTag());
return false;
}
2015-02-22 17:38:32 +00:00
bool Compiler::visit(VariableDeclarationStatement const& _variableDeclarationStatement)
2014-10-25 14:52:22 +00:00
{
2015-02-22 17:38:32 +00:00
StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _variableDeclarationStatement);
if (Expression const* expression = _variableDeclarationStatement.initialValue())
2014-10-25 14:52:22 +00:00
{
2015-10-09 18:44:56 +00:00
CompilerUtils utils(m_context);
compileExpression(*expression);
TypePointers valueTypes;
if (auto tupleType = dynamic_cast<TupleType const*>(expression->annotation().type.get()))
valueTypes = tupleType->components();
else
valueTypes = TypePointers{expression->annotation().type};
auto const& assignments = _variableDeclarationStatement.annotation().assignments;
solAssert(assignments.size() == valueTypes.size(), "");
for (size_t i = 0; i < assignments.size(); ++i)
{
size_t j = assignments.size() - i - 1;
VariableDeclaration const* varDecl = assignments[j];
if (!varDecl)
utils.popStackElement(*valueTypes[j]);
else
{
utils.convertType(*valueTypes[j], *varDecl->annotation().type);
utils.moveToStackVariable(*varDecl);
}
}
2014-10-25 14:52:22 +00:00
}
2015-02-22 17:38:32 +00:00
checker.check();
return false;
2014-10-25 14:52:22 +00:00
}
2014-12-06 00:06:24 +00:00
bool Compiler::visit(ExpressionStatement const& _expressionStatement)
2014-10-25 14:52:22 +00:00
{
2015-02-22 17:38:32 +00:00
StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _expressionStatement);
2015-08-31 16:44:29 +00:00
Expression const& expression = _expressionStatement.expression();
compileExpression(expression);
CompilerUtils(m_context).popStackElement(*expression.annotation().type);
2015-02-22 17:38:32 +00:00
checker.check();
return false;
2014-10-25 14:52:22 +00:00
}
bool Compiler::visit(PlaceholderStatement const& _placeholderStatement)
2015-01-23 01:35:27 +00:00
{
2015-02-22 17:38:32 +00:00
StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _placeholderStatement);
2015-01-23 01:35:27 +00:00
++m_modifierDepth;
appendModifierOrFunctionCode();
--m_modifierDepth;
2015-02-22 17:38:32 +00:00
checker.check();
2015-01-26 09:13:34 +00:00
return true;
2015-01-23 01:35:27 +00:00
}
2015-07-31 17:23:31 +00:00
void Compiler::appendFunctionsWithoutCode()
{
2015-08-31 16:44:29 +00:00
set<Declaration const*> functions = m_context.functionsWithoutCode();
2015-07-31 17:23:31 +00:00
while (!functions.empty())
{
for (Declaration const* function: functions)
{
m_context.setStackOffset(0);
function->accept(*this);
}
2015-08-31 16:44:29 +00:00
functions = m_context.functionsWithoutCode();
2015-07-31 17:23:31 +00:00
}
}
2015-01-23 01:35:27 +00:00
void Compiler::appendModifierOrFunctionCode()
{
solAssert(m_currentFunction, "");
2015-08-31 16:44:29 +00:00
if (m_modifierDepth >= m_currentFunction->modifiers().size())
m_currentFunction->body().accept(*this);
2015-01-23 01:35:27 +00:00
else
{
2015-08-31 16:44:29 +00:00
ASTPointer<ModifierInvocation> const& modifierInvocation = m_currentFunction->modifiers()[m_modifierDepth];
// constructor call should be excluded
if (dynamic_cast<ContractDefinition const*>(modifierInvocation->name()->annotation().referencedDeclaration))
{
++m_modifierDepth;
appendModifierOrFunctionCode();
--m_modifierDepth;
return;
}
2015-08-31 16:44:29 +00:00
ModifierDefinition const& modifier = m_context.functionModifier(modifierInvocation->name()->name());
CompilerContext::LocationSetter locationSetter(m_context, modifier);
2015-08-31 16:44:29 +00:00
solAssert(modifier.parameters().size() == modifierInvocation->arguments().size(), "");
for (unsigned i = 0; i < modifier.parameters().size(); ++i)
2015-01-23 01:35:27 +00:00
{
2015-08-31 16:44:29 +00:00
m_context.addVariable(*modifier.parameters()[i]);
compileExpression(
*modifierInvocation->arguments()[i],
modifier.parameters()[i]->annotation().type
2015-08-31 16:44:29 +00:00
);
2015-01-23 01:35:27 +00:00
}
2015-08-31 16:44:29 +00:00
for (VariableDeclaration const* localVariable: modifier.localVariables())
2015-06-24 15:25:36 +00:00
appendStackVariableInitialisation(*localVariable);
2015-01-23 01:35:27 +00:00
2015-08-31 16:44:29 +00:00
unsigned const c_stackSurplus = CompilerUtils::sizeOnStack(modifier.parameters()) +
CompilerUtils::sizeOnStack(modifier.localVariables());
2015-01-23 01:35:27 +00:00
m_stackCleanupForReturn += c_stackSurplus;
2015-08-31 16:44:29 +00:00
modifier.body().accept(*this);
2015-01-23 01:35:27 +00:00
for (unsigned i = 0; i < c_stackSurplus; ++i)
m_context << eth::Instruction::POP;
m_stackCleanupForReturn -= c_stackSurplus;
}
}
2015-06-24 15:25:36 +00:00
void Compiler::appendStackVariableInitialisation(VariableDeclaration const& _variable)
{
CompilerContext::LocationSetter location(m_context, _variable);
m_context.addVariable(_variable);
CompilerUtils(m_context).pushZeroValue(*_variable.annotation().type);
2015-06-24 15:25:36 +00:00
}
2015-01-23 01:35:27 +00:00
void Compiler::compileExpression(Expression const& _expression, TypePointer const& _targetType)
{
2015-02-25 14:14:22 +00:00
ExpressionCompiler expressionCompiler(m_context, m_optimize);
expressionCompiler.compile(_expression);
2015-01-23 01:35:27 +00:00
if (_targetType)
CompilerUtils(m_context).convertType(*_expression.annotation().type, *_targetType);
2014-10-20 10:41:56 +00:00
}
2015-07-31 17:23:31 +00:00
2015-08-31 16:44:29 +00:00
eth::Assembly Compiler::cloneRuntime()
2015-07-31 17:23:31 +00:00
{
eth::Assembly a;
a << eth::Instruction::CALLDATASIZE;
a << u256(0) << eth::Instruction::DUP1 << eth::Instruction::CALLDATACOPY;
//@todo adjust for larger return values, make this dynamic.
a << u256(0x20) << u256(0) << eth::Instruction::CALLDATASIZE;
// unfortunately, we have to send the value again, so that CALLVALUE returns the correct value
// in the callcoded contract.
a << u256(0) << eth::Instruction::CALLVALUE;
2015-07-31 17:23:31 +00:00
// this is the address which has to be substituted by the linker.
//@todo implement as special "marker" AssemblyItem.
a << u256("0xcafecafecafecafecafecafecafecafecafecafe");
a << u256(eth::c_callGas + eth::c_callValueTransferGas + 10) << eth::Instruction::GAS << eth::Instruction::SUB;
2015-07-31 17:23:31 +00:00
a << eth::Instruction::CALLCODE;
2015-08-20 18:02:38 +00:00
//Propagate error condition (if CALLCODE pushes 0 on stack).
a << eth::Instruction::ISZERO;
a.appendJumpI(a.errorTag());
2015-07-31 17:23:31 +00:00
//@todo adjust for larger return values, make this dynamic.
a << u256(0x20) << u256(0) << eth::Instruction::RETURN;
return a;
}