implement immutable variables codegen (#70)

This commit is contained in:
Cyrill Leutwiler
2024-10-10 13:33:00 +02:00
committed by GitHub
parent 8b7fe8e3d7
commit d5d419cefc
24 changed files with 920 additions and 510 deletions
Generated
+350 -350
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -67,7 +67,7 @@ log = { version = "0.4" }
# polkadot-sdk and friends
codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
scale-info = { version = "2.11.1", default-features = false }
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "c77095f51119d2eccdc54d2f3518bed0ffbd6d53" }
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "fe0bfb79f4c883abbc3214519d19e46617c20bd2" }
# llvm
[workspace.dependencies.inkwell]
+8 -8
View File
@@ -1,10 +1,10 @@
{
"Baseline": 912,
"Computation": 4413,
"DivisionArithmetics": 40689,
"ERC20": 54374,
"Events": 1726,
"FibonacciIterative": 3015,
"Flipper": 3612,
"SHA1": 32865
"Baseline": 962,
"Computation": 4463,
"DivisionArithmetics": 40756,
"ERC20": 54427,
"Events": 1792,
"FibonacciIterative": 3065,
"Flipper": 3665,
"SHA1": 32923
}
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
/* runner.json
{
"differential": true,
"actions": [
{
"Upload": {
"code": {
"Solidity": {
"contract": "ImmutablesTester"
}
}
}
},
{
"Instantiate": {
"code": {
"Solidity": {
"contract": "Immutables"
}
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
}
}
}
]
}
*/
contract ImmutablesTester {
// Read should work in the runtime code
uint public immutable foo;
// Read should work in the runtime code
uint public immutable bar;
// Read should work in the runtime code
uint public immutable zoo;
// Assign and read should work in the constructor
constructor(uint _foo) payable {
foo = _foo;
bar = foo + 1;
zoo = bar + 2;
assert(zoo == _foo + 3);
}
}
contract Immutables {
fallback() external {
ImmutablesTester tester = new ImmutablesTester(127);
assert(tester.foo() == 127);
assert(tester.bar() == tester.foo() + 1);
assert(tester.zoo() == tester.bar() + 2);
}
}
+1
View File
@@ -42,6 +42,7 @@ test_spec!(create, "CreateB", "Create.sol");
test_spec!(call, "Caller", "Call.sol");
test_spec!(transfer, "Transfer", "Transfer.sol");
test_spec!(return_data_oob, "ReturnDataOob", "ReturnDataOob.sol");
test_spec!(immutables, "Immutables", "Immutables.sol");
fn instantiate(path: &str, contract: &str) -> Vec<SpecsAction> {
vec![Instantiate {
+2
View File
@@ -27,9 +27,11 @@ pub use self::polkavm::context::function::llvm_runtime::LLVMRuntime as PolkaVMLL
pub use self::polkavm::context::function::r#return::Return as PolkaVMFunctionReturn;
pub use self::polkavm::context::function::runtime::deploy_code::DeployCode as PolkaVMDeployCodeFunction;
pub use self::polkavm::context::function::runtime::entry::Entry as PolkaVMEntryFunction;
pub use self::polkavm::context::function::runtime::immutable_data_load::ImmutableDataLoad as PolkaVMImmutableDataLoadFunction;
pub use self::polkavm::context::function::runtime::runtime_code::RuntimeCode as PolkaVMRuntimeCodeFunction;
pub use self::polkavm::context::function::runtime::FUNCTION_DEPLOY_CODE as PolkaVMFunctionDeployCode;
pub use self::polkavm::context::function::runtime::FUNCTION_ENTRY as PolkaVMFunctionEntry;
pub use self::polkavm::context::function::runtime::FUNCTION_LOAD_IMMUTABLE_DATA as PolkaVMFunctionImmutableDataLoad;
pub use self::polkavm::context::function::runtime::FUNCTION_RUNTIME_CODE as PolkaVMFunctionRuntimeCode;
pub use self::polkavm::context::function::yul_data::YulData as PolkaVMFunctionYulData;
pub use self::polkavm::context::function::Function as PolkaVMFunction;
@@ -29,6 +29,8 @@ pub mod imports {
pub static DEPOSIT_EVENT: &str = "deposit_event";
pub static GET_IMMUTABLE_DATA: &str = "get_immutable_data";
pub static GET_STORAGE: &str = "get_storage";
pub static HASH_KECCAK_256: &str = "hash_keccak_256";
@@ -47,11 +49,13 @@ pub mod imports {
pub static SET_STORAGE: &str = "set_storage";
pub static SET_IMMUTABLE_DATA: &str = "set_immutable_data";
pub static VALUE_TRANSFERRED: &str = "value_transferred";
/// All imported runtime API symbols.
/// Useful for configuring common attributes and linkage.
pub static IMPORTS: [&str; 18] = [
pub static IMPORTS: [&str; 20] = [
ADDRESS,
BALANCE,
BLOCK_NUMBER,
@@ -60,6 +64,7 @@ pub mod imports {
CHAIN_ID,
CODE_SIZE,
DEPOSIT_EVENT,
GET_IMMUTABLE_DATA,
GET_STORAGE,
HASH_KECCAK_256,
INPUT,
@@ -68,6 +73,7 @@ pub mod imports {
RETURN,
RETURNDATACOPY,
RETURNDATASIZE,
SET_IMMUTABLE_DATA,
SET_STORAGE,
VALUE_TRANSFERRED,
];
@@ -91,7 +91,8 @@ impl<'ctx> Function<'ctx> {
|| (name.starts_with("__")
&& name != self::runtime::FUNCTION_ENTRY
&& name != self::runtime::FUNCTION_DEPLOY_CODE
&& name != self::runtime::FUNCTION_RUNTIME_CODE)
&& name != self::runtime::FUNCTION_RUNTIME_CODE
&& name != self::runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
}
/// Checks whether the function is related to the near call ABI.
@@ -31,6 +31,18 @@ impl Entry {
where
D: Dependency + Clone,
{
context.declare_global(
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER,
context.word_type().array_type(0),
AddressSpace::Stack,
);
context.declare_global(
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE,
context.xlen_type(),
AddressSpace::Stack,
);
let calldata_type = context.array_type(context.byte_type(), Self::MAX_CALLDATA_SIZE);
context.set_global(
crate::polkavm::GLOBAL_CALLDATA_POINTER,
@@ -0,0 +1,116 @@
//! The immutable data runtime function.
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::function::runtime;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::WriteLLVM;
use crate::polkavm::{runtime_api, Dependency};
/// A function for requesting the immutable data from the runtime.
/// This is a special function that is only used by the front-end generated code.
///
/// The runtime API is called lazily and subsequent calls are no-ops.
///
/// The bytes written is asserted to match the expected length.
/// This should never fail; the length is known.
/// However, this is a one time assertion, hence worth it.
#[derive(Debug)]
pub struct ImmutableDataLoad;
impl<D> WriteLLVM<D> for ImmutableDataLoad
where
D: Dependency + Clone,
{
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
context.add_function(
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
context.void_type().fn_type(Default::default(), false),
0,
Some(inkwell::module::Linkage::Private),
)?;
Ok(())
}
fn into_llvm(self, context: &mut Context<D>) -> anyhow::Result<()> {
context.set_current_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)?;
context.set_basic_block(context.current_function().borrow().entry_block());
let immutable_data_size_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
.value
.as_pointer_value();
let immutable_data_size = context.build_load(
Pointer::new(
context.xlen_type(),
AddressSpace::Stack,
immutable_data_size_pointer,
),
"immutable_data_size_load",
)?;
let load_immutable_data_block = context.append_basic_block("load_immutables_block");
let return_block = context.current_function().borrow().return_block();
let immutable_data_size_is_zero = context.builder().build_int_compare(
inkwell::IntPredicate::EQ,
context.xlen_type().const_zero(),
immutable_data_size.into_int_value(),
"immutable_data_size_is_zero",
)?;
context.build_conditional_branch(
immutable_data_size_is_zero,
return_block,
load_immutable_data_block,
)?;
context.set_basic_block(load_immutable_data_block);
let output_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
context.build_runtime_call(
runtime_api::imports::GET_IMMUTABLE_DATA,
&[
context
.builder()
.build_ptr_to_int(output_pointer, context.xlen_type(), "ptr_to_xlen")?
.into(),
context
.builder()
.build_ptr_to_int(
immutable_data_size_pointer,
context.xlen_type(),
"ptr_to_xlen",
)?
.into(),
],
);
let bytes_written = context.builder().build_load(
context.xlen_type(),
immutable_data_size_pointer,
"bytes_written",
)?;
context.builder().build_store(
immutable_data_size_pointer,
context.xlen_type().const_zero(),
)?;
let overflow_block = context.append_basic_block("immutable_data_overflow");
let is_overflow = context.builder().build_int_compare(
inkwell::IntPredicate::UGT,
immutable_data_size.into_int_value(),
bytes_written.into_int_value(),
"is_overflow",
)?;
context.build_conditional_branch(is_overflow, overflow_block, return_block)?;
context.set_basic_block(overflow_block);
context.build_call(context.intrinsics().trap, &[], "invalid_trap");
context.build_unreachable();
context.set_basic_block(return_block);
context.build_return(None);
Ok(())
}
}
@@ -2,6 +2,7 @@
pub mod deploy_code;
pub mod entry;
pub mod immutable_data_load;
pub mod runtime_code;
/// The main entry function name.
@@ -12,3 +13,6 @@ pub const FUNCTION_DEPLOY_CODE: &str = "__deploy";
/// The runtime code function name.
pub const FUNCTION_RUNTIME_CODE: &str = "__runtime";
/// The immutable data load function name.
pub const FUNCTION_LOAD_IMMUTABLE_DATA: &str = "__immutable_data_load";
@@ -51,4 +51,31 @@ impl<'ctx> Global<'ctx> {
global
}
/// Construct an external global.
pub fn declare<D, T>(
context: &mut Context<'ctx, D>,
r#type: T,
address_space: AddressSpace,
name: &str,
) -> Self
where
D: PolkaVMDependency + Clone,
T: BasicType<'ctx>,
{
let r#type = r#type.as_basic_type_enum();
let value = context
.module()
.add_global(r#type, Some(address_space.into()), name);
let global = Self { r#type, value };
global.value.set_linkage(inkwell::module::Linkage::External);
global
.value
.set_visibility(inkwell::GlobalVisibility::Default);
global.value.set_externally_initialized(true);
global
}
}
@@ -162,6 +162,18 @@ where
})
}
fn link_immutable_data(&self, contract_path: &str) -> anyhow::Result<()> {
let size = self.solidity().immutables_size() as u32;
let exports = revive_runtime_api::immutable_data::module(self.llvm(), size);
self.module.link_in_module(exports).map_err(|error| {
anyhow::anyhow!(
"The contract `{}` immutable data module linking error: {}",
contract_path,
error
)
})
}
/// Configure the PolkaVM minimum stack size.
fn set_polkavm_stack_size(
llvm: &'ctx inkwell::context::Context,
@@ -239,6 +251,7 @@ where
let module_clone = self.module.clone();
self.link_polkavm_exports(contract_path)?;
self.link_immutable_data(contract_path)?;
let target_machine = TargetMachine::new(Target::PVM, self.optimizer.settings())?;
target_machine.set_target_data(self.module());
@@ -381,6 +394,15 @@ where
}
}
/// Declare an external global.
pub fn declare_global<T>(&mut self, name: &str, r#type: T, address_space: AddressSpace)
where
T: BasicType<'ctx> + Clone + Copy,
{
let global = Global::declare(self, r#type, address_space, name);
self.globals.insert(name.to_owned(), global);
}
/// Returns the LLVM intrinsics collection reference.
pub fn intrinsics(&self) -> &Intrinsics<'ctx> {
&self.intrinsics
@@ -17,7 +17,7 @@ impl SolidityData {
Self::default()
}
/// Returns the current number of immutables values in the contract.
/// Returns the current size of immutable values in the contract.
pub fn immutables_size(&self) -> usize {
self.immutables.len() * revive_common::BYTE_LENGTH_WORD
}
@@ -1,14 +1,19 @@
//! Translates the contract immutable operations.
use inkwell::types::BasicType;
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::code_type::CodeType;
use crate::polkavm::context::function::runtime;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
/// Translates the contract immutable load.
/// In the deploy code the values are read from the auxiliary heap.
/// In the runtime code they are requested from the system contract.
///
/// In deploy code the values are read from the stack.
///
/// In runtime code they are loaded lazily with the `get_immutable_data` syscall.
pub fn load<'ctx, D>(
context: &mut Context<'ctx, D>,
index: inkwell::values::IntValue<'ctx>,
@@ -20,38 +25,27 @@ where
None => {
anyhow::bail!("Immutables are not available if the contract part is undefined");
}
Some(CodeType::Deploy) => {
let index_double = context.builder().build_int_mul(
index,
context.word_const(2),
"immutable_load_index_double",
)?;
let offset_absolute = context.builder().build_int_add(
index_double,
context.word_const(
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA
+ (3 * revive_common::BYTE_LENGTH_WORD) as u64,
),
"immutable_offset_absolute",
)?;
let immutable_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
offset_absolute,
"immutable_pointer",
);
context.build_load(immutable_pointer, "immutable_value")
}
Some(CodeType::Deploy) => load_from_memory(context, index),
Some(CodeType::Runtime) => {
todo!()
context.build_call(
context
.get_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
.expect("is always declared for runtime code")
.borrow()
.declaration(),
&[],
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
);
load_from_memory(context, index)
}
}
}
/// Translates the contract immutable store.
/// In the deploy code the values are written to the auxiliary heap at the predefined offset,
/// being prepared for returning to the system contract for saving.
///
/// In deploy code the values are written to the stack at the predefined offset,
/// being prepared for storing them using the `set_immutable_data` syscall.
///
/// Ignored in the runtime code.
pub fn store<'ctx, D>(
context: &mut Context<'ctx, D>,
@@ -66,46 +60,48 @@ where
anyhow::bail!("Immutables are not available if the contract part is undefined");
}
Some(CodeType::Deploy) => {
let index_double = context.builder().build_int_mul(
index,
context.word_const(2),
"immutable_load_index_double",
)?;
let index_offset_absolute = context.builder().build_int_add(
index_double,
context.word_const(
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA
+ (2 * revive_common::BYTE_LENGTH_WORD) as u64,
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
let immutable_pointer = context.build_gep(
Pointer::new(
context.word_type(),
AddressSpace::Stack,
immutable_data_pointer,
),
"index_offset_absolute",
)?;
let index_offset_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
index_offset_absolute,
"immutable_index_pointer",
&[index],
context.word_type().as_basic_type_enum(),
"immutable_variable_pointer",
);
context.build_store(index_offset_pointer, index)?;
let value_offset_absolute = context.builder().build_int_add(
index_offset_absolute,
context.word_const(revive_common::BYTE_LENGTH_WORD as u64),
"value_offset_absolute",
)?;
let value_offset_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
value_offset_absolute,
"immutable_value_pointer",
);
context.build_store(value_offset_pointer, value)?;
Ok(())
context.build_store(immutable_pointer, value)
}
Some(CodeType::Runtime) => {
anyhow::bail!("Immutable writes are not available in the runtime code");
}
}
}
pub fn load_from_memory<'ctx, D>(
context: &mut Context<'ctx, D>,
index: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
let immutable_pointer = context.build_gep(
Pointer::new(
context.word_type(),
AddressSpace::Stack,
immutable_data_pointer,
),
&[index],
context.word_type().as_basic_type_enum(),
"immutable_variable_pointer",
);
context.build_load(immutable_pointer, "immutable_value")
}
+58 -3
View File
@@ -1,7 +1,10 @@
//! Translates the transaction return operations.
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::code_type::CodeType;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm::{runtime_api, Dependency};
/// Translates the `return` instruction.
pub fn r#return<'ctx, D>(
@@ -12,8 +15,60 @@ pub fn r#return<'ctx, D>(
where
D: Dependency + Clone,
{
if context.code_type().is_none() {
anyhow::bail!("Return is not available if the contract part is undefined");
match context.code_type() {
None => anyhow::bail!("Return is not available if the contract part is undefined"),
Some(CodeType::Deploy) => {
let immutable_data_size_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
.value
.as_pointer_value();
let immutable_data_size = context.build_load(
Pointer::new(
context.xlen_type(),
AddressSpace::Stack,
immutable_data_size_pointer,
),
"immutable_data_size_load",
)?;
let write_immutable_data_block = context.append_basic_block("write_immutables_block");
let join_return_block = context.append_basic_block("join_return_block");
let immutable_data_size_is_zero = context.builder().build_int_compare(
inkwell::IntPredicate::EQ,
context.xlen_type().const_zero(),
immutable_data_size.into_int_value(),
"immutable_data_size_is_zero",
)?;
context.build_conditional_branch(
immutable_data_size_is_zero,
join_return_block,
write_immutable_data_block,
)?;
context.set_basic_block(write_immutable_data_block);
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
context.build_runtime_call(
runtime_api::imports::SET_IMMUTABLE_DATA,
&[
context
.builder()
.build_ptr_to_int(
immutable_data_pointer,
context.xlen_type(),
"immutable_data_pointer_to_xlen",
)?
.into(),
immutable_data_size,
],
);
context.build_unconditional_branch(join_return_block);
context.set_basic_block(join_return_block);
}
Some(CodeType::Runtime) => {}
}
context.build_exit(
+3 -1
View File
@@ -12,4 +12,6 @@ riscv-64 = []
[dependencies]
anyhow = { workspace = true }
inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] }
inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] }
revive-common = { workspace = true }
+89
View File
@@ -0,0 +1,89 @@
//! Allocates memory for the immutable data in a separate module.
//!
//! Because we only know how many immutable variables were set after
//! translating the whole contract code, we want to set the size at
//! last. However, array types need a size upon declaration.
//!
//! A simple work around is to replace it during link time.
//! To quote the [LLVM docs][0]:
//!
//! > For global variable declarations [..] the allocation size and
//! > alignment of the definition it resolves to must be greater than
//! > or equal to that of the declaration [..]
//!
//! To adhere to this we initially declare a length of 0 in
//! `revive-llvm-context`.
//!
//! [0]: https://llvm.org/docs/LangRef.html#global-variables
/// The immutable data module name.
pub static MODULE_NAME: &str = "__evm_immutables";
/// The immutable data global pointer.
pub static GLOBAL_IMMUTABLE_DATA_POINTER: &str = "__immutable_data_ptr";
/// The immutable data global size.
pub static GLOBAL_IMMUTABLE_DATA_SIZE: &str = "__immutable_data_size";
/// The immutable data maximum size in bytes.
pub static IMMUTABLE_DATA_MAX_SIZE: u32 = 4 * 1024;
/// Returns the immutable data global type.
pub fn data_type(context: &inkwell::context::Context, size: u32) -> inkwell::types::ArrayType {
context
.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.array_type(size)
}
/// Returns the immutable data size global type.
pub fn size_type(context: &inkwell::context::Context) -> inkwell::types::IntType {
context.custom_width_int_type(revive_common::BIT_LENGTH_X32 as u32)
}
/// Creates a LLVM module with the immutable data and its `size` in bytes.
pub fn module(context: &inkwell::context::Context, size: u32) -> inkwell::module::Module {
let module = context.create_module(MODULE_NAME);
let length = size / revive_common::BYTE_LENGTH_WORD as u32;
let immutable_data = module.add_global(
data_type(context, length),
Default::default(),
GLOBAL_IMMUTABLE_DATA_POINTER,
);
immutable_data.set_linkage(inkwell::module::Linkage::External);
immutable_data.set_visibility(inkwell::GlobalVisibility::Default);
immutable_data.set_initializer(&data_type(context, length).get_undef());
let immutable_data_size = module.add_global(
size_type(context),
Default::default(),
GLOBAL_IMMUTABLE_DATA_SIZE,
);
immutable_data_size.set_linkage(inkwell::module::Linkage::External);
immutable_data_size.set_visibility(inkwell::GlobalVisibility::Default);
immutable_data_size.set_initializer(&size_type(context).const_int(size as u64, false));
module
}
#[cfg(test)]
mod tests {
use crate::immutable_data::*;
#[test]
fn it_works() {
inkwell::targets::Target::initialize_riscv(&Default::default());
let context = inkwell::context::Context::create();
let size = 512;
let module = crate::immutable_data::module(&context, size);
let immutable_data_pointer = module.get_global(GLOBAL_IMMUTABLE_DATA_POINTER).unwrap();
assert_eq!(
immutable_data_pointer.get_initializer().unwrap(),
data_type(&context, size / 32).get_undef()
);
let immutable_data_size = module.get_global(GLOBAL_IMMUTABLE_DATA_SIZE).unwrap();
assert_eq!(
immutable_data_size.get_initializer().unwrap(),
size_type(&context).const_int(size as u64, false)
);
}
}
+1
View File
@@ -7,5 +7,6 @@
//! [1]: [https://docs.rs/pallet-contracts/26.0.0/pallet_contracts/api_doc/index.html]
pub mod calling_convention;
pub mod immutable_data;
pub mod polkavm_exports;
pub mod polkavm_imports;
+4
View File
@@ -59,6 +59,10 @@ POLKAVM_IMPORT(void, return_data_copy, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, return_data_size, uint32_t)
POLKAVM_IMPORT(void, set_immutable_data, uint32_t, uint32_t);
POLKAVM_IMPORT(void, get_immutable_data, uint32_t, uint32_t);
POLKAVM_IMPORT(void, value_transferred, uint32_t)
POLKAVM_IMPORT(uint32_t, set_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
@@ -199,6 +199,7 @@ where
revive_llvm_context::PolkaVMDummyLLVMWritable::default(),
)
.declare(context)?;
revive_llvm_context::PolkaVMImmutableDataLoadFunction.declare(context)?;
entry.into_llvm(context)?;
@@ -266,6 +267,7 @@ where
revive_llvm_context::PolkaVMCodeType::Runtime,
))
.into_llvm(context)?;
revive_llvm_context::PolkaVMImmutableDataLoadFunction.into_llvm(context)?;
Ok(())
}
@@ -45,7 +45,7 @@ impl Element {
fn pop_arguments_llvm<'ctx, D>(
&mut self,
context: &mut revive_llvm_context::PolkaVMContext<'ctx, D>,
) -> Vec<inkwell::values::BasicValueEnum<'ctx>>
) -> anyhow::Result<Vec<inkwell::values::BasicValueEnum<'ctx>>>
where
D: revive_llvm_context::PolkaVMDependency + Clone,
{
@@ -57,15 +57,13 @@ impl Element {
[self.stack.elements.len() + input_size - output_size - 1 - index]
.to_llvm()
.into_pointer_value();
let value = context
.build_load(
revive_llvm_context::PolkaVMPointer::new_stack_field(context, pointer),
format!("argument_{index}").as_str(),
)
.unwrap();
let value = context.build_load(
revive_llvm_context::PolkaVMPointer::new_stack_field(context, pointer),
format!("argument_{index}").as_str(),
)?;
arguments.push(value);
}
arguments
Ok(arguments)
}
}
@@ -426,7 +424,7 @@ where
InstructionName::JUMPDEST => Ok(None),
InstructionName::ADD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::addition(
context,
arguments[0].into_int_value(),
@@ -435,7 +433,7 @@ where
.map(Some)
}
InstructionName::SUB => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::subtraction(
context,
arguments[0].into_int_value(),
@@ -444,7 +442,7 @@ where
.map(Some)
}
InstructionName::MUL => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::multiplication(
context,
arguments[0].into_int_value(),
@@ -453,7 +451,7 @@ where
.map(Some)
}
InstructionName::DIV => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::division(
context,
arguments[0].into_int_value(),
@@ -462,7 +460,7 @@ where
.map(Some)
}
InstructionName::MOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::remainder(
context,
arguments[0].into_int_value(),
@@ -471,7 +469,7 @@ where
.map(Some)
}
InstructionName::SDIV => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::division_signed(
context,
arguments[0].into_int_value(),
@@ -480,7 +478,7 @@ where
.map(Some)
}
InstructionName::SMOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::remainder_signed(
context,
arguments[0].into_int_value(),
@@ -490,7 +488,7 @@ where
}
InstructionName::LT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -500,7 +498,7 @@ where
.map(Some)
}
InstructionName::GT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -510,7 +508,7 @@ where
.map(Some)
}
InstructionName::EQ => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -520,7 +518,7 @@ where
.map(Some)
}
InstructionName::ISZERO => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -530,7 +528,7 @@ where
.map(Some)
}
InstructionName::SLT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -540,7 +538,7 @@ where
.map(Some)
}
InstructionName::SGT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -551,7 +549,7 @@ where
}
InstructionName::OR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::or(
context,
arguments[0].into_int_value(),
@@ -560,7 +558,7 @@ where
.map(Some)
}
InstructionName::XOR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::xor(
context,
arguments[0].into_int_value(),
@@ -569,7 +567,7 @@ where
.map(Some)
}
InstructionName::NOT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::xor(
context,
arguments[0].into_int_value(),
@@ -578,7 +576,7 @@ where
.map(Some)
}
InstructionName::AND => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::and(
context,
arguments[0].into_int_value(),
@@ -587,7 +585,7 @@ where
.map(Some)
}
InstructionName::SHL => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_left(
context,
arguments[0].into_int_value(),
@@ -596,7 +594,7 @@ where
.map(Some)
}
InstructionName::SHR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_right(
context,
arguments[0].into_int_value(),
@@ -605,7 +603,7 @@ where
.map(Some)
}
InstructionName::SAR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_right_arithmetic(
context,
arguments[0].into_int_value(),
@@ -614,7 +612,7 @@ where
.map(Some)
}
InstructionName::BYTE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::byte(
context,
arguments[0].into_int_value(),
@@ -624,7 +622,7 @@ where
}
InstructionName::ADDMOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::add_mod(
context,
arguments[0].into_int_value(),
@@ -634,7 +632,7 @@ where
.map(Some)
}
InstructionName::MULMOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::mul_mod(
context,
arguments[0].into_int_value(),
@@ -644,7 +642,7 @@ where
.map(Some)
}
InstructionName::EXP => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::exponent(
context,
arguments[0].into_int_value(),
@@ -653,7 +651,7 @@ where
.map(Some)
}
InstructionName::SIGNEXTEND => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::sign_extend(
context,
arguments[0].into_int_value(),
@@ -663,7 +661,7 @@ where
}
InstructionName::SHA3 | InstructionName::KECCAK256 => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_crypto::sha3(
context,
arguments[0].into_int_value(),
@@ -673,7 +671,7 @@ where
}
InstructionName::MLOAD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::load(
context,
arguments[0].into_int_value(),
@@ -681,7 +679,7 @@ where
.map(Some)
}
InstructionName::MSTORE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::store(
context,
arguments[0].into_int_value(),
@@ -690,7 +688,7 @@ where
.map(|_| None)
}
InstructionName::MSTORE8 => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::store_byte(
context,
arguments[0].into_int_value(),
@@ -699,7 +697,7 @@ where
.map(|_| None)
}
InstructionName::MCOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let destination = revive_llvm_context::PolkaVMPointer::new_with_offset(
context,
revive_llvm_context::PolkaVMAddressSpace::Heap,
@@ -725,7 +723,7 @@ where
}
InstructionName::SLOAD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::load(
context,
arguments[0].into_int_value(),
@@ -733,7 +731,7 @@ where
.map(Some)
}
InstructionName::SSTORE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::store(
context,
arguments[0].into_int_value(),
@@ -742,7 +740,7 @@ where
.map(|_| None)
}
InstructionName::TLOAD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::transient_load(
context,
arguments[0].into_int_value(),
@@ -750,7 +748,7 @@ where
.map(Some)
}
InstructionName::TSTORE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::transient_store(
context,
arguments[0].into_int_value(),
@@ -766,27 +764,28 @@ where
let offset = context
.solidity_mut()
.get_or_allocate_immutable(key.as_str());
.get_or_allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.word_const(offset as u64);
let index = context.xlen_type().const_int(offset as u64, false);
revive_llvm_context::polkavm_evm_immutable::load(context, index).map(Some)
}
InstructionName::ASSIGNIMMUTABLE => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let key = self
.instruction
.value
.ok_or_else(|| anyhow::anyhow!("Instruction value missing"))?;
let offset = context.solidity_mut().allocate_immutable(key.as_str());
let offset = context.solidity_mut().allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.word_const(offset as u64);
let index = context.xlen_type().const_int(offset as u64, false);
let value = arguments.pop().expect("Always exists").into_int_value();
revive_llvm_context::polkavm_evm_immutable::store(context, index, value)
.map(|_| None)
}
InstructionName::CALLDATALOAD => {
match context
.code_type()
@@ -796,7 +795,7 @@ where
Ok(Some(context.word_const(0).as_basic_value_enum()))
}
revive_llvm_context::PolkaVMCodeType::Runtime => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_calldata::load(
context,
arguments[0].into_int_value(),
@@ -819,7 +818,7 @@ where
}
}
InstructionName::CALLDATACOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
match context
.code_type()
@@ -862,7 +861,7 @@ where
}
}
InstructionName::CODECOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let parent = context.module().get_name().to_str().expect("Always valid");
let source = &self.stack_input.elements[1];
@@ -917,7 +916,7 @@ where
revive_llvm_context::polkavm_evm_return_data::size(context).map(Some)
}
InstructionName::RETURNDATACOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return_data::copy(
context,
arguments[0].into_int_value(),
@@ -927,7 +926,7 @@ where
.map(|_| None)
}
InstructionName::EXTCODESIZE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_ext_code::size(
context,
Some(arguments[0].into_int_value()),
@@ -935,7 +934,7 @@ where
.map(Some)
}
InstructionName::EXTCODEHASH => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_ext_code::hash(
context,
arguments[0].into_int_value(),
@@ -944,7 +943,7 @@ where
}
InstructionName::RETURN => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return::r#return(
context,
arguments[0].into_int_value(),
@@ -953,7 +952,7 @@ where
.map(|_| None)
}
InstructionName::REVERT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return::revert(
context,
arguments[0].into_int_value(),
@@ -969,7 +968,7 @@ where
}
InstructionName::LOG0 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -982,7 +981,7 @@ where
.map(|_| None)
}
InstructionName::LOG1 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -995,7 +994,7 @@ where
.map(|_| None)
}
InstructionName::LOG2 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -1008,7 +1007,7 @@ where
.map(|_| None)
}
InstructionName::LOG3 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -1021,7 +1020,7 @@ where
.map(|_| None)
}
InstructionName::LOG4 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -1035,7 +1034,7 @@ where
}
InstructionName::CALL => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value();
@@ -1060,7 +1059,7 @@ where
.map(Some)
}
InstructionName::STATICCALL => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value();
@@ -1084,7 +1083,7 @@ where
.map(Some)
}
InstructionName::DELEGATECALL => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value();
@@ -1108,7 +1107,7 @@ where
}
InstructionName::CREATE | InstructionName::ZK_CREATE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let value = arguments[0].into_int_value();
let input_offset = arguments[1].into_int_value();
@@ -1124,7 +1123,7 @@ where
.map(Some)
}
InstructionName::CREATE2 | InstructionName::ZK_CREATE2 => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let value = arguments[0].into_int_value();
let input_offset = arguments[1].into_int_value();
@@ -1155,7 +1154,7 @@ where
revive_llvm_context::polkavm_evm_ether_gas::gas(context).map(Some)
}
InstructionName::BALANCE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let address = arguments[0].into_int_value();
revive_llvm_context::polkavm_evm_ether_gas::balance(context, address).map(Some)
@@ -1184,7 +1183,7 @@ where
revive_llvm_context::polkavm_evm_contract_context::block_number(context).map(Some)
}
InstructionName::BLOCKHASH => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let index = arguments[0].into_int_value();
revive_llvm_context::polkavm_evm_contract_context::block_hash(context, index)
@@ -1222,7 +1221,7 @@ where
anyhow::bail!("The `EXTCODECOPY` instruction is not supported");
}
InstructionName::SELFDESTRUCT => {
let _arguments = self.pop_arguments_llvm(context);
let _arguments = self.pop_arguments_llvm(context)?;
anyhow::bail!("The `SELFDESTRUCT` instruction is not supported");
}
@@ -1234,7 +1233,7 @@ where
return_address,
..
} => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
arguments.pop();
arguments.reverse();
arguments.pop();
@@ -1297,7 +1296,7 @@ where
return Ok(());
}
InstructionName::RecursiveReturn { .. } => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
arguments.reverse();
arguments.pop();
@@ -501,25 +501,30 @@ impl FunctionCall {
)
.map(|_| None)
}
Name::LoadImmutable => todo!(),
Name::LoadImmutable => {
let mut arguments = self.pop_arguments::<D, 1>(context)?;
let key = arguments[0].original.take().ok_or_else(|| {
anyhow::anyhow!("{} `load_immutable` literal is missing", location)
})?;
let offset = context
.solidity_mut()
.get_or_allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.xlen_type().const_int(offset as u64, false);
revive_llvm_context::polkavm_evm_immutable::load(context, index).map(Some)
}
Name::SetImmutable => {
let mut arguments = self.pop_arguments::<D, 3>(context)?;
let key = arguments[1].original.take().ok_or_else(|| {
anyhow::anyhow!("{} `load_immutable` literal is missing", location)
})?;
if key.as_str() == "library_deploy_address" {
return Ok(None);
}
let offset = context.solidity_mut().allocate_immutable(key.as_str());
let index = context.word_const(offset as u64);
let offset = context.solidity_mut().allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.xlen_type().const_int(offset as u64, false);
let value = arguments[2].value.into_int_value();
revive_llvm_context::polkavm_evm_immutable::store(context, index, value)
.map(|_| None)
}
Name::CallDataLoad => {
let arguments = self.pop_arguments_llvm::<D, 1>(context)?;
@@ -183,6 +183,7 @@ where
&mut self,
context: &mut revive_llvm_context::PolkaVMContext<D>,
) -> anyhow::Result<()> {
revive_llvm_context::PolkaVMImmutableDataLoadFunction.declare(context)?;
let mut entry = revive_llvm_context::PolkaVMEntryFunction::default();
entry.declare(context)?;
@@ -199,6 +200,7 @@ where
revive_llvm_context::PolkaVMFunctionDeployCode,
revive_llvm_context::PolkaVMFunctionRuntimeCode,
revive_llvm_context::PolkaVMFunctionEntry,
revive_llvm_context::PolkaVMFunctionImmutableDataLoad,
]
.into_iter()
{
@@ -216,6 +218,7 @@ where
fn into_llvm(self, context: &mut revive_llvm_context::PolkaVMContext<D>) -> anyhow::Result<()> {
if self.identifier.ends_with("_deployed") {
revive_llvm_context::PolkaVMImmutableDataLoadFunction.into_llvm(context)?;
revive_llvm_context::PolkaVMRuntimeCodeFunction::new(self.code).into_llvm(context)?;
} else {
revive_llvm_context::PolkaVMDeployCodeFunction::new(self.code).into_llvm(context)?;