mirror of
https://github.com/pezkuwichain/revive.git
synced 2026-06-14 21:31:05 +00:00
Compare commits
119 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c1a635dc3 | |||
| 8d83f6d177 | |||
| 00019eeec4 | |||
| 33cbfe1da5 | |||
| d763e30b8f | |||
| 5d742d150d | |||
| 7844bbb604 | |||
| 0903718f07 | |||
| 880305dbfb | |||
| bb4a4dddde | |||
| 184d40d377 | |||
| bd89ebc45a | |||
| 44bc7b94b2 | |||
| b002382d76 | |||
| e22eebabad | |||
| 16a0cc46e6 | |||
| 6834751522 | |||
| a4c4ad55dc | |||
| 0d39b289cb | |||
| 10c7045e15 | |||
| 39d78179d4 | |||
| 9e9227d740 | |||
| a04eacabff | |||
| 68ec8be49f | |||
| caa1228720 | |||
| d9a304d162 | |||
| 2d0a0e2e81 | |||
| 354b1c8d79 | |||
| 5ff17da695 | |||
| 1ba806be1f | |||
| 532721f3be | |||
| 2ea10d0c3e | |||
| 4f0a109771 | |||
| bdaf573f17 | |||
| 0e90f1fd8c | |||
| 5138fe3d06 | |||
| 06aa289d9b | |||
| 42697edc67 | |||
| d8be21f156 | |||
| 47d5d6b394 | |||
| 83bf9d6041 | |||
| 2194aeebd0 | |||
| 02055c73bb | |||
| 0e90317488 | |||
| 03a1918993 | |||
| 5f5ec1a539 | |||
| 6af889c1ff | |||
| 864e40901f | |||
| ea63991617 | |||
| f80a96059d | |||
| 6f080bb9f4 | |||
| e958da5cd1 | |||
| b55669f5c5 | |||
| 169740eb5e | |||
| 95ff85c6d1 | |||
| a7318f2ef6 | |||
| c0dd845b39 | |||
| 9f8a8a782d | |||
| b1a3a452ac | |||
| 518c03d045 | |||
| a75fc55133 | |||
| c547a9ef78 | |||
| 336fc63f1d | |||
| 9fc24af355 | |||
| 85bd888f48 | |||
| 426f673b0a | |||
| 72515254fe | |||
| 9b341853b4 | |||
| 018d9f39fc | |||
| 3d44685168 | |||
| 44ae9e77d5 | |||
| a85d1ef333 | |||
| 45d53f2ee4 | |||
| 34c233207e | |||
| ec46b211ab | |||
| df8ebb61ec | |||
| bd10742ef8 | |||
| 3468fd5abc | |||
| bd33566206 | |||
| 5a6ef7a3da | |||
| 7623f6f7fa | |||
| 7bdf776ea4 | |||
| 3fbf2833c2 | |||
| b3b4f4c9ae | |||
| cf4901f0a9 | |||
| 21dd0abb8a | |||
| b208daed7e | |||
| 09b905415b | |||
| 99d22cde2f | |||
| bfcdb8afa9 | |||
| 40013b4f5c | |||
| 796d0c19bb | |||
| 8a6d43bcd3 | |||
| bd0c62f99c | |||
| d6ae7daab1 | |||
| 7aa27516e4 | |||
| 3f9a90fe79 | |||
| 45a082d9a8 | |||
| ec952fd2cb | |||
| 17832855e0 | |||
| 69800ae1b3 | |||
| a67e6a94f5 | |||
| 2865676323 | |||
| a76c5578cc | |||
| a400286a3a | |||
| 2327a58213 | |||
| c52a8d0f20 | |||
| 50f2dd9b74 | |||
| e83e4f04e6 | |||
| 6436e1956b | |||
| 2b9e40225d | |||
| 6d058a42ed | |||
| d12fa073fd | |||
| cffa14a4d2 | |||
| d238d8f39e | |||
| 7a094f17c0 | |||
| c04ae9a5c3 | |||
| 80e14f182d | |||
| 426ab4b095 |
@@ -0,0 +1,52 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build-ubuntu-x86:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install solc
|
||||
run: |
|
||||
mkdir -p solc
|
||||
curl -sSL --output solc/solc https://github.com/ethereum/solidity/releases/download/v0.8.26/solc-static-linux
|
||||
chmod +x solc/solc
|
||||
echo "$(pwd)/solc/" >> $GITHUB_PATH
|
||||
|
||||
- name: Install LLVM
|
||||
run: |
|
||||
curl -sSL --output llvm.tar.xz https://github.com/llvm/llvm-project/releases/download/llvmorg-18.1.4/clang+llvm-18.1.4-x86_64-linux-gnu-ubuntu-18.04.tar.xz
|
||||
tar Jxf llvm.tar.xz
|
||||
mv clang+llvm-18.1.4-x86_64-linux-gnu-ubuntu-18.04 llvm18/
|
||||
echo "$(pwd)/llvm18/bin" >> $GITHUB_PATH
|
||||
|
||||
- name: Install apt dependencies
|
||||
run: sudo apt update && sudo apt install -y libtinfo5
|
||||
|
||||
- name: Format
|
||||
run: make format
|
||||
|
||||
- name: Clippy
|
||||
run: make clippy
|
||||
|
||||
- name: Test cargo workspace
|
||||
run: make test-workspace
|
||||
|
||||
- name: Test CLI
|
||||
run: make test-cli
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ github.job }}-resolc
|
||||
path: ./target/release/resolc
|
||||
retention-days: 1
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/target
|
||||
*.dot
|
||||
.vscode/
|
||||
.DS_Store
|
||||
/*.sol
|
||||
/*.yul
|
||||
/*.ll
|
||||
/*.s
|
||||
/llvm-project
|
||||
/llvm18.0
|
||||
node_modules
|
||||
artifacts
|
||||
tmp
|
||||
package-lock.json
|
||||
/*.html
|
||||
/build
|
||||
Generated
+10720
File diff suppressed because it is too large
Load Diff
+79
@@ -0,0 +1,79 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
authors = [
|
||||
"Cyrill Leutwiler <cyrill@parity.io>",
|
||||
"Parity Technologies <admin@parity.io>",
|
||||
]
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2021"
|
||||
repository = "https://github.com/xermicus/revive"
|
||||
|
||||
[workspace.dependencies]
|
||||
revive-benchmarks = { version = "0.1.0", path = "crates/benchmarks" }
|
||||
revive-builtins = { version = "0.1.0", path = "crates/builtins" }
|
||||
revive-common = { version = "0.1.0", path = "crates/common" }
|
||||
revive-differential = { version = "0.1.0", path = "crates/differential" }
|
||||
revive-integration = { version = "0.1.0", path = "crates/integration" }
|
||||
revive-linker = { version = "0.1.0", path = "crates/linker" }
|
||||
lld-sys = { version = "0.1.0", path = "crates/lld-sys" }
|
||||
revive-llvm-context = { version = "0.1.0", path = "crates/llvm-context" }
|
||||
pallet-contracts-pvm-llapi = { version = "0.1.0", path = "crates/pallet-contracts-pvm-llapi" }
|
||||
revive-runner = { version = "0.1.0", path = "crates/runner" }
|
||||
revive-solidity = { version = "0.1.0", path = "crates/solidity" }
|
||||
revive-stdlib = { version = "0.1.0", path = "crates/stdlib" }
|
||||
|
||||
hex = "0.4"
|
||||
petgraph = "0.6"
|
||||
cc = "1.0"
|
||||
libc = "0.2"
|
||||
tempfile = "3.8"
|
||||
anyhow = "1.0"
|
||||
semver = { version = "1.0", features = [ "serde" ] }
|
||||
itertools = "0.12"
|
||||
serde = { version = "1.0", features = [ "derive" ] }
|
||||
serde_json = { version = "1.0", features = [ "arbitrary_precision" ] }
|
||||
regex = "1.10"
|
||||
once_cell = "1.19"
|
||||
num = "0.4"
|
||||
sha1 = "0.10"
|
||||
sha2 = "0.10"
|
||||
sha3 = "0.10"
|
||||
md5 = "0.7"
|
||||
colored = "2.1"
|
||||
thiserror = "1.0"
|
||||
which = "5.0"
|
||||
path-slash = "0.2"
|
||||
rayon = "1.8"
|
||||
clap = { version = "4", default-features = false, features = ["derive"] }
|
||||
rand = "0.8"
|
||||
polkavm-common = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
polkavm-linker = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
polkavm-disassembler = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
polkavm = { git = "https://github.com/koute/polkavm.git", rev = "360029e" }
|
||||
alloy-primitives = "0.6"
|
||||
alloy-sol-types = "0.6"
|
||||
env_logger = { version = "0.10.0", default-features = false }
|
||||
serde_stacker = "0.1"
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
log = { version = "0.4" }
|
||||
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 = "559fa1db0594a81d5dbf343613ba2f3fc16708da" }
|
||||
|
||||
# Benchmarking against EVM
|
||||
primitive-types = { version = "0.12", features = ["codec"] }
|
||||
evm-interpreter = { git = "https://github.com/xermicus/evm.git", branch = "separate-compilation" }
|
||||
|
||||
[workspace.dependencies.inkwell]
|
||||
version = "0.5"
|
||||
default-features = false
|
||||
features = ["serde", "llvm18-0", "no-libffi-linking", "target-riscv"]
|
||||
|
||||
[profile.benchmark]
|
||||
inherits = "release"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
https://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright (c) 2019 Matter Labs
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Matter Labs
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,62 @@
|
||||
.PHONY: install format test test-solidity test-cli test-integration test-workspace clean docs docs-build
|
||||
|
||||
install: install-bin install-npm
|
||||
|
||||
install-bin:
|
||||
cargo install --path crates/solidity
|
||||
|
||||
install-npm:
|
||||
npm install && npm fund
|
||||
|
||||
format:
|
||||
cargo fmt --all --check
|
||||
|
||||
test: format clippy test-cli test-workspace
|
||||
cargo test --workspace
|
||||
|
||||
test-integration: install-bin
|
||||
cargo test --package revive-integration
|
||||
|
||||
test-solidity: install
|
||||
cargo test --package revive-solidity
|
||||
|
||||
test-workspace: install
|
||||
cargo test --workspace
|
||||
|
||||
test-cli: install
|
||||
npm run test:cli
|
||||
|
||||
bench-prepare: install-bin
|
||||
cargo criterion --bench prepare --features bench-evm,bench-pvm --message-format=json \
|
||||
| criterion-table > crates/benchmarks/PREPARE.md
|
||||
|
||||
bench-execute: install-bin
|
||||
cargo criterion --bench execute --features bench-evm,bench-pvm --message-format=json \
|
||||
| criterion-table > crates/benchmarks/EXECUTE.md
|
||||
|
||||
bench-extensive: install-bin
|
||||
cargo criterion --all --all-features --message-format=json \
|
||||
| criterion-table > crates/benchmarks/BENCHMARKS.md
|
||||
|
||||
bench-quick: install-bin
|
||||
cargo criterion --all --features bench-evm
|
||||
|
||||
bench: install-bin
|
||||
cargo criterion --all --features bench-evm,bench-pvm --message-format=json \
|
||||
| criterion-table > crates/benchmarks/BENCHMARKS.md
|
||||
|
||||
clippy:
|
||||
cargo clippy --all-features --workspace --tests --benches
|
||||
|
||||
docs: docs-build
|
||||
mdbook serve --open docs/
|
||||
|
||||
docs-build:
|
||||
mdbook test docs/ && mdbook build docs/
|
||||
|
||||
clean:
|
||||
cargo clean ; \
|
||||
rm -rf node_modules ; \
|
||||
rm -rf crates/solidity/src/tests/cli-tests/artifacts ; \
|
||||
cargo uninstall revive-solidity ; \
|
||||
rm -f package-lock.json
|
||||
@@ -0,0 +1,38 @@
|
||||

|
||||
|
||||
# revive
|
||||
|
||||
YUL and EVM assembly recompiler to LLVM, targetting RISC-V on [PolkaVM](https://github.com/koute/polkavm).
|
||||
|
||||
[Frontend](https://github.com/matter-labs/era-compiler-solidity) and [code generator](https://github.com/matter-labs/era-compiler-llvm-context) are based of ZKSync `zksolc`.
|
||||
|
||||
## Status
|
||||
|
||||
This is experimental software in active development and not ready just yet for production usage.
|
||||
|
||||
Discussion around the development is hosted on the [Polkadot Forum](https://forum.polkadot.network/t/contracts-update-solidity-on-polkavm/6949#a-new-solidity-compiler-1).
|
||||
|
||||
## Installation
|
||||
|
||||
`resolc` depends on the [solc](https://github.com/ethereum/solidity) binary installed on your system.
|
||||
|
||||
To install the `resolc` Solidity frontend executable:
|
||||
|
||||
```bash
|
||||
bash build-llvm.sh
|
||||
export PATH=${PWD}/llvm18.0/bin:$PATH
|
||||
make install-bin
|
||||
resolc --version
|
||||
```
|
||||
|
||||
### LLVM
|
||||
|
||||
`revive` requires a build of LLVM 18.1.4 or later including `compiler-rt`. Use the provided [build-llvm.sh](build-llvm.sh) build script to compile a compatible LLVM build locally in `$PWD/llvm18.0` (don't forget to add that to `$PATH` afterwards).
|
||||
|
||||
### Development
|
||||
|
||||
Please consult the [Makefile](Makefile) targets to learn how to run tests and benchmarks.
|
||||
Ensure that your branch passes `make test` locally when submitting a pull request.
|
||||
|
||||
## Design overview
|
||||
`revive` uses [solc](https://github.com/ethereum/solidity/), the Ethereum Solidity compiler, as the [Solidity frontend](crates/solidity/src/lib.rs) to process smart contracts written in Solidity. The YUL IR code (or legacy EVM assembly as a fallback for older `solc` versions) emitted by `solc` is then translated to LLVM IR, targetting a runtime similar to [Polkadots `contracts` pallet](https://docs.rs/pallet-contracts/latest/pallet_contracts/api_doc/trait.Current.html).
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
INSTALL_DIR="${PWD}/llvm18.0"
|
||||
mkdir -p ${INSTALL_DIR}
|
||||
|
||||
|
||||
# Clone LLVM 18 (any revision after commit bd32aaa is supposed to work)
|
||||
if [ ! -d "llvm-project" ]; then
|
||||
git clone --depth 1 --branch release/18.x https://github.com/llvm/llvm-project.git
|
||||
fi
|
||||
|
||||
|
||||
# Build LLVM, clang
|
||||
LLVM_SRC_PREFIX=${PWD}/llvm-project
|
||||
LLVM_SRC_DIR=${LLVM_SRC_PREFIX}/llvm
|
||||
LLVM_BUILD_DIR=${PWD}/build/llvm
|
||||
if [ ! -d ${LLVM_BUILD_DIR} ] ; then
|
||||
mkdir -p ${LLVM_BUILD_DIR}
|
||||
fi
|
||||
|
||||
cmake -G Ninja \
|
||||
-S ${LLVM_SRC_DIR} \
|
||||
-B ${LLVM_BUILD_DIR} \
|
||||
-DLLVM_ENABLE_ASSERTIONS=On \
|
||||
-DLLVM_ENABLE_TERMINFO=Off \
|
||||
-DLLVM_ENABLE_LIBXML2=Off \
|
||||
-DLLVM_ENABLE_ZLIB=Off \
|
||||
-DLLVM_ENABLE_PROJECTS='clang;lld' \
|
||||
-DLLVM_TARGETS_TO_BUILD='RISCV' \
|
||||
-DLLVM_ENABLE_ZSTD=Off \
|
||||
-DCMAKE_BUILD_TYPE=MinSizeRel \
|
||||
-DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
|
||||
|
||||
cmake --build ${LLVM_BUILD_DIR}
|
||||
cmake --install ${LLVM_BUILD_DIR}
|
||||
|
||||
# Build compiler builtins
|
||||
COMPILER_RT_SRC_DIR=${LLVM_SRC_PREFIX}/compiler-rt
|
||||
COMPILER_RT_BUILD_DIR=${PWD}/build/compiler-rt
|
||||
if [ ! -d ${COMPILER_RT_BUILD_DIR} ] ; then
|
||||
mkdir -p ${COMPILER_RT_BUILD_DIR}
|
||||
fi
|
||||
|
||||
build_compiler_rt() {
|
||||
case "$1" in
|
||||
64) TARGET_ABI=lp64e ;;
|
||||
32) TARGET_ABI=ilp32e ;;
|
||||
*) exit -1
|
||||
esac
|
||||
CFLAGS="--target=riscv${1} -march=rv${1}em -mabi=${TARGET_ABI} -mcpu=generic-rv${1} -nostdlib -nodefaultlibs"
|
||||
|
||||
cmake -G Ninja \
|
||||
-S ${COMPILER_RT_SRC_DIR} \
|
||||
-B ${COMPILER_RT_BUILD_DIR} \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} \
|
||||
-DCOMPILER_RT_BUILD_BUILTINS=ON \
|
||||
-DCOMPILER_RT_BUILD_LIBFUZZER=OFF \
|
||||
-DCOMPILER_RT_BUILD_MEMPROF=OFF \
|
||||
-DCOMPILER_RT_BUILD_PROFILE=OFF \
|
||||
-DCOMPILER_RT_BUILD_SANITIZERS=OFF \
|
||||
-DCOMPILER_RT_BUILD_XRAY=OFF \
|
||||
-DCMAKE_C_COMPILER=${INSTALL_DIR}/bin/clang \
|
||||
-DCMAKE_C_COMPILER_TARGET=riscv${1} \
|
||||
-DCMAKE_ASM_COMPILER_TARGET=riscv${1} \
|
||||
-DCMAKE_CXX_COMPILER_TARGET=riscv${1} \
|
||||
-DCMAKE_C_TARGET_BITS=riscv${1} \
|
||||
-DCMAKE_ASM_TARGET_BITS=riscv${1} \
|
||||
-DCMAKE_AR=${INSTALL_DIR}/bin/llvm-ar \
|
||||
-DCMAKE_NM=${INSTALL_DIR}/bin/llvm-nm \
|
||||
-DCMAKE_RANLIB=${INSTALL_DIR}/bin/llvm-ranlib \
|
||||
-DCOMPILER_RT_BAREMETAL_BUILD=ON \
|
||||
-DLLVM_CONFIG_PATH=${INSTALL_DIR}/bin/llvm-config \
|
||||
-DCMAKE_C_FLAGS="${CFLAGS}" \
|
||||
-DCMAKE_ASM_FLAGS="${CFLAGS}" \
|
||||
-DCOMPILER_RT_TEST_COMPILER=${INSTALL_DIR}/bin/clang \
|
||||
-DCMAKE_CXX_FLAGS="${CFLAGS}" \
|
||||
-DCMAKE_SYSTEM_NAME=unknown \
|
||||
-DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON
|
||||
|
||||
cmake --build ${COMPILER_RT_BUILD_DIR}
|
||||
cmake --install ${COMPILER_RT_BUILD_DIR}
|
||||
}
|
||||
|
||||
build_compiler_rt 32
|
||||
build_compiler_rt 64
|
||||
|
||||
echo ""
|
||||
echo "success"
|
||||
echo "add this directory to your PATH: ${INSTALL_DIR}/bin/"
|
||||
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "revive-benchmarks"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
description = "revive compiler benchmarks"
|
||||
|
||||
[features]
|
||||
default = ["bench-pvm-interpreter"]
|
||||
bench-pvm-interpreter = []
|
||||
bench-pvm = []
|
||||
bench-evm = ["revive-differential"]
|
||||
bench-extensive = []
|
||||
|
||||
[dependencies]
|
||||
hex = { workspace = true }
|
||||
polkavm = { workspace = true }
|
||||
revive-integration = { workspace = true }
|
||||
revive-differential = { workspace = true, optional = true }
|
||||
alloy-primitives = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { workspace = true }
|
||||
|
||||
[[bench]]
|
||||
name = "execute"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "prepare"
|
||||
harness = false
|
||||
@@ -0,0 +1,210 @@
|
||||
use alloy_primitives::U256;
|
||||
use criterion::{
|
||||
criterion_group, criterion_main, measurement::Measurement, BenchmarkGroup, BenchmarkId,
|
||||
Criterion,
|
||||
};
|
||||
use revive_integration::cases::Contract;
|
||||
|
||||
fn bench<P, L, I, M>(mut group: BenchmarkGroup<'_, M>, parameters: &[P], labels: &[L], contract: I)
|
||||
where
|
||||
P: Clone,
|
||||
L: std::fmt::Display,
|
||||
I: Fn(P) -> Contract,
|
||||
M: Measurement,
|
||||
{
|
||||
assert_eq!(parameters.len(), labels.len());
|
||||
|
||||
for (p, l) in parameters.iter().zip(labels.iter()) {
|
||||
#[cfg(feature = "bench-evm")]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
group.bench_with_input(BenchmarkId::new("EVM", l), p, move |b, _| {
|
||||
b.iter(|| {
|
||||
revive_differential::execute(revive_differential::prepare(
|
||||
contract.evm_runtime.clone(),
|
||||
contract.calldata.clone(),
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
{
|
||||
#[cfg(all(feature = "bench-pvm-interpreter", not(feature = "bench-extensive")))]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let (transaction, mut instance, export) = revive_benchmarks::prepare_pvm(
|
||||
&contract.pvm_runtime,
|
||||
contract.calldata,
|
||||
polkavm::BackendKind::Interpreter,
|
||||
);
|
||||
group.bench_with_input(BenchmarkId::new("PVMInterpreter", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "bench-pvm", not(feature = "bench-extensive")))]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let (transaction, mut instance, export) = revive_benchmarks::prepare_pvm(
|
||||
&contract.pvm_runtime,
|
||||
contract.calldata,
|
||||
polkavm::BackendKind::Compiler,
|
||||
);
|
||||
group.bench_with_input(BenchmarkId::new("PVM", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
{
|
||||
use revive_benchmarks::instantiate_engine;
|
||||
use revive_integration::mock_runtime::{instantiate_module, recompile_code, State};
|
||||
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let engine = instantiate_engine(polkavm::BackendKind::Interpreter);
|
||||
let module = recompile_code(&contract.pvm_runtime, &engine);
|
||||
let transaction = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata);
|
||||
group.bench_with_input(BenchmarkId::new("PVMInterpreter", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let (mut instance, export) = instantiate_module(&module, &engine);
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm")]
|
||||
{
|
||||
let contract = contract(p.clone());
|
||||
let engine = instantiate_engine(polkavm::BackendKind::Compiler);
|
||||
let module = recompile_code(&contract.pvm_runtime, &engine);
|
||||
let transaction = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata);
|
||||
group.bench_with_input(BenchmarkId::new("PVM", l), p, |b, _| {
|
||||
b.iter(|| {
|
||||
let (mut instance, export) = instantiate_module(&module, &engine);
|
||||
let _ = transaction.clone().call_on(&mut instance, export);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn group<'error, M>(c: &'error mut Criterion<M>, group_name: &str) -> BenchmarkGroup<'error, M>
|
||||
where
|
||||
M: Measurement,
|
||||
{
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
{
|
||||
let mut group = c.benchmark_group(group_name);
|
||||
group.sample_size(10);
|
||||
group
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
return c.benchmark_group(group_name);
|
||||
}
|
||||
|
||||
fn bench_baseline(c: &mut Criterion) {
|
||||
let group = group(c, "Baseline");
|
||||
let parameters = &[0u8];
|
||||
|
||||
bench(group, parameters, parameters, |_| Contract::baseline());
|
||||
}
|
||||
|
||||
fn bench_odd_product(c: &mut Criterion) {
|
||||
let group = group(c, "OddPorduct");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = &[300000, 1200000, 12000000, 180000000, 720000000];
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = &[10_000, 100_000];
|
||||
|
||||
bench(group, parameters, parameters, Contract::odd_product);
|
||||
}
|
||||
|
||||
fn bench_triangle_number(c: &mut Criterion) {
|
||||
let group = group(c, "TriangleNumber");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = &[360000, 1440000, 14400000, 216000000, 864000000];
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = &[10_000, 100_000];
|
||||
|
||||
bench(group, parameters, parameters, Contract::triangle_number);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_recurisve(c: &mut Criterion) {
|
||||
let group = group(c, "FibonacciRecursive");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = [24, 27, 31, 36, 39]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = [12, 16, 20]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
bench(group, ¶meters, ¶meters, Contract::fib_recursive);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_iterative(c: &mut Criterion) {
|
||||
let group = group(c, "FibonacciIterative");
|
||||
#[cfg(feature = "bench-extensive")]
|
||||
let parameters = [256, 162500, 650000, 6500000, 100000000, 400000000]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
#[cfg(not(feature = "bench-extensive"))]
|
||||
let parameters = [64, 128, 256]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
bench(group, ¶meters, ¶meters, Contract::fib_iterative);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_binet(c: &mut Criterion) {
|
||||
let group = group(c, "FibonacciBinet");
|
||||
let parameters = [64, 128, 256]
|
||||
.iter()
|
||||
.map(|p| U256::from(*p))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
bench(group, ¶meters, ¶meters, Contract::fib_binet);
|
||||
}
|
||||
|
||||
fn bench_sha1(c: &mut Criterion) {
|
||||
let group = group(c, "SHA1");
|
||||
let parameters = &[vec![0xff], vec![0xff; 64], vec![0xff; 512]];
|
||||
let labels = parameters.iter().map(|p| p.len()).collect::<Vec<_>>();
|
||||
|
||||
bench(group, parameters, &labels, Contract::sha1);
|
||||
}
|
||||
|
||||
criterion_group!(
|
||||
name = execute;
|
||||
config = Criterion::default();
|
||||
targets = bench_baseline,
|
||||
bench_odd_product,
|
||||
bench_triangle_number,
|
||||
bench_fibonacci_recurisve,
|
||||
bench_fibonacci_iterative,
|
||||
bench_fibonacci_binet,
|
||||
bench_sha1
|
||||
);
|
||||
criterion_main!(execute);
|
||||
@@ -0,0 +1,171 @@
|
||||
use alloy_primitives::U256;
|
||||
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
|
||||
|
||||
use revive_integration::cases::Contract;
|
||||
|
||||
fn bench(
|
||||
c: &mut Criterion,
|
||||
group_name: &str,
|
||||
#[cfg(feature = "bench-evm")] evm_runtime: Vec<u8>,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))] pvm_runtime: Vec<u8>,
|
||||
) {
|
||||
let mut group = c.benchmark_group(group_name);
|
||||
let code_size = 0;
|
||||
|
||||
#[cfg(feature = "bench-evm")]
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("Evm", code_size),
|
||||
&evm_runtime,
|
||||
|b, code| b.iter(|| revive_differential::prepare(code.clone(), Vec::new())),
|
||||
);
|
||||
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Interpreter);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMInterpreterCompile", code_size),
|
||||
&(&pvm_runtime, engine),
|
||||
|b, (code, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::recompile_code(code, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm-interpreter")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Interpreter);
|
||||
let module = revive_integration::mock_runtime::recompile_code(&pvm_runtime, &engine);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMInterpreterInstantiate", code_size),
|
||||
&(module, engine),
|
||||
|b, (module, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::instantiate_module(module, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Compiler);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMCompile", code_size),
|
||||
&(&pvm_runtime, engine),
|
||||
|b, (code, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::recompile_code(code, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "bench-pvm")]
|
||||
{
|
||||
let engine = revive_benchmarks::instantiate_engine(polkavm::BackendKind::Compiler);
|
||||
let module = revive_integration::mock_runtime::recompile_code(&pvm_runtime, &engine);
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("PVMInstantiate", code_size),
|
||||
&(module, engine),
|
||||
|b, (module, engine)| {
|
||||
b.iter(|| {
|
||||
revive_integration::mock_runtime::instantiate_module(module, engine);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn bench_baseline(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareBaseline",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::baseline().evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::baseline().pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_odd_product(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareOddProduct",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::odd_product(0).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::baseline().pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_triangle_number(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareTriangleNumber",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::triangle_number(0).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::triangle_number(0).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_recursive(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareFibonacciRecursive",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::fib_recursive(U256::ZERO).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::fib_recursive(U256::ZERO).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_iterative(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareFibonacciIterative",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::fib_iterative(U256::ZERO).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::fib_iterative(U256::ZERO).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_fibonacci_binet(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareFibonacciBinet",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::fib_binet(U256::ZERO).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::fib_binet(U256::ZERO).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_sha1(c: &mut Criterion) {
|
||||
bench(
|
||||
c,
|
||||
"PrepareSHA1",
|
||||
#[cfg(feature = "bench-evm")]
|
||||
Contract::sha1(Default::default()).evm_runtime,
|
||||
#[cfg(any(feature = "bench-pvm-interpreter", feature = "bench-pvm"))]
|
||||
Contract::sha1(Default::default()).pvm_runtime,
|
||||
);
|
||||
}
|
||||
|
||||
criterion_group!(
|
||||
name = prepare;
|
||||
config = Criterion::default();
|
||||
targets = bench_baseline,
|
||||
bench_odd_product,
|
||||
bench_triangle_number,
|
||||
bench_fibonacci_recursive,
|
||||
bench_fibonacci_iterative,
|
||||
bench_fibonacci_binet,
|
||||
bench_sha1
|
||||
);
|
||||
criterion_main!(prepare);
|
||||
@@ -0,0 +1,28 @@
|
||||
use polkavm::{BackendKind, Config, Engine, ExportIndex, Instance, SandboxKind};
|
||||
use revive_integration::mock_runtime::{self, TransactionBuilder};
|
||||
use revive_integration::mock_runtime::{State, Transaction};
|
||||
|
||||
pub fn prepare_pvm(
|
||||
code: &[u8],
|
||||
input: Vec<u8>,
|
||||
backend: BackendKind,
|
||||
) -> (TransactionBuilder, Instance<Transaction>, ExportIndex) {
|
||||
let mut config = Config::new();
|
||||
config.set_backend(Some(backend));
|
||||
config.set_sandbox(Some(SandboxKind::Linux));
|
||||
|
||||
let (instance, export_index) = mock_runtime::prepare(code, Some(config));
|
||||
let transaction = State::default()
|
||||
.transaction()
|
||||
.with_default_account(code)
|
||||
.calldata(input);
|
||||
|
||||
(transaction, instance, export_index)
|
||||
}
|
||||
|
||||
pub fn instantiate_engine(backend: BackendKind) -> Engine {
|
||||
let mut config = Config::new();
|
||||
config.set_backend(Some(backend));
|
||||
config.set_sandbox(Some(SandboxKind::Linux));
|
||||
mock_runtime::setup(Some(config))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "revive-builtins"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
build = "build.rs"
|
||||
description = "compiler builtins for the revive compiler"
|
||||
|
||||
[features]
|
||||
riscv-64 = []
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,41 @@
|
||||
use std::{env, fs, io::Read, path::Path, process::Command};
|
||||
|
||||
#[cfg(not(feature = "riscv-64"))]
|
||||
pub const BUILTINS_ARCHIVE_FILE: &str = "libclang_rt.builtins-riscv32.a";
|
||||
#[cfg(feature = "riscv-64")]
|
||||
pub const BUILTINS_ARCHIVE_FILE: &str = "libclang_rt.builtins-riscv64.a";
|
||||
|
||||
fn main() {
|
||||
let mut llvm_lib_dir = String::new();
|
||||
|
||||
Command::new("llvm-config")
|
||||
.args(["--libdir"])
|
||||
.output()
|
||||
.expect("llvm-config should be able to provide LD path")
|
||||
.stdout
|
||||
.as_slice()
|
||||
.read_to_string(&mut llvm_lib_dir)
|
||||
.expect("llvm-config output should be utf8");
|
||||
|
||||
let mut lib_path = std::path::PathBuf::from(llvm_lib_dir.trim())
|
||||
.join("linux")
|
||||
.join(BUILTINS_ARCHIVE_FILE);
|
||||
if !lib_path.exists() {
|
||||
lib_path = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())
|
||||
.join(BUILTINS_ARCHIVE_FILE);
|
||||
}
|
||||
let archive = fs::read(lib_path).expect("clang builtins not found");
|
||||
|
||||
let out_dir = env::var_os("OUT_DIR").expect("has OUT_DIR");
|
||||
let archive_path = Path::new(&out_dir).join(BUILTINS_ARCHIVE_FILE);
|
||||
let len = archive.len();
|
||||
std::fs::write(archive_path, &archive).expect("can write to OUT_DIR");
|
||||
|
||||
let src_path = Path::new(&out_dir).join("compiler_rt.rs");
|
||||
let src = format!(
|
||||
"pub static COMPILER_RT: &[u8; {len}] = include_bytes!(\"{BUILTINS_ARCHIVE_FILE}\");"
|
||||
);
|
||||
fs::write(src_path, src).expect("can write to OUT_DIR");
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
include!(concat!(env!("OUT_DIR"), "/compiler_rt.rs"));
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Use this template for reporting issues
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
### 🐛 Bug Report
|
||||
|
||||
#### 📝 Description
|
||||
|
||||
Provide a clear and concise description of the bug.
|
||||
|
||||
#### 🔄 Reproduction Steps
|
||||
|
||||
Steps to reproduce the behaviour
|
||||
|
||||
#### 🤔 Expected Behavior
|
||||
|
||||
Describe what you expected to happen.
|
||||
|
||||
#### 😯 Current Behavior
|
||||
|
||||
Describe what actually happened.
|
||||
|
||||
#### 🖥️ Environment
|
||||
|
||||
Any relevant environment details.
|
||||
|
||||
#### 📋 Additional Context
|
||||
|
||||
Add any other context about the problem here. If applicable, add screenshots to help explain.
|
||||
|
||||
#### 📎 Log Output
|
||||
|
||||
```
|
||||
Paste any relevant log output here.
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Use this template for requesting features
|
||||
title: ''
|
||||
labels: feat
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
### 🌟 Feature Request
|
||||
|
||||
#### 📝 Description
|
||||
|
||||
Provide a clear and concise description of the feature you'd like to see.
|
||||
|
||||
#### 🤔 Rationale
|
||||
|
||||
Explain why this feature is important and how it benefits the project.
|
||||
|
||||
#### 📋 Additional Context
|
||||
|
||||
Add any other context or information about the feature request here.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# What ❔
|
||||
|
||||
<!-- What are the changes this PR brings about? -->
|
||||
<!-- Example: This PR adds a PR template to the repo. -->
|
||||
<!-- (For bigger PRs adding more context is appreciated) -->
|
||||
|
||||
## Why ❔
|
||||
|
||||
<!-- Why are these changes done? What goal do they contribute to? What are the principles behind them? -->
|
||||
<!-- Example: PR templates ensure PR reviewers, observers, and future iterators are in context about the evolution of repos. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
<!-- Check your PR fulfills the following items. -->
|
||||
<!-- For draft PRs check the boxes as you complete them. -->
|
||||
|
||||
- [ ] PR title corresponds to the body of PR.
|
||||
- [ ] Tests for the changes have been added / updated.
|
||||
- [ ] Documentation comments have been added / updated.
|
||||
- [ ] Code has been formatted via `cargo fmt` and checked with `cargo clippy`.
|
||||
@@ -0,0 +1,9 @@
|
||||
name: Cargo license check
|
||||
on: pull_request
|
||||
|
||||
jobs:
|
||||
cargo-deny:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: EmbarkStudios/cargo-deny-action@v1
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
name: "Rust CI"
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: cargo build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- run: cargo build --verbose
|
||||
|
||||
formatting:
|
||||
name: cargo fmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
components: rustfmt
|
||||
- name: Rustfmt Check
|
||||
uses: actions-rust-lang/rustfmt@v1
|
||||
@@ -0,0 +1,17 @@
|
||||
name: Leaked Secrets Scan
|
||||
on: [pull_request]
|
||||
jobs:
|
||||
TruffleHog:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: TruffleHog OSS
|
||||
uses: trufflesecurity/trufflehog@0c66d30c1f4075cee1aada2e1ab46dabb1b0071a
|
||||
with:
|
||||
path: ./
|
||||
base: ${{ github.event.repository.default_branch }}
|
||||
head: HEAD
|
||||
extra_args: --debug --only-verified
|
||||
@@ -0,0 +1,14 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# IDE
|
||||
/.idea/
|
||||
/.vscode/
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "revive-common"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors = [
|
||||
"Cyrill Leutwiler <cyrill@parity.io>",
|
||||
"Oleksandr Zarudnyi <a.zarudnyy@matterlabs.dev>",
|
||||
]
|
||||
description = "Shared constants of the revive compiler"
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[features]
|
||||
riscv-64 = []
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true, features = [ "arbitrary_precision", "unbounded_depth" ] }
|
||||
serde_stacker = { workspace = true }
|
||||
@@ -0,0 +1,10 @@
|
||||
# revive: Compiler Common
|
||||
|
||||
## License
|
||||
|
||||
This library is distributed under the terms of either
|
||||
|
||||
- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
@@ -0,0 +1,13 @@
|
||||
//! The number base constants.
|
||||
|
||||
/// The binary number base.
|
||||
pub const BASE_BINARY: u32 = 2;
|
||||
|
||||
/// The octal number base.
|
||||
pub const BASE_OCTAL: u32 = 8;
|
||||
|
||||
/// The decimal number base.
|
||||
pub const BASE_DECIMAL: u32 = 10;
|
||||
|
||||
/// The hexadecimal number base.
|
||||
pub const BASE_HEXADECIMAL: u32 = 16;
|
||||
@@ -0,0 +1,31 @@
|
||||
//! The common sizes in bits.
|
||||
|
||||
/// The `bool` type bit-length.
|
||||
pub const BIT_LENGTH_BOOLEAN: usize = 1;
|
||||
|
||||
/// The `u8` type or byte bit-length.
|
||||
pub const BIT_LENGTH_BYTE: usize = 8;
|
||||
|
||||
/// The x86 word type (usually `u32`) bit-length.
|
||||
pub const BIT_LENGTH_X32: usize = crate::byte_length::BYTE_LENGTH_X32 * BIT_LENGTH_BYTE;
|
||||
|
||||
/// The x86_64 word type (usually `u64`) bit-length.
|
||||
pub const BIT_LENGTH_X64: usize = crate::byte_length::BYTE_LENGTH_X64 * BIT_LENGTH_BYTE;
|
||||
|
||||
/// The ETH address (usually `u160`) bit-length.
|
||||
pub const BIT_LENGTH_ETH_ADDRESS: usize =
|
||||
crate::byte_length::BYTE_LENGTH_ETH_ADDRESS * BIT_LENGTH_BYTE;
|
||||
|
||||
/// The VM word (usually `u256` or `i256`) bit-length.
|
||||
pub const BIT_LENGTH_WORD: usize = crate::byte_length::BYTE_LENGTH_WORD * BIT_LENGTH_BYTE;
|
||||
|
||||
/// Bit length of the runtime value type.
|
||||
pub const BIT_LENGTH_VALUE: usize = crate::byte_length::BYTE_LENGTH_VALUE * BIT_LENGTH_BYTE;
|
||||
|
||||
/// Bit length of thre runimte block number type.
|
||||
pub const BIT_LENGTH_BLOCK_NUMBER: usize =
|
||||
crate::byte_length::BYTE_LENGTH_BLOCK_NUMBER * BIT_LENGTH_BYTE;
|
||||
|
||||
/// Bit length of thre runimte block timestamp type.
|
||||
pub const BIT_LENGTH_BLOCK_TIMESTAMP: usize =
|
||||
crate::byte_length::BYTE_LENGTH_BLOCK_TIMESTAMP * BIT_LENGTH_BYTE;
|
||||
@@ -0,0 +1,31 @@
|
||||
//! The common sizes in bytes.
|
||||
|
||||
/// The byte-length.
|
||||
pub const BYTE_LENGTH_BYTE: usize = 1;
|
||||
|
||||
/// The x86 word byte-length.
|
||||
pub const BYTE_LENGTH_X32: usize = 4;
|
||||
|
||||
/// Native stack alignment size in bytes
|
||||
#[cfg(not(feature = "riscv-64"))]
|
||||
pub const BYTE_LENGTH_STACK_ALIGN: usize = 4;
|
||||
#[cfg(feature = "riscv-64")]
|
||||
pub const BYTE_LENGTH_STACK_ALIGN: usize = 8;
|
||||
|
||||
/// The x86_64 word byte-length.
|
||||
pub const BYTE_LENGTH_X64: usize = 8;
|
||||
|
||||
/// The ETH address byte-length.
|
||||
pub const BYTE_LENGTH_ETH_ADDRESS: usize = 20;
|
||||
|
||||
/// The word byte-length.
|
||||
pub const BYTE_LENGTH_WORD: usize = 32;
|
||||
|
||||
/// Byte length of the runtime value type.
|
||||
pub const BYTE_LENGTH_VALUE: usize = 32;
|
||||
|
||||
/// Byte length of the runtime block number type.
|
||||
pub const BYTE_LENGTH_BLOCK_NUMBER: usize = 8;
|
||||
|
||||
/// Byte length of the runtime block timestamp type.
|
||||
pub const BYTE_LENGTH_BLOCK_TIMESTAMP: usize = 8;
|
||||
@@ -0,0 +1,87 @@
|
||||
//! The EVM version.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The EVM version.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum EVMVersion {
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "homestead")]
|
||||
Homestead,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "tangerineWhistle")]
|
||||
TangerineWhistle,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "spuriousDragon")]
|
||||
SpuriousDragon,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "byzantium")]
|
||||
Byzantium,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "constantinople")]
|
||||
Constantinople,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "petersburg")]
|
||||
Petersburg,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "istanbul")]
|
||||
Istanbul,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "berlin")]
|
||||
Berlin,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "london")]
|
||||
London,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "paris")]
|
||||
Paris,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "shanghai")]
|
||||
Shanghai,
|
||||
/// The corresponding EVM version.
|
||||
#[serde(rename = "cancun")]
|
||||
Cancun,
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for EVMVersion {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
Ok(match value {
|
||||
"homestead" => Self::Homestead,
|
||||
"tangerineWhistle" => Self::TangerineWhistle,
|
||||
"spuriousDragon" => Self::SpuriousDragon,
|
||||
"byzantium" => Self::Byzantium,
|
||||
"constantinople" => Self::Constantinople,
|
||||
"petersburg" => Self::Petersburg,
|
||||
"istanbul" => Self::Istanbul,
|
||||
"berlin" => Self::Berlin,
|
||||
"london" => Self::London,
|
||||
"paris" => Self::Paris,
|
||||
"shanghai" => Self::Shanghai,
|
||||
"cancun" => Self::Cancun,
|
||||
_ => anyhow::bail!("Invalid EVM version: {}", value),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EVMVersion {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Homestead => write!(f, "homestead"),
|
||||
Self::TangerineWhistle => write!(f, "tangerineWhistle"),
|
||||
Self::SpuriousDragon => write!(f, "spuriousDragon"),
|
||||
Self::Byzantium => write!(f, "byzantium"),
|
||||
Self::Constantinople => write!(f, "constantinople"),
|
||||
Self::Petersburg => write!(f, "petersburg"),
|
||||
Self::Istanbul => write!(f, "istanbul"),
|
||||
Self::Berlin => write!(f, "berlin"),
|
||||
Self::London => write!(f, "london"),
|
||||
Self::Paris => write!(f, "paris"),
|
||||
Self::Shanghai => write!(f, "shanghai"),
|
||||
Self::Cancun => write!(f, "cancun"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//!
|
||||
//! The exit code constants.
|
||||
//!
|
||||
|
||||
/// The common application success exit code.
|
||||
pub const EXIT_CODE_SUCCESS: i32 = 0;
|
||||
|
||||
/// The common application failure exit code.
|
||||
pub const EXIT_CODE_FAILURE: i32 = 1;
|
||||
@@ -0,0 +1,43 @@
|
||||
//! The file extensions.
|
||||
|
||||
/// The manifest file extension.
|
||||
pub static EXTENSION_MANIFEST: &str = "toml";
|
||||
|
||||
/// The JSON data file extension.
|
||||
pub static EXTENSION_JSON: &str = "json";
|
||||
|
||||
/// The ABI file extension.
|
||||
pub static EXTENSION_ABI: &str = "abi";
|
||||
|
||||
/// The Yul IR file extension.
|
||||
pub static EXTENSION_YUL: &str = "yul";
|
||||
|
||||
/// The EVM legacy assembly IR file extension.
|
||||
pub static EXTENSION_EVMLA: &str = "evmla";
|
||||
|
||||
/// The Ethereal IR file extension.
|
||||
pub static EXTENSION_ETHIR: &str = "ethir";
|
||||
|
||||
/// The EVM file extension.
|
||||
pub static EXTENSION_EVM: &str = "evm";
|
||||
|
||||
/// The EVM bytecode file extension.
|
||||
pub static EXTENSION_EVM_BINARY: &str = "bin";
|
||||
|
||||
/// The Solidity file extension.
|
||||
pub static EXTENSION_SOLIDITY: &str = "sol";
|
||||
|
||||
/// The LLL IR file extension.
|
||||
pub static EXTENSION_LLL: &str = "lll";
|
||||
|
||||
/// The LLVM source code file extension.
|
||||
pub static EXTENSION_LLVM_SOURCE: &str = "ll";
|
||||
|
||||
/// The LLVM bitcode file extension.
|
||||
pub static EXTENSION_LLVM_BINARY: &str = "bc";
|
||||
|
||||
/// The PolkaVM assembly file extension.
|
||||
pub static EXTENSION_POLKAVM_ASSEMBLY: &str = "pvmasm";
|
||||
|
||||
/// The PolkaVM bytecode file extension.
|
||||
pub static EXTENSION_POLKAVM_BINARY: &str = "pvm";
|
||||
@@ -0,0 +1,19 @@
|
||||
//! The compiler common library.
|
||||
|
||||
pub(crate) mod base;
|
||||
pub(crate) mod bit_length;
|
||||
pub(crate) mod byte_length;
|
||||
pub(crate) mod evm_version;
|
||||
pub(crate) mod exit_code;
|
||||
pub(crate) mod extension;
|
||||
pub(crate) mod polkavm;
|
||||
pub(crate) mod utils;
|
||||
|
||||
pub use self::base::*;
|
||||
pub use self::bit_length::*;
|
||||
pub use self::byte_length::*;
|
||||
pub use self::evm_version::EVMVersion;
|
||||
pub use self::exit_code::*;
|
||||
pub use self::extension::*;
|
||||
pub use self::polkavm::address::*;
|
||||
pub use self::utils::*;
|
||||
@@ -0,0 +1,115 @@
|
||||
//! The PolkaVM address constants.
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_TO_L1: u16 = 0xFFFF;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_PRECOMPILE: u16 = 0xFFFD;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_META: u16 = 0xFFFC;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_MIMIC_CALL: u16 = 0xFFFB;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_MIMIC_CALL: u16 = 0xFFFA;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_MIMIC_CALL_BYREF: u16 = 0xFFF9;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_MIMIC_CALL_BYREF: u16 = 0xFFF8;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_RAW_FAR_CALL: u16 = 0xFFF7;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_RAW_FAR_CALL_BYREF: u16 = 0xFFF6;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_CALL: u16 = 0xFFF5;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SYSTEM_CALL_BYREF: u16 = 0xFFF4;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SET_CONTEXT_VALUE_CALL: u16 = 0xFFF3;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_SET_PUBDATA_PRICE: u16 = 0xFFF2;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_INCREMENT_TX_COUNTER: u16 = 0xFFF1;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_PTR_CALLDATA: u16 = 0xFFF0;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_CALL_FLAGS: u16 = 0xFFEF;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_PTR_RETURN_DATA: u16 = 0xFFEE;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_EVENT_INITIALIZE: u16 = 0xFFED;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_EVENT_WRITE: u16 = 0xFFEC;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_LOAD_CALLDATA: u16 = 0xFFEB;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_LOAD_RETURN_DATA: u16 = 0xFFEA;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_ADD: u16 = 0xFFE9;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_SHRINK: u16 = 0xFFE8;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_PACK: u16 = 0xFFE7;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_MULTIPLICATION_HIGH_REGISTER: u16 = 0xFFE6;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_GET_GLOBAL_EXTRA_ABI_DATA: u16 = 0xFFE5;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_DATA_LOAD: u16 = 0xFFE4;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_DATA_COPY: u16 = 0xFFE3;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_DATA_SIZE: u16 = 0xFFE2;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_DECLARE: u16 = 0xFFE1;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_SET: u16 = 0xFFE0;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_FINALIZE: u16 = 0xFFDF;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_CONST_ARRAY_GET: u16 = 0xFFDE;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_DECOMMIT: u16 = 0xFFDD;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_LOAD_DECOMMIT: u16 = 0xFFDC;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_RETURN_FORWARD: u16 = 0xFFDB;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_REVERT_FORWARD: u16 = 0xFFDA;
|
||||
|
||||
/// The corresponding simulation predefined address.
|
||||
pub const POLKAVM_ADDRESS_ACTIVE_PTR_SWAP: u16 = 0xFFD9;
|
||||
@@ -0,0 +1,5 @@
|
||||
//!
|
||||
//! The PolkaVM constants.
|
||||
//!
|
||||
|
||||
pub mod address;
|
||||
@@ -0,0 +1,27 @@
|
||||
//! The compiler common utils.
|
||||
|
||||
/// Deserializes a `serde_json` object from slice with the recursion limit disabled.
|
||||
/// Must be used for all JSON I/O to avoid crashes due to the aforementioned limit.
|
||||
pub fn deserialize_from_slice<O>(input: &[u8]) -> anyhow::Result<O>
|
||||
where
|
||||
O: serde::de::DeserializeOwned,
|
||||
{
|
||||
let mut deserializer = serde_json::Deserializer::from_slice(input);
|
||||
deserializer.disable_recursion_limit();
|
||||
let deserializer = serde_stacker::Deserializer::new(&mut deserializer);
|
||||
let result = O::deserialize(deserializer)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Deserializes a `serde_json` object from string with the recursion limit disabled.
|
||||
/// Must be used for all JSON I/O to avoid crashes due to the aforementioned limit.
|
||||
pub fn deserialize_from_str<O>(input: &str) -> anyhow::Result<O>
|
||||
where
|
||||
O: serde::de::DeserializeOwned,
|
||||
{
|
||||
let mut deserializer = serde_json::Deserializer::from_str(input);
|
||||
deserializer.disable_recursion_limit();
|
||||
let deserializer = serde_stacker::Deserializer::new(&mut deserializer);
|
||||
let result = O::deserialize(deserializer)?;
|
||||
Ok(result)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "revive-differential"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
evm-interpreter = { workspace = true }
|
||||
primitive-types = { workspace = true }
|
||||
alloy-primitives = { workspace = true }
|
||||
@@ -0,0 +1,159 @@
|
||||
use alloy_primitives::{keccak256, Address, B256};
|
||||
use evm_interpreter::{
|
||||
interpreter::{EtableInterpreter, RunInterpreter},
|
||||
trap::CallCreateTrap,
|
||||
Context, Etable, ExitError, Log, Machine, RuntimeBackend, RuntimeBaseBackend,
|
||||
RuntimeEnvironment, RuntimeState, TransactionContext, Valids,
|
||||
};
|
||||
use primitive_types::{H160, H256, U256};
|
||||
|
||||
static RUNTIME_ETABLE: Etable<RuntimeState, UnimplementedHandler, CallCreateTrap> =
|
||||
Etable::runtime();
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UnimplementedHandler {
|
||||
logs: Vec<Log>,
|
||||
}
|
||||
|
||||
impl RuntimeEnvironment for UnimplementedHandler {
|
||||
fn block_hash(&self, _number: U256) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_number(&self) -> U256 {
|
||||
U256::from(123)
|
||||
}
|
||||
fn block_coinbase(&self) -> H160 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_timestamp(&self) -> U256 {
|
||||
U256::from(456)
|
||||
}
|
||||
fn block_difficulty(&self) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_randomness(&self) -> Option<H256> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_gas_limit(&self) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn block_base_fee_per_gas(&self) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn chain_id(&self) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeBaseBackend for UnimplementedHandler {
|
||||
fn balance(&self, _address: H160) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn code_size(&self, _address: H160) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn code_hash(&self, _address: H160) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
fn code(&self, _address: H160) -> Vec<u8> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn storage(&self, _address: H160, _index: H256) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn exists(&self, _address: H160) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn nonce(&self, _address: H160) -> U256 {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeBackend for UnimplementedHandler {
|
||||
fn original_storage(&self, _address: H160, _index: H256) -> H256 {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn deleted(&self, _address: H160) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
fn is_cold(&self, _address: H160, _index: Option<H256>) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn mark_hot(&mut self, _address: H160, _index: Option<H256>) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn set_storage(&mut self, _address: H160, _index: H256, _value: H256) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn log(&mut self, log: Log) -> Result<(), ExitError> {
|
||||
self.logs.push(log);
|
||||
Ok(())
|
||||
}
|
||||
fn mark_delete(&mut self, _address: H160) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn reset_storage(&mut self, _address: H160) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn set_code(&mut self, _address: H160, _code: Vec<u8>) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
fn reset_balance(&mut self, _address: H160) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn deposit(&mut self, _address: H160, _value: U256) {
|
||||
unimplemented!()
|
||||
}
|
||||
fn withdrawal(&mut self, _address: H160, _value: U256) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn inc_nonce(&mut self, _address: H160) -> Result<(), ExitError> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PreparedEvm {
|
||||
pub valids: Valids,
|
||||
pub vm: Machine<RuntimeState>,
|
||||
}
|
||||
|
||||
pub fn prepare(code: Vec<u8>, data: Vec<u8>) -> PreparedEvm {
|
||||
let address = Address::default().create2(B256::default(), keccak256([]).0);
|
||||
let caller = Address::default().create2(B256::default(), keccak256([]).0);
|
||||
|
||||
let state = RuntimeState {
|
||||
context: Context {
|
||||
address: H160::from(address.0 .0),
|
||||
caller: H160::from(caller.0 .0),
|
||||
apparent_value: U256::default(),
|
||||
},
|
||||
transaction_context: TransactionContext {
|
||||
gas_price: U256::default(),
|
||||
origin: H160::default(),
|
||||
}
|
||||
.into(),
|
||||
retbuf: Vec::new(),
|
||||
};
|
||||
|
||||
PreparedEvm {
|
||||
valids: Valids::new(&code[..]),
|
||||
vm: evm_interpreter::Machine::new(code.into(), data.to_vec().into(), 1024, 0xFFFF, state),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute(pre: PreparedEvm) -> (Vec<u8>, Vec<Log>) {
|
||||
let mut vm = EtableInterpreter::new_valid(pre.vm, &RUNTIME_ETABLE, pre.valids);
|
||||
let mut handler = UnimplementedHandler::default();
|
||||
vm.run(&mut handler).exit().unwrap().unwrap();
|
||||
(vm.retval.clone(), handler.logs)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "revive-integration"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
description = "revive compiler integration test cases"
|
||||
|
||||
[dependencies]
|
||||
polkavm = { workspace = true }
|
||||
alloy-primitives = { workspace = true }
|
||||
alloy-sol-types = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
revive-solidity = { workspace = true }
|
||||
revive-differential = { workspace = true }
|
||||
revive-llvm-context = { workspace = true }
|
||||
revive-common = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
sha1 = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"Baseline": 934,
|
||||
"Computation": 4360,
|
||||
"DivisionArithmetics": 39824,
|
||||
"ERC20": 46471,
|
||||
"Events": 1749,
|
||||
"FibonacciIterative": 2973,
|
||||
"Flipper": 3563,
|
||||
"SHA1": 32543
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Baseline {
|
||||
function baseline() public payable {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Bitwise {
|
||||
function opByte(uint i, uint x) public payable returns (uint ret) {
|
||||
assembly {
|
||||
ret := byte(i, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Block {
|
||||
function timestamp() public view returns (uint ret) {
|
||||
ret = block.timestamp;
|
||||
}
|
||||
|
||||
function number() public view returns (uint ret) {
|
||||
ret = block.number;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Call {
|
||||
function value_transfer(address payable destination) public payable {
|
||||
destination.transfer(msg.value);
|
||||
}
|
||||
|
||||
function echo(bytes memory payload) public pure returns (bytes memory) {
|
||||
return payload;
|
||||
}
|
||||
|
||||
function call(
|
||||
address callee,
|
||||
bytes memory payload
|
||||
) public pure returns (bytes memory) {
|
||||
return Call(callee).echo(payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Computation {
|
||||
function triangle_number(int64 n) public pure returns (int64 sum) {
|
||||
unchecked {
|
||||
for (int64 x = 1; x <= n; x++) {
|
||||
sum += x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function odd_product(int32 n) public pure returns (int64) {
|
||||
unchecked {
|
||||
int64 prod = 1;
|
||||
for (int32 x = 1; x <= n; x++) {
|
||||
prod *= 2 * int64(x) - 1;
|
||||
}
|
||||
return prod;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Context {
|
||||
function address_this() public view returns (address ret) {
|
||||
ret = address(this);
|
||||
}
|
||||
|
||||
function caller() public view returns (address ret) {
|
||||
ret = msg.sender;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.24;
|
||||
|
||||
contract CreateA {
|
||||
address creator;
|
||||
|
||||
constructor() payable {
|
||||
creator = msg.sender;
|
||||
}
|
||||
}
|
||||
|
||||
contract CreateB {
|
||||
receive() external payable {
|
||||
new CreateA{value: msg.value}();
|
||||
}
|
||||
|
||||
fallback() external {
|
||||
new CreateA{salt: hex"01"}();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract DivisionArithmetics {
|
||||
function div(uint n, uint d) public pure returns (uint q) {
|
||||
assembly {
|
||||
q := div(n, d)
|
||||
}
|
||||
}
|
||||
|
||||
function sdiv(int n, int d) public pure returns (int q) {
|
||||
assembly {
|
||||
q := sdiv(n, d)
|
||||
}
|
||||
}
|
||||
|
||||
function mod(uint n, uint d) public pure returns (uint r) {
|
||||
assembly {
|
||||
r := mod(n, d)
|
||||
}
|
||||
}
|
||||
|
||||
function smod(int n, int d) public pure returns (int r) {
|
||||
assembly {
|
||||
r := smod(n, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol
|
||||
interface IERC20 {
|
||||
function totalSupply() external view returns (uint);
|
||||
|
||||
function balanceOf(address account) external view returns (uint);
|
||||
|
||||
function transfer(address recipient, uint amount) external returns (bool);
|
||||
|
||||
function allowance(
|
||||
address owner,
|
||||
address spender
|
||||
) external view returns (uint);
|
||||
|
||||
function approve(address spender, uint amount) external returns (bool);
|
||||
|
||||
function transferFrom(
|
||||
address sender,
|
||||
address recipient,
|
||||
uint amount
|
||||
) external returns (bool);
|
||||
|
||||
event Transfer(address indexed from, address indexed to, uint value);
|
||||
event Approval(address indexed owner, address indexed spender, uint value);
|
||||
}
|
||||
|
||||
contract ERC20 is IERC20 {
|
||||
uint public totalSupply;
|
||||
mapping(address => uint) public balanceOf;
|
||||
mapping(address => mapping(address => uint)) public allowance;
|
||||
string public name = "Solidity by Example";
|
||||
string public symbol = "SOLBYEX";
|
||||
uint8 public decimals = 18;
|
||||
|
||||
function transfer(address recipient, uint amount) external returns (bool) {
|
||||
balanceOf[msg.sender] -= amount;
|
||||
balanceOf[recipient] += amount;
|
||||
emit Transfer(msg.sender, recipient, amount);
|
||||
return true;
|
||||
}
|
||||
|
||||
function approve(address spender, uint amount) external returns (bool) {
|
||||
allowance[msg.sender][spender] = amount;
|
||||
emit Approval(msg.sender, spender, amount);
|
||||
return true;
|
||||
}
|
||||
|
||||
function transferFrom(
|
||||
address sender,
|
||||
address recipient,
|
||||
uint amount
|
||||
) external returns (bool) {
|
||||
allowance[sender][msg.sender] -= amount;
|
||||
balanceOf[sender] -= amount;
|
||||
balanceOf[recipient] += amount;
|
||||
emit Transfer(sender, recipient, amount);
|
||||
return true;
|
||||
}
|
||||
|
||||
function mint(uint amount) external {
|
||||
balanceOf[msg.sender] += amount;
|
||||
totalSupply += amount;
|
||||
emit Transfer(address(0), msg.sender, amount);
|
||||
}
|
||||
|
||||
function burn(uint amount) external {
|
||||
balanceOf[msg.sender] -= amount;
|
||||
totalSupply -= amount;
|
||||
emit Transfer(msg.sender, address(0), amount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Events {
|
||||
event A() anonymous;
|
||||
event E(uint, uint indexed, uint indexed, uint indexed);
|
||||
|
||||
function emitEvent(uint topics) public {
|
||||
if (topics == 0) {
|
||||
emit A();
|
||||
} else {
|
||||
emit E(topics, 1, 2, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract ExtCode {
|
||||
function ExtCodeSize(address who) public view returns (uint ret) {
|
||||
assembly {
|
||||
ret := extcodesize(who)
|
||||
}
|
||||
}
|
||||
|
||||
function CodeSize() public pure returns (uint ret) {
|
||||
assembly {
|
||||
ret := codesize()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// SPDX-License-Identifier: UNLICENSED
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
// https://medium.com/coinmonks/fibonacci-in-solidity-8477d907e22a
|
||||
|
||||
contract FibonacciRecursive {
|
||||
function f(uint n) internal pure returns (uint) {
|
||||
if (n <= 1) {
|
||||
return n;
|
||||
} else {
|
||||
return f(n - 1) + f(n - 2);
|
||||
}
|
||||
}
|
||||
|
||||
function fib3(uint n) public pure returns (uint) {
|
||||
return f(n);
|
||||
}
|
||||
}
|
||||
|
||||
contract FibonacciIterative {
|
||||
function fib3(uint n) external pure returns (uint b) {
|
||||
if (n == 0) {
|
||||
return 0;
|
||||
}
|
||||
uint a = 1;
|
||||
b = 1;
|
||||
for (uint i = 2; i < n; i++) {
|
||||
unchecked {
|
||||
uint c = a + b;
|
||||
a = b;
|
||||
b = c;
|
||||
}
|
||||
}
|
||||
return b;
|
||||
}
|
||||
}
|
||||
|
||||
contract FibonacciBinet {
|
||||
function fib3(uint n) external pure returns (uint a) {
|
||||
if (n == 0) {
|
||||
return 0;
|
||||
}
|
||||
uint h = n / 2;
|
||||
uint mask = 1;
|
||||
// find highest set bit in n
|
||||
while (mask <= h) {
|
||||
mask <<= 1;
|
||||
}
|
||||
mask >>= 1;
|
||||
a = 1;
|
||||
uint b = 1;
|
||||
uint c;
|
||||
while (mask > 0) {
|
||||
c = a * a + b * b;
|
||||
if (n & mask > 0) {
|
||||
b = b * (b + 2 * a);
|
||||
a = c;
|
||||
} else {
|
||||
a = a * (2 * b - a);
|
||||
b = c;
|
||||
}
|
||||
mask >>= 1;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract MCopy {
|
||||
function memcpy(bytes memory payload) public pure returns (bytes memory) {
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract MSize {
|
||||
uint[] public data;
|
||||
|
||||
function mSize() public pure returns (uint size) {
|
||||
assembly {
|
||||
size := msize()
|
||||
}
|
||||
}
|
||||
|
||||
function mStore100() public pure returns (uint size) {
|
||||
assembly {
|
||||
mstore(100, msize())
|
||||
size := msize()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
// SPDX-License-Identifier: BSD-2-Clause
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
contract SHA1 {
|
||||
function sha1(bytes memory data) public pure returns (bytes20 ret) {
|
||||
assembly {
|
||||
// Get a safe scratch location
|
||||
let scratch := mload(0x40)
|
||||
|
||||
// Get the data length, and point data at the first byte
|
||||
let len := mload(data)
|
||||
data := add(data, 32)
|
||||
|
||||
// Find the length after padding
|
||||
let totallen := add(and(add(len, 1), 0xFFFFFFFFFFFFFFC0), 64)
|
||||
switch lt(sub(totallen, len), 9)
|
||||
case 1 {
|
||||
totallen := add(totallen, 64)
|
||||
}
|
||||
|
||||
let h := 0x6745230100EFCDAB890098BADCFE001032547600C3D2E1F0
|
||||
|
||||
function readword(ptr, off, count) -> result {
|
||||
result := 0
|
||||
if lt(off, count) {
|
||||
result := mload(add(ptr, off))
|
||||
count := sub(count, off)
|
||||
if lt(count, 32) {
|
||||
let mask := not(sub(exp(256, sub(32, count)), 1))
|
||||
result := and(result, mask)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
let i := 0
|
||||
} lt(i, totallen) {
|
||||
i := add(i, 64)
|
||||
} {
|
||||
mstore(scratch, readword(data, i, len))
|
||||
mstore(add(scratch, 32), readword(data, add(i, 32), len))
|
||||
|
||||
// If we loaded the last byte, store the terminator byte
|
||||
switch lt(sub(len, i), 64)
|
||||
case 1 {
|
||||
mstore8(add(scratch, sub(len, i)), 0x80)
|
||||
}
|
||||
|
||||
// If this is the last block, store the length
|
||||
switch eq(i, sub(totallen, 64))
|
||||
case 1 {
|
||||
mstore(
|
||||
add(scratch, 32),
|
||||
or(mload(add(scratch, 32)), mul(len, 8))
|
||||
)
|
||||
}
|
||||
|
||||
// Expand the 16 32-bit words into 80
|
||||
for {
|
||||
let j := 64
|
||||
} lt(j, 128) {
|
||||
j := add(j, 12)
|
||||
} {
|
||||
let temp := xor(
|
||||
xor(
|
||||
mload(add(scratch, sub(j, 12))),
|
||||
mload(add(scratch, sub(j, 32)))
|
||||
),
|
||||
xor(
|
||||
mload(add(scratch, sub(j, 56))),
|
||||
mload(add(scratch, sub(j, 64)))
|
||||
)
|
||||
)
|
||||
temp := or(
|
||||
and(
|
||||
mul(temp, 2),
|
||||
0xFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFE
|
||||
),
|
||||
and(
|
||||
div(temp, 0x80000000),
|
||||
0x0000000100000001000000010000000100000001000000010000000100000001
|
||||
)
|
||||
)
|
||||
mstore(add(scratch, j), temp)
|
||||
}
|
||||
for {
|
||||
let j := 128
|
||||
} lt(j, 320) {
|
||||
j := add(j, 24)
|
||||
} {
|
||||
let temp := xor(
|
||||
xor(
|
||||
mload(add(scratch, sub(j, 24))),
|
||||
mload(add(scratch, sub(j, 64)))
|
||||
),
|
||||
xor(
|
||||
mload(add(scratch, sub(j, 112))),
|
||||
mload(add(scratch, sub(j, 128)))
|
||||
)
|
||||
)
|
||||
temp := or(
|
||||
and(
|
||||
mul(temp, 4),
|
||||
0xFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFC
|
||||
),
|
||||
and(
|
||||
div(temp, 0x40000000),
|
||||
0x0000000300000003000000030000000300000003000000030000000300000003
|
||||
)
|
||||
)
|
||||
mstore(add(scratch, j), temp)
|
||||
}
|
||||
|
||||
let x := h
|
||||
let f := 0
|
||||
let k := 0
|
||||
for {
|
||||
let j := 0
|
||||
} lt(j, 80) {
|
||||
j := add(j, 1)
|
||||
} {
|
||||
switch div(j, 20)
|
||||
case 0 {
|
||||
// f = d xor (b and (c xor d))
|
||||
f := xor(
|
||||
div(x, 0x100000000000000000000),
|
||||
div(x, 0x10000000000)
|
||||
)
|
||||
f := and(div(x, 0x1000000000000000000000000000000), f)
|
||||
f := xor(div(x, 0x10000000000), f)
|
||||
k := 0x5A827999
|
||||
}
|
||||
case 1 {
|
||||
// f = b xor c xor d
|
||||
f := xor(
|
||||
div(x, 0x1000000000000000000000000000000),
|
||||
div(x, 0x100000000000000000000)
|
||||
)
|
||||
f := xor(div(x, 0x10000000000), f)
|
||||
k := 0x6ED9EBA1
|
||||
}
|
||||
case 2 {
|
||||
// f = (b and c) or (d and (b or c))
|
||||
f := or(
|
||||
div(x, 0x1000000000000000000000000000000),
|
||||
div(x, 0x100000000000000000000)
|
||||
)
|
||||
f := and(div(x, 0x10000000000), f)
|
||||
f := or(
|
||||
and(
|
||||
div(x, 0x1000000000000000000000000000000),
|
||||
div(x, 0x100000000000000000000)
|
||||
),
|
||||
f
|
||||
)
|
||||
k := 0x8F1BBCDC
|
||||
}
|
||||
case 3 {
|
||||
// f = b xor c xor d
|
||||
f := xor(
|
||||
div(x, 0x1000000000000000000000000000000),
|
||||
div(x, 0x100000000000000000000)
|
||||
)
|
||||
f := xor(div(x, 0x10000000000), f)
|
||||
k := 0xCA62C1D6
|
||||
}
|
||||
// temp = (a leftrotate 5) + f + e + k + w[i]
|
||||
let temp := and(
|
||||
div(
|
||||
x,
|
||||
0x80000000000000000000000000000000000000000000000
|
||||
),
|
||||
0x1F
|
||||
)
|
||||
temp := or(
|
||||
and(
|
||||
div(x, 0x800000000000000000000000000000000000000),
|
||||
0xFFFFFFE0
|
||||
),
|
||||
temp
|
||||
)
|
||||
temp := add(f, temp)
|
||||
temp := add(and(x, 0xFFFFFFFF), temp)
|
||||
temp := add(k, temp)
|
||||
temp := add(
|
||||
div(
|
||||
mload(add(scratch, mul(j, 4))),
|
||||
0x100000000000000000000000000000000000000000000000000000000
|
||||
),
|
||||
temp
|
||||
)
|
||||
x := or(
|
||||
div(x, 0x10000000000),
|
||||
mul(temp, 0x10000000000000000000000000000000000000000)
|
||||
)
|
||||
x := or(
|
||||
and(
|
||||
x,
|
||||
0xFFFFFFFF00FFFFFFFF000000000000FFFFFFFF00FFFFFFFF
|
||||
),
|
||||
mul(
|
||||
or(
|
||||
and(div(x, 0x4000000000000), 0xC0000000),
|
||||
and(div(x, 0x400000000000000000000), 0x3FFFFFFF)
|
||||
),
|
||||
0x100000000000000000000
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
h := and(
|
||||
add(h, x),
|
||||
0xFFFFFFFF00FFFFFFFF00FFFFFFFF00FFFFFFFF00FFFFFFFF
|
||||
)
|
||||
}
|
||||
ret := mul(
|
||||
or(
|
||||
or(
|
||||
or(
|
||||
or(
|
||||
and(
|
||||
div(h, 0x100000000),
|
||||
0xFFFFFFFF00000000000000000000000000000000
|
||||
),
|
||||
and(
|
||||
div(h, 0x1000000),
|
||||
0xFFFFFFFF000000000000000000000000
|
||||
)
|
||||
),
|
||||
and(div(h, 0x10000), 0xFFFFFFFF0000000000000000)
|
||||
),
|
||||
and(div(h, 0x100), 0xFFFFFFFF00000000)
|
||||
),
|
||||
and(h, 0xFFFFFFFF)
|
||||
),
|
||||
0x1000000000000000000000000
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Storage {
|
||||
function transient(uint value) public returns (uint ret) {
|
||||
assembly {
|
||||
let slot := 123
|
||||
tstore(slot, value)
|
||||
let success := call(0, 0, 0, 0, 0, 0, 0)
|
||||
ret := tload(slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Value {
|
||||
function value() public payable returns (uint ret) {
|
||||
ret = msg.value;
|
||||
}
|
||||
|
||||
function balance_of(address _address) public view returns (uint ret) {
|
||||
ret = _address.balance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract Flipper {
|
||||
bool coin;
|
||||
|
||||
constructor(bool _coin) {
|
||||
coin = _coin;
|
||||
}
|
||||
|
||||
function flip() public {
|
||||
coin = !coin;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8;
|
||||
|
||||
contract MStore8 {
|
||||
function mStore8(uint value) public pure returns (uint256 word) {
|
||||
assembly {
|
||||
mstore8(0x80, value)
|
||||
word := mload(0x80)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
use alloy_primitives::{Address, I256, U256};
|
||||
use alloy_sol_types::{sol, SolCall, SolConstructor};
|
||||
|
||||
use revive_solidity::test_utils::*;
|
||||
|
||||
use crate::mock_runtime::{CallOutput, State};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Contract {
|
||||
pub name: &'static str,
|
||||
pub evm_runtime: Vec<u8>,
|
||||
pub pvm_runtime: Vec<u8>,
|
||||
pub calldata: Vec<u8>,
|
||||
}
|
||||
|
||||
macro_rules! case {
|
||||
// Arguments:
|
||||
// 1. The file name, expect to live under "../contracts/"
|
||||
// 2. The Solidity contract name
|
||||
// 3. The derived Solidity function call name
|
||||
// 4. The method name on [Contract]
|
||||
// 5. Any parameters to the Solidity functions
|
||||
($file_name:literal, $contract_name:ident, $contract_method:ident, $method_name:ident, $( $v:ident: $t:ty ),* ) => {
|
||||
impl Contract {
|
||||
pub fn $method_name($($v: $t),*) -> Self {
|
||||
let code = include_str!(concat!("../contracts/", $file_name));
|
||||
let args = $contract_name::$contract_method::new(($($v,)*)).abi_encode();
|
||||
let name = stringify!($contract_name);
|
||||
Contract::build(args, name, code)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Arguments:
|
||||
// 1. The file name, expect to live under "../contracts/"
|
||||
// 2. The Solidity contract name
|
||||
// 3. Raw Calldata
|
||||
// 4. The method name on [Contract]
|
||||
($file_name:literal, $contract_name:literal, $calldata:expr, $method_name:ident) => {
|
||||
impl Contract {
|
||||
pub fn $method_name() -> Self {
|
||||
let code = include_str!(concat!("../contracts/", $file_name));
|
||||
Contract::build($calldata, $contract_name, code)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
case!("Create.sol", "CreateA", vec![0; 4], create_a);
|
||||
case!("Create.sol", "CreateB", vec![0; 4], create_b);
|
||||
|
||||
sol!(contract Baseline { function baseline() public payable; });
|
||||
case!("Baseline.sol", Baseline, baselineCall, baseline,);
|
||||
|
||||
sol!(contract Flipper {
|
||||
constructor (bool);
|
||||
|
||||
function flip() public;
|
||||
});
|
||||
case!("flipper.sol", Flipper, flipCall, flipper,);
|
||||
case!("flipper.sol", Flipper, constructorCall, flipper_constructor, coin: bool);
|
||||
|
||||
sol!(contract Computation {
|
||||
function odd_product(int32 n) public pure returns (int64);
|
||||
function triangle_number(int64 n) public pure returns (int64 sum);
|
||||
});
|
||||
case!("Computation.sol", Computation, odd_productCall, odd_product, n: i32);
|
||||
case!("Computation.sol", Computation, triangle_numberCall, triangle_number, n: i64);
|
||||
|
||||
sol!(
|
||||
contract FibonacciRecursive {
|
||||
function fib3(uint n) public pure returns (uint);
|
||||
}
|
||||
);
|
||||
case!("Fibonacci.sol", FibonacciRecursive, fib3Call, fib_recursive, n: U256);
|
||||
|
||||
sol!(
|
||||
contract FibonacciIterative {
|
||||
function fib3(uint n) external pure returns (uint b);
|
||||
}
|
||||
);
|
||||
case!("Fibonacci.sol", FibonacciIterative, fib3Call, fib_iterative, n: U256);
|
||||
|
||||
sol!(
|
||||
contract FibonacciBinet {
|
||||
function fib3(uint n) external pure returns (uint a);
|
||||
}
|
||||
);
|
||||
case!("Fibonacci.sol", FibonacciBinet, fib3Call, fib_binet, n: U256);
|
||||
|
||||
sol!(
|
||||
contract SHA1 {
|
||||
function sha1(bytes memory data) public pure returns (bytes20 ret);
|
||||
}
|
||||
);
|
||||
case!("SHA1.sol", SHA1, sha1Call, sha1, pre: Vec<u8>);
|
||||
|
||||
sol!(
|
||||
contract ERC20 {
|
||||
function totalSupply() external view returns (uint);
|
||||
|
||||
function balanceOf(address account) external view returns (uint);
|
||||
|
||||
function transfer(address recipient, uint amount) external returns (bool);
|
||||
|
||||
function allowance(
|
||||
address owner,
|
||||
address spender
|
||||
) external view returns (uint);
|
||||
|
||||
function approve(address spender, uint amount) external returns (bool);
|
||||
|
||||
function transferFrom(
|
||||
address sender,
|
||||
address recipient,
|
||||
uint amount
|
||||
) external returns (bool);
|
||||
|
||||
event Transfer(address indexed from, address indexed to, uint value);
|
||||
event Approval(address indexed owner, address indexed spender, uint value);
|
||||
}
|
||||
);
|
||||
case!("ERC20.sol", ERC20, totalSupplyCall, erc20,);
|
||||
|
||||
sol!(
|
||||
contract Block {
|
||||
function timestamp() public view returns (uint ret);
|
||||
|
||||
function number() public view returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Block.sol", Block, numberCall, block_number,);
|
||||
case!("Block.sol", Block, timestampCall, block_timestamp,);
|
||||
|
||||
sol!(
|
||||
contract Context {
|
||||
function address_this() public view returns (address);
|
||||
|
||||
function caller() public pure returns (address);
|
||||
}
|
||||
);
|
||||
case!("Context.sol", Context, address_thisCall, context_address,);
|
||||
case!("Context.sol", Context, callerCall, context_caller,);
|
||||
|
||||
sol!(
|
||||
contract DivisionArithmetics {
|
||||
function div(uint n, uint d) public pure returns (uint q);
|
||||
|
||||
function sdiv(int n, int d) public pure returns (int q);
|
||||
|
||||
function mod(uint n, uint d) public pure returns (uint r);
|
||||
|
||||
function smod(int n, int d) public pure returns (int r);
|
||||
}
|
||||
);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, divCall, division_arithmetics_div, n: U256, d: U256);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, sdivCall, division_arithmetics_sdiv, n: I256, d: I256);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, modCall, division_arithmetics_mod, n: U256, d: U256);
|
||||
case!("DivisionArithmetics.sol", DivisionArithmetics, smodCall, division_arithmetics_smod, n: I256, d: I256);
|
||||
|
||||
sol!(
|
||||
contract MStore8 {
|
||||
function mStore8(uint value) public pure returns (uint256 word);
|
||||
}
|
||||
);
|
||||
case!("mStore8.sol", MStore8, mStore8Call, mstore8, value: U256);
|
||||
|
||||
sol!(
|
||||
contract Events {
|
||||
event A(uint) anonymous;
|
||||
event E(uint indexed, uint indexed, uint indexed);
|
||||
|
||||
function emitEvent(uint topics) public;
|
||||
}
|
||||
);
|
||||
case!("Events.sol", Events, emitEventCall, event, topics: U256);
|
||||
|
||||
sol!(
|
||||
contract ExtCode {
|
||||
function ExtCodeSize(address who) public view returns (uint ret);
|
||||
|
||||
function CodeSize() public pure returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("ExtCode.sol", ExtCode, ExtCodeSizeCall, ext_code_size, address: Address);
|
||||
case!("ExtCode.sol", ExtCode, CodeSizeCall, code_size,);
|
||||
|
||||
sol!(
|
||||
contract MCopy {
|
||||
function memcpy(bytes memory payload) public pure returns (bytes memory);
|
||||
}
|
||||
);
|
||||
case!("MCopy.sol", MCopy, memcpyCall, memcpy, payload: Vec<u8>);
|
||||
|
||||
sol!(
|
||||
contract Call {
|
||||
function value_transfer(address payable destination) public payable;
|
||||
|
||||
function echo(bytes memory payload) public payable returns (bytes memory);
|
||||
|
||||
function call(
|
||||
address callee,
|
||||
bytes memory payload
|
||||
) public payable returns (bytes memory);
|
||||
}
|
||||
);
|
||||
case!("Call.sol", Call, value_transferCall, call_value_transfer, destination: Address);
|
||||
case!("Call.sol", Call, callCall, call_call, destination: Address, payload: Vec<u8>);
|
||||
case!("Call.sol", "Call", vec![], call_constructor);
|
||||
|
||||
sol!(
|
||||
contract Value {
|
||||
function balance_of(address _address) public view returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Value.sol", Value, balance_ofCall, value_balance_of, address: Address);
|
||||
|
||||
sol!(
|
||||
contract Bitwise {
|
||||
function opByte(uint i, uint x) public payable returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Bitwise.sol", Bitwise, opByteCall, bitwise_byte, index: U256, value: U256);
|
||||
|
||||
sol!(
|
||||
contract Storage {
|
||||
function transient(uint value) public returns (uint ret);
|
||||
}
|
||||
);
|
||||
case!("Storage.sol", Storage, transientCall, storage_transient, value: U256);
|
||||
|
||||
impl Contract {
|
||||
/// Execute the contract.
|
||||
///
|
||||
/// Useful helper if the contract state can be ignored,
|
||||
/// as it spares the deploy transaciton.
|
||||
///
|
||||
/// - Inserts an account with given `code` into a new state.
|
||||
/// - Callee and caller account will be `Transaction::default_address()`.
|
||||
/// - Sets the calldata.
|
||||
/// - Doesn't execute the constructor or deploy code.
|
||||
/// - Calls the "call" export on a default backend config.
|
||||
pub fn execute(&self) -> (State, CallOutput) {
|
||||
State::default()
|
||||
.transaction()
|
||||
.with_default_account(&self.pvm_runtime)
|
||||
.calldata(self.calldata.clone())
|
||||
.call()
|
||||
}
|
||||
|
||||
fn build(calldata: Vec<u8>, name: &'static str, code: &str) -> Self {
|
||||
Self {
|
||||
name,
|
||||
evm_runtime: compile_evm_bin_runtime(name, code),
|
||||
pvm_runtime: compile_blob(name, code),
|
||||
calldata,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloy_primitives::U256;
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
use serde::{de::Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, fs::File};
|
||||
|
||||
use super::Contract;
|
||||
|
||||
#[test]
|
||||
fn codesize() {
|
||||
let path = "codesize.json";
|
||||
|
||||
let existing = File::open(path)
|
||||
.map(|file| {
|
||||
BTreeMap::<String, usize>::deserialize(&mut serde_json::Deserializer::from_reader(
|
||||
file,
|
||||
))
|
||||
.expect("should be able to deserialze codesize data")
|
||||
})
|
||||
.ok();
|
||||
|
||||
let extract_code_size = |compile: fn() -> Contract| {
|
||||
let contract = compile();
|
||||
let contract_length = contract.pvm_runtime.len();
|
||||
let size_change = existing
|
||||
.as_ref()
|
||||
.and_then(|map| map.get(contract.name))
|
||||
.filter(|old| **old != 0)
|
||||
.map(|old| {
|
||||
let old = *old as f32;
|
||||
let p = (contract_length as f32 - old) / old * 100.0;
|
||||
format!("({p}% change from {old} bytes)",)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
println!("{}: {contract_length} bytes {size_change}", contract.name);
|
||||
|
||||
(contract.name, contract_length)
|
||||
};
|
||||
|
||||
[
|
||||
Contract::baseline as fn() -> Contract,
|
||||
Contract::flipper as fn() -> Contract,
|
||||
(|| Contract::odd_product(0)) as fn() -> Contract,
|
||||
(|| Contract::fib_iterative(U256::ZERO)) as fn() -> Contract,
|
||||
Contract::erc20 as fn() -> Contract,
|
||||
(|| Contract::sha1(Vec::new())) as fn() -> Contract,
|
||||
(|| Contract::division_arithmetics_div(U256::ZERO, U256::ZERO)) as fn() -> Contract,
|
||||
(|| Contract::event(U256::ZERO)) as fn() -> Contract,
|
||||
]
|
||||
.into_par_iter()
|
||||
.map(extract_code_size)
|
||||
.collect::<BTreeMap<_, _>>()
|
||||
.serialize(&mut serde_json::Serializer::pretty(
|
||||
File::create(path).unwrap(),
|
||||
))
|
||||
.unwrap_or_else(|err| panic!("can not write codesize data to '{path}': {err}"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use alloy_primitives::{Address, U256};
|
||||
use cases::Contract;
|
||||
use mock_runtime::{CallOutput, State};
|
||||
|
||||
use crate::mock_runtime::{Event, ReturnFlags};
|
||||
|
||||
pub mod cases;
|
||||
pub mod mock_runtime;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub fn assert_success(contract: &Contract, differential: bool) -> (State, CallOutput) {
|
||||
let (state, output) = contract.execute();
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
if differential {
|
||||
let evm =
|
||||
revive_differential::prepare(contract.evm_runtime.clone(), contract.calldata.clone());
|
||||
let (evm_output, evm_log) = revive_differential::execute(evm);
|
||||
|
||||
assert_eq!(output.data.clone(), evm_output);
|
||||
assert_eq!(output.events.len(), evm_log.len());
|
||||
assert_eq!(
|
||||
output.events,
|
||||
evm_log
|
||||
.iter()
|
||||
.map(|log| Event {
|
||||
address: Address::from_slice(log.address.as_bytes()),
|
||||
data: log.data.clone(),
|
||||
topics: log
|
||||
.topics
|
||||
.iter()
|
||||
.map(|topic| U256::from_be_bytes(topic.0))
|
||||
.collect(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
(state, output)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,640 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use alloy_primitives::{keccak256, Address, FixedBytes, B256, I256, U256};
|
||||
use alloy_sol_types::{sol, SolCall, SolValue};
|
||||
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
|
||||
use sha1::Digest;
|
||||
|
||||
use revive_solidity::test_utils::*;
|
||||
|
||||
use crate::{
|
||||
assert_success,
|
||||
cases::Contract,
|
||||
mock_runtime::{self, ReturnFlags, State, Transaction},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn fibonacci() {
|
||||
let parameter = 6;
|
||||
|
||||
for contract in [
|
||||
Contract::fib_recursive(U256::from(parameter)),
|
||||
Contract::fib_iterative(U256::from(parameter)),
|
||||
Contract::fib_binet(U256::from(parameter)),
|
||||
] {
|
||||
let (_, output) = assert_success(&contract, true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::from(8);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipper() {
|
||||
let (state, address) = State::new_deployed(Contract::flipper_constructor(true));
|
||||
|
||||
let contract = Contract::flipper();
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.calldata(contract.calldata.clone())
|
||||
.callee(address)
|
||||
.call();
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
state.assert_storage_key(address, U256::ZERO, U256::ZERO);
|
||||
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.calldata(contract.calldata)
|
||||
.callee(address)
|
||||
.call();
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
state.assert_storage_key(address, U256::ZERO, U256::from(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_keccak_256() {
|
||||
sol!(
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
contract TestSha3 {
|
||||
function test(string memory _pre) external payable returns (bytes32);
|
||||
}
|
||||
);
|
||||
let source = r#"contract TestSha3 {
|
||||
function test(string memory _pre) external payable returns (bytes32 hash) {
|
||||
hash = keccak256(bytes(_pre));
|
||||
}
|
||||
}"#;
|
||||
let code = compile_blob("TestSha3", source);
|
||||
|
||||
let param = "hello";
|
||||
let input = TestSha3::testCall::new((param.to_string(),)).abi_encode();
|
||||
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&code)
|
||||
.calldata(input)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
let expected = keccak256(param.as_bytes());
|
||||
let received = FixedBytes::<32>::from_slice(&output.data);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erc20() {
|
||||
let _ = compile_blob("ERC20", include_str!("../contracts/ERC20.sol"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangle_number() {
|
||||
let (_, output) = assert_success(&Contract::triangle_number(13), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::try_from(91).unwrap();
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_product() {
|
||||
let (_, output) = assert_success(&Contract::odd_product(5), true);
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = I256::try_from(945i64).unwrap();
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msize_plain() {
|
||||
sol!(
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
contract MSize {
|
||||
function mSize() public pure returns (uint);
|
||||
}
|
||||
);
|
||||
let code = compile_blob_with_options(
|
||||
"MSize",
|
||||
include_str!("../contracts/MSize.sol"),
|
||||
false,
|
||||
revive_solidity::SolcPipeline::EVMLA,
|
||||
);
|
||||
|
||||
let input = MSize::mSizeCall::new(()).abi_encode();
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.calldata(input)
|
||||
.with_default_account(&code)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
// Solidity always stores the "free memory pointer" (32 byte int) at offset 64.
|
||||
let expected = U256::try_from(64 + 32).unwrap();
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transferred_value() {
|
||||
sol!(
|
||||
contract Value {
|
||||
function value() public payable returns (uint);
|
||||
}
|
||||
);
|
||||
let code = compile_blob("Value", include_str!("../contracts/Value.sol"));
|
||||
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.calldata(Value::valueCall::SELECTOR.to_vec())
|
||||
.callvalue(U256::from(123))
|
||||
.with_default_account(&code)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
let expected = I256::try_from(123).unwrap();
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msize_non_word_sized_access() {
|
||||
sol!(
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
contract MSize {
|
||||
function mStore100() public pure returns (uint);
|
||||
}
|
||||
);
|
||||
let code = compile_blob_with_options(
|
||||
"MSize",
|
||||
include_str!("../contracts/MSize.sol"),
|
||||
false,
|
||||
revive_solidity::SolcPipeline::Yul,
|
||||
);
|
||||
|
||||
let input = MSize::mStore100Call::new(()).abi_encode();
|
||||
let (_, output) = State::default()
|
||||
.transaction()
|
||||
.with_default_account(&code)
|
||||
.calldata(input)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
// https://docs.zksync.io/build/developer-reference/differences-with-ethereum.html#mstore-mload
|
||||
// "Unlike EVM, where the memory growth is in words, on zkEVM the memory growth is counted in bytes."
|
||||
// "For example, if you write mstore(100, 0) the msize on zkEVM will be 132, but on the EVM it will be 160."
|
||||
let expected = U256::try_from(132).unwrap();
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mstore8() {
|
||||
for (received, expected) in [
|
||||
(U256::MIN, U256::MIN),
|
||||
(
|
||||
U256::from(1),
|
||||
U256::from_str_radix(
|
||||
"452312848583266388373324160190187140051835877600158453279131187530910662656",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(2),
|
||||
U256::from_str_radix(
|
||||
"904625697166532776746648320380374280103671755200316906558262375061821325312",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(255),
|
||||
U256::from_str_radix(
|
||||
"115339776388732929035197660848497720713218148788040405586178452820382218977280",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(U256::from(256), U256::from(0)),
|
||||
(
|
||||
U256::from(257),
|
||||
U256::from_str_radix(
|
||||
"452312848583266388373324160190187140051835877600158453279131187530910662656",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(258),
|
||||
U256::from_str_radix(
|
||||
"904625697166532776746648320380374280103671755200316906558262375061821325312",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::from(123456789),
|
||||
U256::from_str_radix(
|
||||
"9498569820248594155839807363993929941088553429603327518861754938149123915776",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
(
|
||||
U256::MAX,
|
||||
U256::from_str_radix(
|
||||
"115339776388732929035197660848497720713218148788040405586178452820382218977280",
|
||||
10,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(parameter, expected)| {
|
||||
let (_, output) = assert_success(&Contract::mstore8(*parameter), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *expected)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha1() {
|
||||
let pre = vec![0xffu8; 512];
|
||||
let mut hasher = sha1::Sha1::new();
|
||||
hasher.update(&pre);
|
||||
let hash = hasher.finalize();
|
||||
|
||||
let (_, output) = assert_success(&Contract::sha1(pre), true);
|
||||
let expected = FixedBytes::<20>::from_slice(&hash[..]);
|
||||
let received = FixedBytes::<20>::from_slice(&output.data[..20]);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_number() {
|
||||
let (_, output) = assert_success(&Contract::block_number(), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::from(mock_runtime::State::BLOCK_NUMBER);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_timestamp() {
|
||||
let (_, output) = assert_success(&Contract::block_timestamp(), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
let expected = U256::from(mock_runtime::State::BLOCK_TIMESTAMP);
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address() {
|
||||
let contract = Contract::context_address();
|
||||
let (_, output) = assert_success(&contract, true);
|
||||
let received = Address::from_slice(&output.data[12..]);
|
||||
let expected = Transaction::default_address();
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caller() {
|
||||
let (_, output) = assert_success(&Contract::context_caller(), true);
|
||||
let received = Address::from_slice(&output.data[12..]);
|
||||
let expected = Transaction::default_address();
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_division() {
|
||||
let one = U256::from(1);
|
||||
let two = U256::from(2);
|
||||
let five = U256::from(5);
|
||||
for (received, expected) in [
|
||||
(five, five, one),
|
||||
(five, one, five),
|
||||
(U256::ZERO, U256::MAX, U256::ZERO),
|
||||
(five, two, two),
|
||||
(one, U256::ZERO, U256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_div(*n, *d), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_division() {
|
||||
let one = I256::try_from(1).unwrap();
|
||||
let two = I256::try_from(2).unwrap();
|
||||
let minus_two = I256::try_from(-2).unwrap();
|
||||
let five = I256::try_from(5).unwrap();
|
||||
let minus_five = I256::try_from(-5).unwrap();
|
||||
for (received, expected) in [
|
||||
(five, five, one),
|
||||
(five, one, five),
|
||||
(I256::ZERO, I256::MAX, I256::ZERO),
|
||||
(I256::ZERO, I256::MINUS_ONE, I256::ZERO),
|
||||
(five, two, two),
|
||||
(five, I256::MINUS_ONE, minus_five),
|
||||
(I256::MINUS_ONE, minus_two, I256::ZERO),
|
||||
(minus_five, minus_five, one),
|
||||
(minus_five, two, minus_two),
|
||||
(I256::MINUS_ONE, I256::MIN, I256::ZERO),
|
||||
(one, I256::ZERO, I256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_sdiv(*n, *d), true);
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_remainder() {
|
||||
let one = U256::from(1);
|
||||
let two = U256::from(2);
|
||||
let five = U256::from(5);
|
||||
for (received, expected) in [
|
||||
(five, five, U256::ZERO),
|
||||
(five, one, U256::ZERO),
|
||||
(U256::ZERO, U256::MAX, U256::ZERO),
|
||||
(U256::MAX, U256::MAX, U256::ZERO),
|
||||
(five, two, one),
|
||||
(two, five, two),
|
||||
(U256::MAX, U256::ZERO, U256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_mod(*n, *d), true);
|
||||
let received = U256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_remainder() {
|
||||
let one = I256::try_from(1).unwrap();
|
||||
let two = I256::try_from(2).unwrap();
|
||||
let minus_two = I256::try_from(-2).unwrap();
|
||||
let five = I256::try_from(5).unwrap();
|
||||
let minus_five = I256::try_from(-5).unwrap();
|
||||
for (received, expected) in [
|
||||
(five, five, I256::ZERO),
|
||||
(five, one, I256::ZERO),
|
||||
(I256::ZERO, I256::MAX, I256::ZERO),
|
||||
(I256::MAX, I256::MAX, I256::ZERO),
|
||||
(five, two, one),
|
||||
(two, five, two),
|
||||
(five, minus_five, I256::ZERO),
|
||||
(five, I256::MINUS_ONE, I256::ZERO),
|
||||
(five, minus_two, one),
|
||||
(minus_five, two, I256::MINUS_ONE),
|
||||
(minus_two, five, minus_two),
|
||||
(minus_five, minus_five, I256::ZERO),
|
||||
(minus_five, I256::MINUS_ONE, I256::ZERO),
|
||||
(minus_five, minus_two, I256::MINUS_ONE),
|
||||
(minus_two, minus_five, minus_two),
|
||||
(I256::MIN, I256::MINUS_ONE, I256::ZERO),
|
||||
(I256::ZERO, I256::ZERO, I256::ZERO),
|
||||
]
|
||||
.par_iter()
|
||||
.map(|(n, d, q)| {
|
||||
let (_, output) = assert_success(&Contract::division_arithmetics_smod(*n, *d), true);
|
||||
let received = I256::from_be_bytes::<32>(output.data.try_into().unwrap());
|
||||
(received, *q)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn events() {
|
||||
assert_success(&Contract::event(U256::ZERO), true);
|
||||
assert_success(&Contract::event(U256::from(123)), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create2() {
|
||||
let mut state = State::default();
|
||||
let contract_a = Contract::create_a();
|
||||
state.upload_code(&contract_a.pvm_runtime);
|
||||
|
||||
let contract = Contract::create_b();
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
assert_eq!(state.accounts().len(), 2);
|
||||
|
||||
for address in state.accounts().keys() {
|
||||
if *address != Transaction::default_address() {
|
||||
let derived_address = Transaction::default_address().create2(
|
||||
B256::from(U256::from(1)),
|
||||
keccak256(&contract_a.pvm_runtime).0,
|
||||
);
|
||||
assert_eq!(*address, derived_address);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create2_failure() {
|
||||
let mut state = State::default();
|
||||
let contract_a = Contract::create_a();
|
||||
state.upload_code(&contract_a.pvm_runtime);
|
||||
|
||||
let contract = Contract::create_b();
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata.clone())
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
// The address already exists, which should cause the contract to revert
|
||||
|
||||
let (_, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Revert);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_with_value() {
|
||||
let mut state = State::default();
|
||||
state.upload_code(&Contract::create_a().pvm_runtime);
|
||||
let amount = U256::from(123);
|
||||
|
||||
let contract = Contract::create_b();
|
||||
let (state, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.callvalue(amount)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
assert_eq!(state.accounts().len(), 2);
|
||||
|
||||
for (address, account) in state.accounts() {
|
||||
if *address == Transaction::default_address() {
|
||||
assert_eq!(account.value, U256::ZERO);
|
||||
} else {
|
||||
assert_eq!(account.value, amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_code_size() {
|
||||
let contract = Contract::ext_code_size(Transaction::default_address());
|
||||
let (_, output) = assert_success(&contract, false);
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
let expected = U256::from(contract.pvm_runtime.len());
|
||||
assert_eq!(received, expected);
|
||||
|
||||
let contract = Contract::ext_code_size(Default::default());
|
||||
let (_, output) = assert_success(&contract, false);
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
let expected = U256::ZERO;
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_size() {
|
||||
let contract = Contract::code_size();
|
||||
let (_, output) = assert_success(&contract, false);
|
||||
let expected = U256::from(contract.pvm_runtime.len());
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
assert_eq!(expected, received);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_transfer() {
|
||||
// Succeeds in remix (shanghai) but traps the interpreter
|
||||
let (state, _) = assert_success(&Contract::call_value_transfer(Default::default()), false);
|
||||
|
||||
assert_eq!(state.accounts().len(), 2);
|
||||
assert!(state.accounts().get(&Address::default()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echo() {
|
||||
let (state, address) = State::new_deployed(Contract::call_constructor());
|
||||
|
||||
let expected = vec![1, 2, 3, 4, 5];
|
||||
let contract = Contract::call_call(address, expected.clone());
|
||||
let (_, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata)
|
||||
.call();
|
||||
|
||||
assert_eq!(output.flags, ReturnFlags::Success);
|
||||
|
||||
let received = alloy_primitives::Bytes::abi_decode(&output.data, true)
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
|
||||
assert_eq!(expected, received);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcopy() {
|
||||
let expected = vec![1, 2, 3];
|
||||
|
||||
let (_, output) = assert_success(&Contract::memcpy(expected.clone()), false);
|
||||
|
||||
let received = alloy_primitives::Bytes::abi_decode(&output.data, true)
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
|
||||
assert_eq!(expected, received);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance() {
|
||||
let (_, output) = assert_success(&Contract::value_balance_of(Default::default()), false);
|
||||
|
||||
let expected = U256::ZERO;
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
assert_eq!(expected, received);
|
||||
|
||||
let expected = U256::from(54589);
|
||||
let (mut state, address) = State::new_deployed(Contract::value_balance_of(Default::default()));
|
||||
state.accounts_mut().get_mut(&address).unwrap().value = expected;
|
||||
|
||||
let contract = Contract::value_balance_of(address);
|
||||
let (_, output) = state
|
||||
.transaction()
|
||||
.with_default_account(&contract.pvm_runtime)
|
||||
.calldata(contract.calldata)
|
||||
.call();
|
||||
|
||||
assert_eq!(ReturnFlags::Success, output.flags);
|
||||
|
||||
let received = U256::from_be_slice(&output.data);
|
||||
assert_eq!(expected, received)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitwise_byte() {
|
||||
assert_success(&Contract::bitwise_byte(U256::ZERO, U256::ZERO), true);
|
||||
assert_success(&Contract::bitwise_byte(U256::ZERO, U256::MAX), true);
|
||||
assert_success(&Contract::bitwise_byte(U256::MAX, U256::ZERO), true);
|
||||
assert_success(
|
||||
&Contract::bitwise_byte(U256::from_str("18446744073709551619").unwrap(), U256::MAX),
|
||||
true,
|
||||
);
|
||||
|
||||
let de_bruijn_sequence =
|
||||
hex::decode("4060503824160d0784426150b864361d0f88c4a27148ac5a2f198d46e391d8f4").unwrap();
|
||||
let value = U256::from_be_bytes::<32>(de_bruijn_sequence.clone().try_into().unwrap());
|
||||
|
||||
for (index, byte) in de_bruijn_sequence.iter().enumerate() {
|
||||
let (_, output) = assert_success(&Contract::bitwise_byte(U256::from(index), value), true);
|
||||
let expected = U256::from(*byte as i32);
|
||||
let received = U256::abi_decode(&output.data, true).unwrap();
|
||||
assert_eq!(expected, received)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transient_storage() {
|
||||
let expected = U256::MAX;
|
||||
let (state, output) = assert_success(&Contract::storage_transient(expected), false);
|
||||
let received = U256::abi_decode(&output.data, true).unwrap();
|
||||
assert_eq!(expected, received);
|
||||
|
||||
assert!(state
|
||||
.accounts()
|
||||
.values()
|
||||
.all(|account| account.storage.is_empty()));
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "revive-linker"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
description = "revive compiler linker utils"
|
||||
|
||||
[features]
|
||||
riscv-64 = []
|
||||
|
||||
[dependencies]
|
||||
inkwell = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
polkavm-linker = { workspace = true }
|
||||
polkavm-common = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
|
||||
revive-builtins = { workspace = true }
|
||||
lld-sys = { workspace = true }
|
||||
@@ -0,0 +1,87 @@
|
||||
use std::{env, ffi::CString, fs};
|
||||
|
||||
use lld_sys::LLDELFLink;
|
||||
use revive_builtins::COMPILER_RT;
|
||||
|
||||
const LINKER_SCRIPT: &str = r#"
|
||||
SECTIONS {
|
||||
.text : { KEEP(*(.text.polkavm_export)) *(.text .text.*) }
|
||||
}"#;
|
||||
|
||||
#[cfg(not(feature = "riscv-64"))]
|
||||
const BUILTINS_ARCHIVE_FILE: &str = "libclang_rt.builtins-riscv32.a";
|
||||
#[cfg(feature = "riscv-64")]
|
||||
const BUILTINS_ARCHIVE_FILE: &str = "libclang_rt.builtins-riscv64.a";
|
||||
|
||||
#[cfg(not(feature = "riscv-64"))]
|
||||
const BUILTINS_LIB_NAME: &str = "clang_rt.builtins-riscv32";
|
||||
#[cfg(feature = "riscv-64")]
|
||||
const BUILTINS_LIB_NAME: &str = "clang_rt.builtins-riscv64";
|
||||
|
||||
fn invoke_lld(cmd_args: &[&str]) -> bool {
|
||||
let c_strings = cmd_args
|
||||
.iter()
|
||||
.map(|arg| CString::new(*arg).expect("ld.lld args should not contain null bytes"))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let args: Vec<*const libc::c_char> = c_strings.iter().map(|arg| arg.as_ptr()).collect();
|
||||
|
||||
unsafe { LLDELFLink(args.as_ptr(), args.len()) == 0 }
|
||||
}
|
||||
|
||||
fn polkavm_linker<T: AsRef<[u8]>>(code: T) -> anyhow::Result<Vec<u8>> {
|
||||
let mut config = polkavm_linker::Config::default();
|
||||
config.set_strip(true);
|
||||
|
||||
polkavm_linker::program_from_elf(config, code.as_ref())
|
||||
.map_err(|reason| anyhow::anyhow!("polkavm linker failed: {}", reason))
|
||||
}
|
||||
|
||||
pub fn link<T: AsRef<[u8]>>(input: T) -> anyhow::Result<Vec<u8>> {
|
||||
let dir = tempfile::tempdir().expect("failed to create temp directory for linking");
|
||||
let output_path = dir.path().join("out.so");
|
||||
let object_path = dir.path().join("out.o");
|
||||
let linker_script_path = dir.path().join("linker.ld");
|
||||
let compiler_rt_path = dir.path().join(BUILTINS_ARCHIVE_FILE);
|
||||
|
||||
fs::write(&object_path, input).map_err(|msg| anyhow::anyhow!("{msg} {object_path:?}"))?;
|
||||
|
||||
if env::var("PVM_LINKER_DUMP_OBJ").is_ok() {
|
||||
fs::copy(&object_path, "/tmp/out.o")?;
|
||||
}
|
||||
|
||||
fs::write(&linker_script_path, LINKER_SCRIPT)
|
||||
.map_err(|msg| anyhow::anyhow!("{msg} {linker_script_path:?}"))?;
|
||||
|
||||
fs::write(&compiler_rt_path, COMPILER_RT)
|
||||
.map_err(|msg| anyhow::anyhow!("{msg} {compiler_rt_path:?}"))?;
|
||||
|
||||
let ld_args = [
|
||||
"ld.lld",
|
||||
"--lto=full",
|
||||
"--error-limit=0",
|
||||
"--relocatable",
|
||||
"--emit-relocs",
|
||||
"--no-relax",
|
||||
"--gc-sections",
|
||||
"--library-path",
|
||||
dir.path().to_str().expect("should be utf8"),
|
||||
"--library",
|
||||
BUILTINS_LIB_NAME,
|
||||
linker_script_path.to_str().expect("should be utf8"),
|
||||
object_path.to_str().expect("should be utf8"),
|
||||
"-o",
|
||||
output_path.to_str().expect("should be utf8"),
|
||||
];
|
||||
|
||||
if invoke_lld(&ld_args) {
|
||||
return Err(anyhow::anyhow!("ld.lld failed"));
|
||||
}
|
||||
|
||||
if env::var("PVM_LINKER_DUMP_SO").is_ok() {
|
||||
fs::copy(&output_path, "/tmp/out.so")?;
|
||||
};
|
||||
|
||||
let blob = fs::read(&output_path)?;
|
||||
polkavm_linker(blob)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "lld-sys"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
build = "build.rs"
|
||||
description = "bindings for ld.lld core"
|
||||
|
||||
[dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
cc = { workspace = true }
|
||||
@@ -0,0 +1,48 @@
|
||||
fn llvm_config(arg: &str) -> String {
|
||||
let output = std::process::Command::new("llvm-config")
|
||||
.args([arg])
|
||||
.output()
|
||||
.unwrap_or_else(|_| panic!("`llvm-config {arg}` failed"));
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.unwrap_or_else(|_| panic!("output of `llvm-config {arg}` should be utf8"))
|
||||
}
|
||||
|
||||
fn set_rustc_link_flags() {
|
||||
println!("cargo:rustc-link-search=native={}", llvm_config("--libdir"));
|
||||
|
||||
for lib in [
|
||||
"lldELF",
|
||||
"lldCommon",
|
||||
"lldMachO",
|
||||
"LLVMSupport",
|
||||
"LLVMLinker",
|
||||
"LLVMCore",
|
||||
"LLVMLTO",
|
||||
"LLVMTargetParser",
|
||||
"LLVMBinaryFormat",
|
||||
"LLVMDemangle",
|
||||
] {
|
||||
println!("cargo:rustc-link-lib=static={lib}");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
println!("cargo:rustc-link-lib=dylib=stdc++");
|
||||
println!("cargo:rustc-link-lib=tinfo");
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
llvm_config("--cxxflags")
|
||||
.split_whitespace()
|
||||
.fold(&mut cc::Build::new(), |builder, flag| builder.flag(flag))
|
||||
.flag("-Wno-unused-parameter")
|
||||
.cpp(true)
|
||||
.file("src/linker.cpp")
|
||||
.compile("liblinker.a");
|
||||
|
||||
set_rustc_link_flags();
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
extern "C" {
|
||||
pub fn LLDELFLink(args: *const *const libc::c_char, size: libc::size_t) -> libc::c_int;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#include "lld/Common/Driver.h"
|
||||
#include "lld/Common/CommonLinkerContext.h"
|
||||
#include "llvm/Support/CrashRecoveryContext.h"
|
||||
|
||||
LLD_HAS_DRIVER(elf);
|
||||
|
||||
extern "C" bool LLDELFLink(const char *argv[], size_t length)
|
||||
{
|
||||
bool canRunAgain;
|
||||
|
||||
{
|
||||
llvm::ArrayRef<const char *> args(argv, length);
|
||||
llvm::CrashRecoveryContext crc;
|
||||
if (!crc.RunSafely([&]()
|
||||
{ canRunAgain = lld::elf::link(args, llvm::outs(), llvm::errs(), false, false); }))
|
||||
return false;
|
||||
}
|
||||
|
||||
llvm::CrashRecoveryContext crc;
|
||||
return canRunAgain && crc.RunSafely([&]()
|
||||
{ lld::CommonLinkerContext::destroy(); });
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
[package]
|
||||
name = "revive-llvm-context"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
authors = [
|
||||
"Oleksandr Zarudnyi <a.zarudnyy@matterlabs.dev>",
|
||||
"Cyrill Leutwiler <cyrill@parity.io>",
|
||||
]
|
||||
description = "Shared front end code of the revive PolkaVM compilers"
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[features]
|
||||
riscv-zbb = []
|
||||
riscv-64 = []
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
semver = { workspace = true }
|
||||
itertools = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
regex = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
num = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
sha3 = { workspace = true }
|
||||
md5 = { workspace = true }
|
||||
inkwell = { workspace = true }
|
||||
polkavm-disassembler = { workspace = true }
|
||||
polkavm-common = { workspace = true }
|
||||
|
||||
revive-common = { workspace = true }
|
||||
pallet-contracts-pvm-llapi = { workspace = true }
|
||||
revive-linker = { workspace = true }
|
||||
revive-builtins = { workspace = true }
|
||||
revive-stdlib = { workspace = true }
|
||||
@@ -0,0 +1,36 @@
|
||||
//! The debug IR type.
|
||||
|
||||
/// The debug IR type.
|
||||
#[allow(non_camel_case_types)]
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum IRType {
|
||||
/// Whether to dump the Yul code.
|
||||
Yul,
|
||||
/// Whether to dump the EVM legacy assembly code.
|
||||
EVMLA,
|
||||
/// Whether to dump the Ethereal IR code.
|
||||
EthIR,
|
||||
/// Whether to dump the LLVM IR code.
|
||||
LLVM,
|
||||
/// Whether to dump the assembly code.
|
||||
Assembly,
|
||||
/// Whether to jump JSON
|
||||
#[cfg(debug_assertions)]
|
||||
JSON,
|
||||
}
|
||||
|
||||
impl IRType {
|
||||
/// Returns the file extension for the specified IR.
|
||||
pub fn file_extension(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Yul => revive_common::EXTENSION_YUL,
|
||||
Self::EthIR => revive_common::EXTENSION_ETHIR,
|
||||
Self::EVMLA => revive_common::EXTENSION_EVMLA,
|
||||
Self::LLVM => revive_common::EXTENSION_LLVM_SOURCE,
|
||||
Self::Assembly => revive_common::EXTENSION_POLKAVM_ASSEMBLY,
|
||||
#[cfg(debug_assertions)]
|
||||
Self::JSON => revive_common::EXTENSION_JSON,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The debug configuration.
|
||||
|
||||
pub mod ir_type;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use self::ir_type::IRType;
|
||||
|
||||
/// The debug configuration.
|
||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||
pub struct DebugConfig {
|
||||
/// The directory to dump the IRs to.
|
||||
pub output_directory: PathBuf,
|
||||
}
|
||||
|
||||
impl DebugConfig {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(output_directory: PathBuf) -> Self {
|
||||
Self { output_directory }
|
||||
}
|
||||
|
||||
/// Dumps the Yul IR.
|
||||
pub fn dump_yul(&self, contract_path: &str, code: &str) -> anyhow::Result<()> {
|
||||
let mut file_path = self.output_directory.to_owned();
|
||||
let full_file_name = Self::full_file_name(contract_path, None, IRType::Yul);
|
||||
file_path.push(full_file_name);
|
||||
std::fs::write(file_path, code)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dumps the EVM legacy assembly IR.
|
||||
pub fn dump_evmla(&self, contract_path: &str, code: &str) -> anyhow::Result<()> {
|
||||
let mut file_path = self.output_directory.to_owned();
|
||||
let full_file_name = Self::full_file_name(contract_path, None, IRType::EVMLA);
|
||||
file_path.push(full_file_name);
|
||||
std::fs::write(file_path, code)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dumps the Ethereal IR.
|
||||
pub fn dump_ethir(&self, contract_path: &str, code: &str) -> anyhow::Result<()> {
|
||||
let mut file_path = self.output_directory.to_owned();
|
||||
let full_file_name = Self::full_file_name(contract_path, None, IRType::EthIR);
|
||||
file_path.push(full_file_name);
|
||||
std::fs::write(file_path, code)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dumps the unoptimized LLVM IR.
|
||||
pub fn dump_llvm_ir_unoptimized(
|
||||
&self,
|
||||
contract_path: &str,
|
||||
module: &inkwell::module::Module,
|
||||
) -> anyhow::Result<()> {
|
||||
let llvm_code = module.print_to_string().to_string();
|
||||
|
||||
let mut file_path = self.output_directory.to_owned();
|
||||
let full_file_name = Self::full_file_name(contract_path, Some("unoptimized"), IRType::LLVM);
|
||||
file_path.push(full_file_name);
|
||||
std::fs::write(file_path, llvm_code)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dumps the optimized LLVM IR.
|
||||
pub fn dump_llvm_ir_optimized(
|
||||
&self,
|
||||
contract_path: &str,
|
||||
module: &inkwell::module::Module,
|
||||
) -> anyhow::Result<()> {
|
||||
let llvm_code = module.print_to_string().to_string();
|
||||
|
||||
let mut file_path = self.output_directory.to_owned();
|
||||
let full_file_name = Self::full_file_name(contract_path, Some("optimized"), IRType::LLVM);
|
||||
file_path.push(full_file_name);
|
||||
std::fs::write(file_path, llvm_code)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dumps the assembly.
|
||||
pub fn dump_assembly(&self, contract_path: &str, code: &str) -> anyhow::Result<()> {
|
||||
let mut file_path = self.output_directory.to_owned();
|
||||
let full_file_name = Self::full_file_name(contract_path, None, IRType::Assembly);
|
||||
file_path.push(full_file_name);
|
||||
std::fs::write(file_path, code)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dumps the stage output as a json file suitable for use with --recursive-process
|
||||
#[cfg(debug_assertions)]
|
||||
pub fn dump_stage_output(
|
||||
&self,
|
||||
contract_path: &str,
|
||||
contract_suffix: Option<&str>,
|
||||
stage_json: &Vec<u8>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut file_path = self.output_directory.to_owned();
|
||||
let full_file_name = Self::full_file_name(contract_path, contract_suffix, IRType::JSON);
|
||||
file_path.push(full_file_name);
|
||||
std::fs::write(file_path, stage_json)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates a full file name, given the contract full path, suffix, and extension.
|
||||
fn full_file_name(contract_path: &str, suffix: Option<&str>, ir_type: IRType) -> String {
|
||||
let mut full_file_name = contract_path.replace('/', "_").replace(':', ".");
|
||||
if let Some(suffix) = suffix {
|
||||
full_file_name.push('.');
|
||||
full_file_name.push_str(suffix);
|
||||
}
|
||||
full_file_name.push('.');
|
||||
full_file_name.push_str(ir_type.file_extension());
|
||||
full_file_name
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! The LLVM context library.
|
||||
|
||||
pub(crate) mod debug_config;
|
||||
pub(crate) mod optimizer;
|
||||
pub(crate) mod polkavm;
|
||||
pub(crate) mod target_machine;
|
||||
|
||||
pub use self::debug_config::ir_type::IRType as DebugConfigIR;
|
||||
pub use self::debug_config::DebugConfig;
|
||||
pub use self::optimizer::settings::size_level::SizeLevel as OptimizerSettingsSizeLevel;
|
||||
pub use self::optimizer::settings::Settings as OptimizerSettings;
|
||||
pub use self::optimizer::Optimizer;
|
||||
pub use self::polkavm::build_assembly_text as polkavm_build_assembly_text;
|
||||
pub use self::polkavm::context::address_space::AddressSpace as PolkaVMAddressSpace;
|
||||
pub use self::polkavm::context::argument::Argument as PolkaVMArgument;
|
||||
pub use self::polkavm::context::attribute::Attribute as PolkaVMAttribute;
|
||||
pub use self::polkavm::context::build::Build as PolkaVMBuild;
|
||||
pub use self::polkavm::context::code_type::CodeType as PolkaVMCodeType;
|
||||
pub use self::polkavm::context::evmla_data::EVMLAData as PolkaVMContextEVMLAData;
|
||||
pub use self::polkavm::context::function::block::evmla_data::key::Key as PolkaVMFunctionBlockKey;
|
||||
pub use self::polkavm::context::function::block::evmla_data::EVMLAData as PolkaVMFunctionBlockEVMLAData;
|
||||
pub use self::polkavm::context::function::block::Block as PolkaVMFunctionBlock;
|
||||
pub use self::polkavm::context::function::declaration::Declaration as PolkaVMFunctionDeclaration;
|
||||
pub use self::polkavm::context::function::evmla_data::EVMLAData as PolkaVMFunctionEVMLAData;
|
||||
pub use self::polkavm::context::function::intrinsics::Intrinsics as PolkaVMIntrinsicFunction;
|
||||
pub use self::polkavm::context::function::llvm_runtime::LLVMRuntime as PolkaVMLLVMRuntime;
|
||||
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::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_RUNTIME_CODE as PolkaVMFunctionRuntimeCode;
|
||||
pub use self::polkavm::context::function::yul_data::YulData as PolkaVMFunctionYulData;
|
||||
pub use self::polkavm::context::function::Function as PolkaVMFunction;
|
||||
pub use self::polkavm::context::global::Global as PolkaVMGlobal;
|
||||
pub use self::polkavm::context::pointer::Pointer as PolkaVMPointer;
|
||||
pub use self::polkavm::context::r#loop::Loop as PolkaVMLoop;
|
||||
pub use self::polkavm::context::solidity_data::SolidityData as PolkaVMContextSolidityData;
|
||||
pub use self::polkavm::context::yul_data::YulData as PolkaVMContextYulData;
|
||||
pub use self::polkavm::context::Context as PolkaVMContext;
|
||||
pub use self::polkavm::evm::arithmetic as polkavm_evm_arithmetic;
|
||||
pub use self::polkavm::evm::bitwise as polkavm_evm_bitwise;
|
||||
pub use self::polkavm::evm::call as polkavm_evm_call;
|
||||
pub use self::polkavm::evm::calldata as polkavm_evm_calldata;
|
||||
pub use self::polkavm::evm::comparison as polkavm_evm_comparison;
|
||||
pub use self::polkavm::evm::context as polkavm_evm_contract_context;
|
||||
pub use self::polkavm::evm::create as polkavm_evm_create;
|
||||
pub use self::polkavm::evm::crypto as polkavm_evm_crypto;
|
||||
pub use self::polkavm::evm::ether_gas as polkavm_evm_ether_gas;
|
||||
pub use self::polkavm::evm::event as polkavm_evm_event;
|
||||
pub use self::polkavm::evm::ext_code as polkavm_evm_ext_code;
|
||||
pub use self::polkavm::evm::immutable as polkavm_evm_immutable;
|
||||
pub use self::polkavm::evm::math as polkavm_evm_math;
|
||||
pub use self::polkavm::evm::memory as polkavm_evm_memory;
|
||||
pub use self::polkavm::evm::r#return as polkavm_evm_return;
|
||||
pub use self::polkavm::evm::return_data as polkavm_evm_return_data;
|
||||
pub use self::polkavm::evm::storage as polkavm_evm_storage;
|
||||
pub use self::polkavm::metadata_hash::MetadataHash as PolkaVMMetadataHash;
|
||||
pub use self::polkavm::r#const as polkavm_const;
|
||||
pub use self::polkavm::utils as polkavm_utils;
|
||||
pub use self::polkavm::Dependency as PolkaVMDependency;
|
||||
pub use self::polkavm::DummyDependency as PolkaVMDummyDependency;
|
||||
pub use self::polkavm::DummyLLVMWritable as PolkaVMDummyLLVMWritable;
|
||||
pub use self::polkavm::WriteLLVM as PolkaVMWriteLLVM;
|
||||
pub use self::target_machine::target::Target;
|
||||
pub use self::target_machine::TargetMachine;
|
||||
|
||||
/// Initializes the target machine.
|
||||
pub fn initialize_target(target: Target) {
|
||||
match target {
|
||||
Target::PVM => self::polkavm::initialize_target(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! The LLVM optimizing tools.
|
||||
|
||||
pub mod settings;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::target_machine::TargetMachine;
|
||||
|
||||
use self::settings::Settings;
|
||||
|
||||
/// The LLVM optimizing tools.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Optimizer {
|
||||
/// The optimizer settings.
|
||||
settings: Settings,
|
||||
}
|
||||
|
||||
impl Optimizer {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(settings: Settings) -> Self {
|
||||
Self { settings }
|
||||
}
|
||||
|
||||
/// Runs the new pass manager.
|
||||
pub fn run(
|
||||
&self,
|
||||
target_machine: &TargetMachine,
|
||||
module: &inkwell::module::Module,
|
||||
) -> Result<(), inkwell::support::LLVMString> {
|
||||
target_machine.run_optimization_passes(
|
||||
module,
|
||||
format!("default<O{}>", self.settings.middle_end_as_string()).as_str(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the optimizer settings reference.
|
||||
pub fn settings(&self) -> &Settings {
|
||||
&self.settings
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The LLVM optimizer settings.
|
||||
|
||||
pub mod size_level;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use itertools::Itertools;
|
||||
|
||||
use self::size_level::SizeLevel;
|
||||
|
||||
/// The LLVM optimizer settings.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Eq)]
|
||||
pub struct Settings {
|
||||
/// The middle-end optimization level.
|
||||
pub level_middle_end: inkwell::OptimizationLevel,
|
||||
/// The middle-end size optimization level.
|
||||
pub level_middle_end_size: SizeLevel,
|
||||
/// The back-end optimization level.
|
||||
pub level_back_end: inkwell::OptimizationLevel,
|
||||
|
||||
/// Fallback to optimizing for size if the bytecode is too large.
|
||||
pub is_fallback_to_size_enabled: bool,
|
||||
/// Whether the system request memoization is disabled.
|
||||
pub is_system_request_memoization_disabled: bool,
|
||||
|
||||
/// Whether the LLVM `verify each` option is enabled.
|
||||
pub is_verify_each_enabled: bool,
|
||||
/// Whether the LLVM `debug logging` option is enabled.
|
||||
pub is_debug_logging_enabled: bool,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(
|
||||
level_middle_end: inkwell::OptimizationLevel,
|
||||
level_middle_end_size: SizeLevel,
|
||||
level_back_end: inkwell::OptimizationLevel,
|
||||
) -> Self {
|
||||
Self {
|
||||
level_middle_end,
|
||||
level_middle_end_size,
|
||||
level_back_end,
|
||||
|
||||
is_fallback_to_size_enabled: false,
|
||||
is_system_request_memoization_disabled: false,
|
||||
|
||||
is_verify_each_enabled: false,
|
||||
is_debug_logging_enabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A shortcut constructor with debugging tools.
|
||||
pub fn new_debug(
|
||||
level_middle_end: inkwell::OptimizationLevel,
|
||||
level_middle_end_size: SizeLevel,
|
||||
level_back_end: inkwell::OptimizationLevel,
|
||||
|
||||
is_verify_each_enabled: bool,
|
||||
is_debug_logging_enabled: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
level_middle_end,
|
||||
level_middle_end_size,
|
||||
level_back_end,
|
||||
|
||||
is_fallback_to_size_enabled: false,
|
||||
is_system_request_memoization_disabled: false,
|
||||
|
||||
is_verify_each_enabled,
|
||||
is_debug_logging_enabled,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates settings from a CLI optimization parameter.
|
||||
pub fn try_from_cli(value: char) -> anyhow::Result<Self> {
|
||||
Ok(match value {
|
||||
'0' => Self::new(
|
||||
// The middle-end optimization level.
|
||||
inkwell::OptimizationLevel::None,
|
||||
// The middle-end size optimization level.
|
||||
SizeLevel::Zero,
|
||||
// The back-end optimization level.
|
||||
inkwell::OptimizationLevel::None,
|
||||
),
|
||||
'1' => Self::new(
|
||||
inkwell::OptimizationLevel::Less,
|
||||
SizeLevel::Zero,
|
||||
// The back-end does not currently distinguish between O1, O2, and O3.
|
||||
inkwell::OptimizationLevel::Less,
|
||||
),
|
||||
'2' => Self::new(
|
||||
inkwell::OptimizationLevel::Default,
|
||||
SizeLevel::Zero,
|
||||
// The back-end does not currently distinguish between O1, O2, and O3.
|
||||
inkwell::OptimizationLevel::Default,
|
||||
),
|
||||
'3' => Self::new(
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
SizeLevel::Zero,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
),
|
||||
's' => Self::new(
|
||||
// The middle-end optimization level is ignored when SizeLevel is set.
|
||||
inkwell::OptimizationLevel::Default,
|
||||
SizeLevel::S,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
),
|
||||
'z' => Self::new(
|
||||
// The middle-end optimization level is ignored when SizeLevel is set.
|
||||
inkwell::OptimizationLevel::Default,
|
||||
SizeLevel::Z,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
),
|
||||
char => anyhow::bail!("Unexpected optimization option '{}'", char),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the settings without optimizations.
|
||||
pub fn none() -> Self {
|
||||
Self::new(
|
||||
inkwell::OptimizationLevel::None,
|
||||
SizeLevel::Zero,
|
||||
inkwell::OptimizationLevel::None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the settings for the optimal number of VM execution cycles.
|
||||
pub fn cycles() -> Self {
|
||||
Self::new(
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
SizeLevel::Zero,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the settings for the optimal size.
|
||||
pub fn size() -> Self {
|
||||
Self::new(
|
||||
inkwell::OptimizationLevel::Default,
|
||||
SizeLevel::Z,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the middle-end optimization parameter as string.
|
||||
pub fn middle_end_as_string(&self) -> String {
|
||||
match self.level_middle_end_size {
|
||||
SizeLevel::Zero => (self.level_middle_end as u8).to_string(),
|
||||
size_level => size_level.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether there are middle-end optimizations enabled.
|
||||
pub fn is_middle_end_enabled(&self) -> bool {
|
||||
self.level_middle_end != inkwell::OptimizationLevel::None
|
||||
|| self.level_middle_end_size != SizeLevel::Zero
|
||||
}
|
||||
|
||||
/// Returns all possible combinations of the optimizer settings.
|
||||
/// Used only for testing purposes.
|
||||
pub fn combinations() -> Vec<Self> {
|
||||
let performance_combinations: Vec<Self> = vec![
|
||||
inkwell::OptimizationLevel::None,
|
||||
inkwell::OptimizationLevel::Less,
|
||||
inkwell::OptimizationLevel::Default,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
]
|
||||
.into_iter()
|
||||
.cartesian_product(vec![
|
||||
inkwell::OptimizationLevel::None,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
])
|
||||
.map(|(optimization_level_middle, optimization_level_back)| {
|
||||
Self::new(
|
||||
optimization_level_middle,
|
||||
SizeLevel::Zero,
|
||||
optimization_level_back,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let size_combinations: Vec<Self> = vec![SizeLevel::S, SizeLevel::Z]
|
||||
.into_iter()
|
||||
.cartesian_product(vec![
|
||||
inkwell::OptimizationLevel::None,
|
||||
inkwell::OptimizationLevel::Aggressive,
|
||||
])
|
||||
.map(|(size_level, optimization_level_back)| {
|
||||
Self::new(
|
||||
inkwell::OptimizationLevel::Default,
|
||||
size_level,
|
||||
optimization_level_back,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut combinations = performance_combinations;
|
||||
combinations.extend(size_combinations);
|
||||
|
||||
combinations
|
||||
}
|
||||
|
||||
/// Sets the fallback to optimizing for size if the bytecode is too large.
|
||||
pub fn enable_fallback_to_size(&mut self) {
|
||||
self.is_fallback_to_size_enabled = true;
|
||||
}
|
||||
|
||||
/// Disables the system request memoization.
|
||||
pub fn disable_system_request_memoization(&mut self) {
|
||||
self.is_system_request_memoization_disabled = true;
|
||||
}
|
||||
|
||||
/// Whether the fallback to optimizing for size is enabled.
|
||||
pub fn is_fallback_to_size_enabled(&self) -> bool {
|
||||
self.is_fallback_to_size_enabled
|
||||
}
|
||||
|
||||
/// Whether the system request memoization is disabled.
|
||||
pub fn is_system_request_memoization_disabled(&self) -> bool {
|
||||
self.is_system_request_memoization_disabled
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Settings {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.level_middle_end == other.level_middle_end
|
||||
&& self.level_middle_end_size == other.level_middle_end_size
|
||||
&& self.level_back_end == other.level_back_end
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Settings {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"M{}B{}",
|
||||
self.middle_end_as_string(),
|
||||
self.level_back_end as u8,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! The LLVM optimizer settings size level.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The LLVM optimizer settings size level.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SizeLevel {
|
||||
/// No size optimizations.
|
||||
Zero,
|
||||
/// The default size optimizations.
|
||||
S,
|
||||
/// The aggresize size optimizations.
|
||||
Z,
|
||||
}
|
||||
|
||||
impl From<SizeLevel> for u32 {
|
||||
fn from(level: SizeLevel) -> Self {
|
||||
match level {
|
||||
SizeLevel::Zero => 0,
|
||||
SizeLevel::S => 1,
|
||||
SizeLevel::Z => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for SizeLevel {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
SizeLevel::Zero => write!(f, "0"),
|
||||
SizeLevel::S => write!(f, "s"),
|
||||
SizeLevel::Z => write!(f, "z"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The LLVM context constants.
|
||||
|
||||
/// Runtime API methods.
|
||||
pub mod runtime_api;
|
||||
|
||||
/// The LLVM framework version.
|
||||
pub const LLVM_VERSION: semver::Version = semver::Version::new(18, 1, 4);
|
||||
|
||||
/// The PolkaVM version.
|
||||
pub const ZKEVM_VERSION: semver::Version = semver::Version::new(1, 3, 2);
|
||||
|
||||
/// The register width sized type
|
||||
pub static XLEN: usize = revive_common::BIT_LENGTH_X32;
|
||||
|
||||
/// The heap memory pointer pointer global variable name.
|
||||
pub static GLOBAL_HEAP_MEMORY_POINTER: &str = "memory_pointer";
|
||||
|
||||
/// The calldata pointer global variable name.
|
||||
pub static GLOBAL_CALLDATA_POINTER: &str = "ptr_calldata";
|
||||
|
||||
/// The calldata size global variable name.
|
||||
pub static GLOBAL_CALLDATA_SIZE: &str = "calldatasize";
|
||||
|
||||
/// The return data pointer global variable name.
|
||||
pub static GLOBAL_RETURN_DATA_POINTER: &str = "ptr_return_data";
|
||||
|
||||
/// The return data size pointer global variable name.
|
||||
pub static GLOBAL_RETURN_DATA_SIZE: &str = "returndatasize";
|
||||
|
||||
/// The call flags global variable name.
|
||||
pub static GLOBAL_CALL_FLAGS: &str = "call_flags";
|
||||
|
||||
/// The extra ABI data global variable name.
|
||||
pub static GLOBAL_EXTRA_ABI_DATA: &str = "extra_abi_data";
|
||||
|
||||
/// The constant array global variable name prefix.
|
||||
pub static GLOBAL_CONST_ARRAY_PREFIX: &str = "const_array_";
|
||||
|
||||
/// The global verbatim getter identifier prefix.
|
||||
pub static GLOBAL_VERBATIM_GETTER_PREFIX: &str = "get_global::";
|
||||
|
||||
/// The static word size.
|
||||
pub static GLOBAL_I256_SIZE: &str = "i256_size";
|
||||
|
||||
/// The static value size.
|
||||
pub static GLOBAL_I160_SIZE: &str = "i160_size";
|
||||
|
||||
/// The static i64 size.
|
||||
pub static GLOBAL_I64_SIZE: &str = "i64_size";
|
||||
|
||||
/// The external call data offset in the auxiliary heap.
|
||||
pub const HEAP_AUX_OFFSET_EXTERNAL_CALL: u64 = 0;
|
||||
|
||||
/// The constructor return data offset in the auxiliary heap.
|
||||
pub const HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA: u64 =
|
||||
8 * (revive_common::BYTE_LENGTH_WORD as u64);
|
||||
|
||||
/// The number of the extra ABI data arguments.
|
||||
pub const EXTRA_ABI_DATA_SIZE: usize = 0;
|
||||
|
||||
/// The `create` method deployer signature.
|
||||
pub static DEPLOYER_SIGNATURE_CREATE: &str = "create(bytes32,bytes32,bytes)";
|
||||
|
||||
/// The `create2` method deployer signature.
|
||||
pub static DEPLOYER_SIGNATURE_CREATE2: &str = "create2(bytes32,bytes32,bytes)";
|
||||
|
||||
/// The absence of system call bit.
|
||||
pub const NO_SYSTEM_CALL_BIT: bool = false;
|
||||
|
||||
/// The system call bit.
|
||||
pub const SYSTEM_CALL_BIT: bool = true;
|
||||
|
||||
/// The deployer call header size that consists of:
|
||||
/// - bytecode hash (32 bytes)
|
||||
pub const DEPLOYER_CALL_HEADER_SIZE: usize = revive_common::BYTE_LENGTH_WORD;
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Runtime API import and export symbols.
|
||||
|
||||
pub mod exports {
|
||||
/// The contract deploy export.
|
||||
pub static CALL: &str = "call";
|
||||
|
||||
/// The contract call export.
|
||||
pub static DEPLOY: &str = "deploy";
|
||||
|
||||
/// All exported symbols.
|
||||
/// Useful for configuring common attributes and linkage.
|
||||
pub static EXPORTS: [&str; 2] = [CALL, DEPLOY];
|
||||
}
|
||||
|
||||
pub mod imports {
|
||||
pub static ADDRESS: &str = "address";
|
||||
|
||||
pub static BALANCE: &str = "balance";
|
||||
|
||||
pub static BLOCK_NUMBER: &str = "block_number";
|
||||
|
||||
pub static CALL: &str = "seal_call";
|
||||
|
||||
pub static CALLER: &str = "caller";
|
||||
|
||||
pub static CODE_SIZE: &str = "code_size";
|
||||
|
||||
pub static DEPOSIT_EVENT: &str = "deposit_event";
|
||||
|
||||
pub static GET_STORAGE: &str = "get_storage";
|
||||
|
||||
pub static HASH_KECCAK_256: &str = "hash_keccak_256";
|
||||
|
||||
pub static INPUT: &str = "input";
|
||||
|
||||
pub static INSTANTIATE: &str = "instantiate";
|
||||
|
||||
pub static NOW: &str = "now";
|
||||
|
||||
pub static RETURN: &str = "seal_return";
|
||||
|
||||
pub static RETURNDATACOPY: &str = "returndatacopy";
|
||||
|
||||
pub static SET_STORAGE: &str = "set_storage";
|
||||
|
||||
pub static VALUE_TRANSFERRED: &str = "value_transferred";
|
||||
|
||||
/// All imported runtime API symbols.
|
||||
/// Useful for configuring common attributes and linkage.
|
||||
pub static IMPORTS: [&str; 16] = [
|
||||
ADDRESS,
|
||||
BALANCE,
|
||||
BLOCK_NUMBER,
|
||||
CALL,
|
||||
CALLER,
|
||||
CODE_SIZE,
|
||||
DEPOSIT_EVENT,
|
||||
GET_STORAGE,
|
||||
HASH_KECCAK_256,
|
||||
INPUT,
|
||||
INSTANTIATE,
|
||||
NOW,
|
||||
RETURN,
|
||||
RETURNDATACOPY,
|
||||
SET_STORAGE,
|
||||
VALUE_TRANSFERRED,
|
||||
];
|
||||
}
|
||||
|
||||
/// PolkaVM __sbrk API symbol to extend the heap memory.
|
||||
pub static SBRK: &str = "__sbrk";
|
||||
@@ -0,0 +1,26 @@
|
||||
//! The address space aliases.
|
||||
|
||||
/// The address space aliases.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum AddressSpace {
|
||||
/// The stack memory.
|
||||
#[default]
|
||||
Stack,
|
||||
/// The heap memory.
|
||||
Heap,
|
||||
/// The generic memory page.
|
||||
Storage,
|
||||
/// The transient storage.
|
||||
TransientStorage,
|
||||
}
|
||||
|
||||
impl From<AddressSpace> for inkwell::AddressSpace {
|
||||
fn from(value: AddressSpace) -> Self {
|
||||
match value {
|
||||
AddressSpace::Stack => Self::from(0),
|
||||
AddressSpace::Heap => Self::from(1),
|
||||
AddressSpace::Storage => Self::from(5),
|
||||
AddressSpace::TransientStorage => Self::from(6),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The LLVM argument with metadata.
|
||||
|
||||
/// The LLVM argument with metadata.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Argument<'ctx> {
|
||||
/// The actual LLVM operand.
|
||||
pub value: inkwell::values::BasicValueEnum<'ctx>,
|
||||
/// The original AST value. Used mostly for string literals.
|
||||
pub original: Option<String>,
|
||||
/// The preserved constant value, if available.
|
||||
pub constant: Option<num::BigUint>,
|
||||
}
|
||||
|
||||
impl<'ctx> Argument<'ctx> {
|
||||
/// The calldata offset argument index.
|
||||
pub const ARGUMENT_INDEX_CALLDATA_OFFSET: usize = 0;
|
||||
|
||||
/// The calldata length argument index.
|
||||
pub const ARGUMENT_INDEX_CALLDATA_LENGTH: usize = 1;
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new(value: inkwell::values::BasicValueEnum<'ctx>) -> Self {
|
||||
Self {
|
||||
value,
|
||||
original: None,
|
||||
constant: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new_with_original(
|
||||
value: inkwell::values::BasicValueEnum<'ctx>,
|
||||
original: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
value,
|
||||
original: Some(original),
|
||||
constant: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new_with_constant(
|
||||
value: inkwell::values::BasicValueEnum<'ctx>,
|
||||
constant: num::BigUint,
|
||||
) -> Self {
|
||||
Self {
|
||||
value,
|
||||
original: None,
|
||||
constant: Some(constant),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the inner LLVM value.
|
||||
pub fn to_llvm(&self) -> inkwell::values::BasicValueEnum<'ctx> {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> From<inkwell::values::BasicValueEnum<'ctx>> for Argument<'ctx> {
|
||||
fn from(value: inkwell::values::BasicValueEnum<'ctx>) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The LLVM attribute.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The LLVM attribute.
|
||||
/// In order to check the real order in a new major version of LLVM, find the `Attributes.inc` file
|
||||
/// inside of the LLVM build directory. This order is actually generated during the building.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Attribute {
|
||||
Unused = 0,
|
||||
AllocAlign = 1,
|
||||
AllocatedPointer = 2,
|
||||
AlwaysInline = 3,
|
||||
Builtin = 4,
|
||||
Cold = 5,
|
||||
Convergent = 6,
|
||||
CoroDestroyOnlyWhenComplete = 7,
|
||||
DeadOnUnwind = 8,
|
||||
DisableSanitizerInstrumentation = 9,
|
||||
FnRetThunkExtern = 10,
|
||||
Hot = 11,
|
||||
ImmArg = 12,
|
||||
InReg = 13,
|
||||
InlineHint = 14,
|
||||
JumpTable = 15,
|
||||
MinSize = 16,
|
||||
MustProgress = 17,
|
||||
Naked = 18,
|
||||
Nest = 19,
|
||||
NoAlias = 20,
|
||||
NoBuiltin = 21,
|
||||
NoCallback = 22,
|
||||
NoCapture = 23,
|
||||
NoCfCheck = 24,
|
||||
NoDuplicate = 25,
|
||||
NoFree = 26,
|
||||
NoImplicitFloat = 27,
|
||||
NoInline = 28,
|
||||
NoMerge = 29,
|
||||
NoProfile = 30,
|
||||
NoRecurse = 31,
|
||||
NoRedZone = 32,
|
||||
NoReturn = 33,
|
||||
NoSanitizeBounds = 34,
|
||||
NoSanitizeCoverage = 35,
|
||||
NoSync = 36,
|
||||
NoUndef = 37,
|
||||
NoUnwind = 38,
|
||||
NonLazyBind = 39,
|
||||
NonNull = 40,
|
||||
NullPointerIsValid = 41,
|
||||
OptForFuzzing = 42,
|
||||
OptimizeForDebugging = 43,
|
||||
OptimizeForSize = 44,
|
||||
OptimizeNone = 45,
|
||||
PresplitCoroutine = 46,
|
||||
ReadNone = 47,
|
||||
ReadOnly = 48,
|
||||
Returned = 49,
|
||||
ReturnsTwice = 50,
|
||||
SExt = 51,
|
||||
SafeStack = 52,
|
||||
SanitizeAddress = 53,
|
||||
SanitizeHWAddress = 54,
|
||||
SanitizeMemTag = 55,
|
||||
SanitizeMemory = 56,
|
||||
SanitizeThread = 57,
|
||||
ShadowCallStack = 58,
|
||||
SkipProfile = 59,
|
||||
Speculatable = 60,
|
||||
SpeculativeLoadHardening = 61,
|
||||
StackProtect = 62,
|
||||
StackProtectReq = 63,
|
||||
StackProtectStrong = 64,
|
||||
StrictFP = 65,
|
||||
SwiftAsync = 66,
|
||||
SwiftError = 67,
|
||||
SwiftSelf = 68,
|
||||
WillReturn = 69,
|
||||
Writable = 70,
|
||||
WriteOnly = 71,
|
||||
ZExt = 72,
|
||||
// LastEnumAttr = 72,
|
||||
// FirstTypeAttr = 73,
|
||||
ByRef = 73,
|
||||
ByVal = 74,
|
||||
ElementType = 75,
|
||||
InAlloca = 76,
|
||||
Preallocated = 77,
|
||||
StructRet = 78,
|
||||
// LastTypeAttr = 78,
|
||||
// FirstIntAttr = 79,
|
||||
Alignment = 79,
|
||||
AllocKind = 80,
|
||||
AllocSize = 81,
|
||||
Dereferenceable = 82,
|
||||
DereferenceableOrNull = 83,
|
||||
Memory = 84,
|
||||
NoFPClass = 85,
|
||||
StackAlignment = 86,
|
||||
UWTable = 87,
|
||||
VScaleRange = 88,
|
||||
// LastIntAttr = 88,
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for Attribute {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
"AlwaysInline" => Ok(Attribute::AlwaysInline),
|
||||
"Cold" => Ok(Attribute::Cold),
|
||||
"Hot" => Ok(Attribute::Hot),
|
||||
"MinSize" => Ok(Attribute::MinSize),
|
||||
"OptimizeForSize" => Ok(Attribute::OptimizeForSize),
|
||||
"NoInline" => Ok(Attribute::NoInline),
|
||||
"WillReturn" => Ok(Attribute::WillReturn),
|
||||
"NoReturn" => Ok(Attribute::NoReturn),
|
||||
"MustProgress" => Ok(Attribute::MustProgress),
|
||||
_ => Err(value.to_owned()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! The LLVM module build.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The LLVM module build.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Build {
|
||||
/// The PolkaVM text assembly.
|
||||
pub assembly_text: String,
|
||||
/// The metadata hash.
|
||||
pub metadata_hash: Option<[u8; revive_common::BYTE_LENGTH_WORD]>,
|
||||
/// The PolkaVM binary bytecode.
|
||||
pub bytecode: Vec<u8>,
|
||||
/// The PolkaVM bytecode hash.
|
||||
pub bytecode_hash: String,
|
||||
/// The hash-to-full-path mapping of the contract factory dependencies.
|
||||
pub factory_dependencies: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Build {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(
|
||||
assembly_text: String,
|
||||
metadata_hash: Option<[u8; revive_common::BYTE_LENGTH_WORD]>,
|
||||
bytecode: Vec<u8>,
|
||||
bytecode_hash: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
assembly_text,
|
||||
metadata_hash,
|
||||
bytecode,
|
||||
bytecode_hash,
|
||||
factory_dependencies: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! The contract code types.
|
||||
|
||||
/// The contract code types (deploy and runtime).
|
||||
/// They do not represent any entities in the final bytecode, but this separation is always present
|
||||
/// in the IRs used for translation to the EVM bytecode.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum CodeType {
|
||||
/// The deploy code.
|
||||
Deploy,
|
||||
/// The runtime code.
|
||||
Runtime,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CodeType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Deploy => write!(f, "deploy"),
|
||||
Self::Runtime => write!(f, "runtime"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! The LLVM debug information.
|
||||
|
||||
use inkwell::debug_info::AsDIScope;
|
||||
use num::Zero;
|
||||
|
||||
/// The LLVM debug information.
|
||||
pub struct DebugInfo<'ctx> {
|
||||
/// The compile unit.
|
||||
compile_unit: inkwell::debug_info::DICompileUnit<'ctx>,
|
||||
/// The debug info builder.
|
||||
builder: inkwell::debug_info::DebugInfoBuilder<'ctx>,
|
||||
}
|
||||
|
||||
impl<'ctx> DebugInfo<'ctx> {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(module: &inkwell::module::Module<'ctx>) -> Self {
|
||||
let (builder, compile_unit) = module.create_debug_info_builder(
|
||||
true,
|
||||
inkwell::debug_info::DWARFSourceLanguage::C,
|
||||
module.get_name().to_string_lossy().as_ref(),
|
||||
"",
|
||||
"",
|
||||
false,
|
||||
"",
|
||||
0,
|
||||
"",
|
||||
inkwell::debug_info::DWARFEmissionKind::Full,
|
||||
0,
|
||||
false,
|
||||
false,
|
||||
"",
|
||||
"",
|
||||
);
|
||||
|
||||
Self {
|
||||
compile_unit,
|
||||
builder,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a function info.
|
||||
pub fn create_function(
|
||||
&self,
|
||||
name: &str,
|
||||
) -> anyhow::Result<inkwell::debug_info::DISubprogram<'ctx>> {
|
||||
let subroutine_type = self.builder.create_subroutine_type(
|
||||
self.compile_unit.get_file(),
|
||||
Some(self.create_type(revive_common::BIT_LENGTH_FIELD)?),
|
||||
&[],
|
||||
inkwell::debug_info::DIFlags::zero(),
|
||||
);
|
||||
|
||||
let function = self.builder.create_function(
|
||||
self.compile_unit.get_file().as_debug_info_scope(),
|
||||
name,
|
||||
None,
|
||||
self.compile_unit.get_file(),
|
||||
42,
|
||||
subroutine_type,
|
||||
true,
|
||||
false,
|
||||
1,
|
||||
inkwell::debug_info::DIFlags::zero(),
|
||||
false,
|
||||
);
|
||||
|
||||
self.builder.create_lexical_block(
|
||||
function.as_debug_info_scope(),
|
||||
self.compile_unit.get_file(),
|
||||
1,
|
||||
1,
|
||||
);
|
||||
|
||||
Ok(function)
|
||||
}
|
||||
|
||||
/// Creates a primitive type info.
|
||||
pub fn create_type(
|
||||
&self,
|
||||
bit_length: usize,
|
||||
) -> anyhow::Result<inkwell::debug_info::DIType<'ctx>> {
|
||||
self.builder
|
||||
.create_basic_type(
|
||||
"U256",
|
||||
bit_length as u64,
|
||||
0,
|
||||
inkwell::debug_info::DIFlags::zero(),
|
||||
)
|
||||
.map(|basic_type| basic_type.as_type())
|
||||
.map_err(|error| anyhow::anyhow!("Debug info error: {}", error))
|
||||
}
|
||||
|
||||
/// Finalizes the builder.
|
||||
pub fn finalize(&self) {
|
||||
self.builder.finalize();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! The LLVM IR generator EVM legacy assembly data.
|
||||
|
||||
use crate::polkavm::context::argument::Argument;
|
||||
|
||||
/// The LLVM IR generator EVM legacy assembly data.
|
||||
/// Describes some data that is only relevant to the EVM legacy assembly.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EVMLAData<'ctx> {
|
||||
/// The Solidity compiler version.
|
||||
/// Some instruction behave differenly depending on the version.
|
||||
pub version: semver::Version,
|
||||
/// The static stack allocated for the current function.
|
||||
pub stack: Vec<Argument<'ctx>>,
|
||||
}
|
||||
|
||||
impl<'ctx> EVMLAData<'ctx> {
|
||||
/// The default stack size.
|
||||
pub const DEFAULT_STACK_SIZE: usize = 64;
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new(version: semver::Version) -> Self {
|
||||
Self {
|
||||
version,
|
||||
stack: Vec::with_capacity(Self::DEFAULT_STACK_SIZE),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The LLVM IR generator function block key.
|
||||
|
||||
use crate::polkavm::context::code_type::CodeType;
|
||||
|
||||
/// The LLVM IR generator function block key.
|
||||
/// Is only relevant to the EVM legacy assembly.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Key {
|
||||
/// The block code type.
|
||||
pub code_type: CodeType,
|
||||
/// The block tag.
|
||||
pub tag: num::BigUint,
|
||||
}
|
||||
|
||||
impl Key {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(code_type: CodeType, tag: num::BigUint) -> Self {
|
||||
Self { code_type, tag }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Key {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}_{}",
|
||||
match self.code_type {
|
||||
CodeType::Deploy => "dt",
|
||||
CodeType::Runtime => "rt",
|
||||
},
|
||||
self.tag
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! The LLVM function block EVM legacy assembly data.
|
||||
|
||||
pub mod key;
|
||||
|
||||
/// The LLVM function block EVM legacy assembly data.
|
||||
/// Describes some data that is only relevant to the EVM legacy assembly.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EVMLAData {
|
||||
/// The initial hashes of the allowed stack states.
|
||||
pub stack_hashes: Vec<md5::Digest>,
|
||||
}
|
||||
|
||||
impl EVMLAData {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(stack_hashes: Vec<md5::Digest>) -> Self {
|
||||
Self { stack_hashes }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The LLVM IR generator function block.
|
||||
|
||||
pub mod evmla_data;
|
||||
|
||||
use self::evmla_data::EVMLAData;
|
||||
|
||||
/// The LLVM IR generator function block.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Block<'ctx> {
|
||||
/// The inner block.
|
||||
inner: inkwell::basic_block::BasicBlock<'ctx>,
|
||||
/// The EVM legacy assembly compiler data.
|
||||
evmla_data: Option<EVMLAData>,
|
||||
}
|
||||
|
||||
impl<'ctx> Block<'ctx> {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(inner: inkwell::basic_block::BasicBlock<'ctx>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
evmla_data: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the EVM legacy assembly data.
|
||||
pub fn set_evmla_data(&mut self, data: EVMLAData) {
|
||||
self.evmla_data = Some(data);
|
||||
}
|
||||
|
||||
/// The LLVM object reference.
|
||||
pub fn inner(&self) -> inkwell::basic_block::BasicBlock<'ctx> {
|
||||
self.inner
|
||||
}
|
||||
|
||||
/// Returns the EVM data reference.
|
||||
/// # Panics
|
||||
/// If the EVM data has not been initialized.
|
||||
pub fn evm(&self) -> &EVMLAData {
|
||||
self.evmla_data
|
||||
.as_ref()
|
||||
.expect("The EVM data must have been initialized")
|
||||
}
|
||||
|
||||
/// Returns the EVM data mutable reference.
|
||||
/// # Panics
|
||||
/// If the EVM data has not been initialized.
|
||||
pub fn evm_mut(&mut self) -> &mut EVMLAData {
|
||||
self.evmla_data
|
||||
.as_mut()
|
||||
.expect("The EVM data must have been initialized")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! The LLVM function declaration.
|
||||
|
||||
/// The LLVM function declaration.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Declaration<'ctx> {
|
||||
/// The function type.
|
||||
pub r#type: inkwell::types::FunctionType<'ctx>,
|
||||
/// The function value.
|
||||
pub value: inkwell::values::FunctionValue<'ctx>,
|
||||
}
|
||||
|
||||
impl<'ctx> Declaration<'ctx> {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(
|
||||
r#type: inkwell::types::FunctionType<'ctx>,
|
||||
value: inkwell::values::FunctionValue<'ctx>,
|
||||
) -> Self {
|
||||
Self { r#type, value }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! The LLVM function EVM legacy assembly data.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::polkavm::context::function::block::evmla_data::key::Key as BlockKey;
|
||||
use crate::polkavm::context::function::block::Block;
|
||||
|
||||
/// The LLVM function EVM legacy assembly data.
|
||||
/// Describes some data that is only relevant to the EVM legacy assembly.
|
||||
#[derive(Debug)]
|
||||
pub struct EVMLAData<'ctx> {
|
||||
/// The ordinary blocks with numeric tags.
|
||||
/// Is only used by the Solidity EVM compiler.
|
||||
pub blocks: BTreeMap<BlockKey, Vec<Block<'ctx>>>,
|
||||
/// The function stack size.
|
||||
pub stack_size: usize,
|
||||
}
|
||||
|
||||
impl<'ctx> EVMLAData<'ctx> {
|
||||
/// A shortcut constructor.
|
||||
pub fn new(stack_size: usize) -> Self {
|
||||
Self {
|
||||
blocks: BTreeMap::new(),
|
||||
stack_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a function block.
|
||||
pub fn insert_block(&mut self, key: BlockKey, block: Block<'ctx>) {
|
||||
if let Some(blocks) = self.blocks.get_mut(&key) {
|
||||
blocks.push(block);
|
||||
} else {
|
||||
self.blocks.insert(key, vec![block]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the block with the specified tag and initial stack pattern.
|
||||
/// If there is only one block, it is returned unconditionally.
|
||||
pub fn find_block(
|
||||
&self,
|
||||
key: &BlockKey,
|
||||
stack_hash: &md5::Digest,
|
||||
) -> anyhow::Result<Block<'ctx>> {
|
||||
if self
|
||||
.blocks
|
||||
.get(key)
|
||||
.ok_or_else(|| anyhow::anyhow!("Undeclared function block {}", key))?
|
||||
.len()
|
||||
== 1
|
||||
{
|
||||
return self
|
||||
.blocks
|
||||
.get(key)
|
||||
.ok_or_else(|| anyhow::anyhow!("Undeclared function block {}", key))?
|
||||
.first()
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("Undeclared function block {}", key));
|
||||
}
|
||||
|
||||
self.blocks
|
||||
.get(key)
|
||||
.ok_or_else(|| anyhow::anyhow!("Undeclared function block {}", key))?
|
||||
.iter()
|
||||
.find(|block| {
|
||||
block
|
||||
.evm()
|
||||
.stack_hashes
|
||||
.iter()
|
||||
.any(|hash| hash == stack_hash)
|
||||
})
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("Undeclared function block {}", key))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! The LLVM intrinsic functions.
|
||||
|
||||
use inkwell::types::BasicType;
|
||||
|
||||
use crate::polkavm::context::function::declaration::Declaration as FunctionDeclaration;
|
||||
|
||||
/// The LLVM intrinsic functions, implemented in the LLVM back-end.
|
||||
/// Most of them are translated directly into bytecode instructions.
|
||||
#[derive(Debug)]
|
||||
pub struct Intrinsics<'ctx> {
|
||||
/// The trap.
|
||||
pub trap: FunctionDeclaration<'ctx>,
|
||||
/// Performs endianness swaps on i256 values
|
||||
pub byte_swap_word: FunctionDeclaration<'ctx>,
|
||||
/// Performs endianness swaps on i160 values
|
||||
pub byte_swap_eth_address: FunctionDeclaration<'ctx>,
|
||||
}
|
||||
|
||||
impl<'ctx> Intrinsics<'ctx> {
|
||||
/// The corresponding intrinsic function name.
|
||||
pub const FUNCTION_TRAP: &'static str = "llvm.trap";
|
||||
|
||||
/// The corresponding intrinsic function name.
|
||||
pub const FUNCTION_BYTE_SWAP_WORD: &'static str = "llvm.bswap.i256";
|
||||
|
||||
/// The corresponding intrinsic function name.
|
||||
pub const FUNCTION_BYTE_SWAP_ETH_ADDRESS: &'static str = "llvm.bswap.i160";
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
module: &inkwell::module::Module<'ctx>,
|
||||
) -> Self {
|
||||
let void_type = llvm.void_type();
|
||||
let word_type = llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32);
|
||||
let address_type = llvm.custom_width_int_type(revive_common::BIT_LENGTH_ETH_ADDRESS as u32);
|
||||
|
||||
let trap = Self::declare(
|
||||
llvm,
|
||||
module,
|
||||
Self::FUNCTION_TRAP,
|
||||
void_type.fn_type(&[], false),
|
||||
);
|
||||
let byte_swap_word = Self::declare(
|
||||
llvm,
|
||||
module,
|
||||
Self::FUNCTION_BYTE_SWAP_WORD,
|
||||
word_type.fn_type(&[word_type.as_basic_type_enum().into()], false),
|
||||
);
|
||||
let byte_swap_eth_address = Self::declare(
|
||||
llvm,
|
||||
module,
|
||||
Self::FUNCTION_BYTE_SWAP_ETH_ADDRESS,
|
||||
address_type.fn_type(&[address_type.as_basic_type_enum().into()], false),
|
||||
);
|
||||
|
||||
Self {
|
||||
trap,
|
||||
byte_swap_word,
|
||||
byte_swap_eth_address,
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the specified LLVM intrinsic function in the target and returns its declaration.
|
||||
pub fn declare(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
module: &inkwell::module::Module<'ctx>,
|
||||
name: &str,
|
||||
r#type: inkwell::types::FunctionType<'ctx>,
|
||||
) -> FunctionDeclaration<'ctx> {
|
||||
let intrinsic = inkwell::intrinsics::Intrinsic::find(name)
|
||||
.unwrap_or_else(|| panic!("Intrinsic function `{name}` does not exist"));
|
||||
let argument_types = Self::argument_types(llvm, name);
|
||||
let value = intrinsic
|
||||
.get_declaration(module, argument_types.as_slice())
|
||||
.unwrap_or_else(|| panic!("Intrinsic function `{name}` declaration error"));
|
||||
FunctionDeclaration::new(r#type, value)
|
||||
}
|
||||
|
||||
/// Returns the LLVM types for selecting via the signature.
|
||||
pub fn argument_types(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
name: &str,
|
||||
) -> Vec<inkwell::types::BasicTypeEnum<'ctx>> {
|
||||
let word_type = llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32);
|
||||
|
||||
match name {
|
||||
name if name == Self::FUNCTION_BYTE_SWAP_WORD => vec![word_type.as_basic_type_enum()],
|
||||
name if name == Self::FUNCTION_BYTE_SWAP_ETH_ADDRESS => {
|
||||
vec![llvm
|
||||
.custom_width_int_type(revive_common::BIT_LENGTH_ETH_ADDRESS as u32)
|
||||
.as_basic_type_enum()]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! The LLVM runtime functions.
|
||||
|
||||
use inkwell::types::BasicType;
|
||||
|
||||
use crate::optimizer::Optimizer;
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::function::declaration::Declaration as FunctionDeclaration;
|
||||
use crate::polkavm::context::function::Function;
|
||||
|
||||
/// The runtime functions, implemented on the LLVM side.
|
||||
/// The functions are automatically linked to the LLVM implementations if the signatures match.
|
||||
#[derive(Debug)]
|
||||
pub struct LLVMRuntime<'ctx> {
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub shl: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub shr: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub sar: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub byte: FunctionDeclaration<'ctx>,
|
||||
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub add_mod: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub mul_mod: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub exp: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub sign_extend: FunctionDeclaration<'ctx>,
|
||||
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub sha3: FunctionDeclaration<'ctx>,
|
||||
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub r#return: FunctionDeclaration<'ctx>,
|
||||
/// The corresponding LLVM runtime function.
|
||||
pub revert: FunctionDeclaration<'ctx>,
|
||||
}
|
||||
|
||||
impl<'ctx> LLVMRuntime<'ctx> {
|
||||
/// The LLVM personality function name.
|
||||
pub const FUNCTION_PERSONALITY: &'static str = "__personality";
|
||||
|
||||
/// The LLVM exception throwing function name.
|
||||
pub const FUNCTION_CXA_THROW: &'static str = "__cxa_throw";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SHL: &'static str = "__shl";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SHR: &'static str = "__shr";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SAR: &'static str = "__sar";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_BYTE: &'static str = "__byte";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_ADDMOD: &'static str = "__addmod";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_MULMOD: &'static str = "__mulmod";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_EXP: &'static str = "__exp";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SIGNEXTEND: &'static str = "__signextend";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SHA3: &'static str = "__sha3";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_SYSTEM_REQUEST: &'static str = "__system_request";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_FARCALL: &'static str = "__farcall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_STATICCALL: &'static str = "__staticcall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_DELEGATECALL: &'static str = "__delegatecall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_MIMICCALL: &'static str = "__mimiccall";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_FARCALL_BYREF: &'static str = "__farcall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_STATICCALL_BYREF: &'static str = "__staticcall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_DELEGATECALL_BYREF: &'static str = "__delegatecall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_MIMICCALL_BYREF: &'static str = "__mimiccall_byref";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_RETURN: &'static str = "__return";
|
||||
|
||||
/// The corresponding runtime function name.
|
||||
pub const FUNCTION_REVERT: &'static str = "__revert";
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
module: &inkwell::module::Module<'ctx>,
|
||||
optimizer: &Optimizer,
|
||||
) -> Self {
|
||||
let shl = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_SHL,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, shl, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, shl);
|
||||
|
||||
let shr = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_SHR,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, shr, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, shr);
|
||||
|
||||
let sar = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_SAR,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, sar, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, sar);
|
||||
|
||||
let byte = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_BYTE,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
2
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, byte, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, byte);
|
||||
|
||||
let add_mod =
|
||||
Self::define(module, Self::FUNCTION_ADDMOD).expect("should be declared in stdlib");
|
||||
Function::set_default_attributes(llvm, add_mod, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, add_mod);
|
||||
|
||||
let mul_mod =
|
||||
Self::define(module, Self::FUNCTION_MULMOD).expect("should be declared in stdlib");
|
||||
Function::set_default_attributes(llvm, mul_mod, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, mul_mod);
|
||||
|
||||
let exp = Self::define(module, Self::FUNCTION_EXP).expect("should be declared in stdlib");
|
||||
Function::set_default_attributes(llvm, exp, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, exp);
|
||||
|
||||
let sign_extend =
|
||||
Self::define(module, Self::FUNCTION_SIGNEXTEND).expect("should be declared in stdlib");
|
||||
Function::set_default_attributes(llvm, sign_extend, optimizer);
|
||||
Function::set_pure_function_attributes(llvm, sign_extend);
|
||||
|
||||
let sha3 = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_SHA3,
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.fn_type(
|
||||
vec![
|
||||
llvm.ptr_type(AddressSpace::Heap.into())
|
||||
.as_basic_type_enum()
|
||||
.into(),
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into(),
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_BOOLEAN as u32)
|
||||
.as_basic_type_enum()
|
||||
.into(),
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, sha3, optimizer);
|
||||
Function::set_attributes(
|
||||
llvm,
|
||||
sha3,
|
||||
//vec![Attribute::ArgMemOnly, Attribute::ReadOnly],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
|
||||
let r#return = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_RETURN,
|
||||
llvm.void_type().fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
3
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, r#return, optimizer);
|
||||
let revert = Self::declare(
|
||||
module,
|
||||
Self::FUNCTION_REVERT,
|
||||
llvm.void_type().fn_type(
|
||||
vec![
|
||||
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
|
||||
.as_basic_type_enum()
|
||||
.into();
|
||||
3
|
||||
]
|
||||
.as_slice(),
|
||||
false,
|
||||
),
|
||||
Some(inkwell::module::Linkage::External),
|
||||
);
|
||||
Function::set_default_attributes(llvm, revert, optimizer);
|
||||
|
||||
Self {
|
||||
shl,
|
||||
shr,
|
||||
sar,
|
||||
byte,
|
||||
|
||||
add_mod,
|
||||
mul_mod,
|
||||
exp,
|
||||
sign_extend,
|
||||
|
||||
sha3,
|
||||
|
||||
r#return,
|
||||
revert,
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares an LLVM runtime function in the `module`,
|
||||
pub fn declare(
|
||||
module: &inkwell::module::Module<'ctx>,
|
||||
name: &str,
|
||||
r#type: inkwell::types::FunctionType<'ctx>,
|
||||
linkage: Option<inkwell::module::Linkage>,
|
||||
) -> FunctionDeclaration<'ctx> {
|
||||
let value = module.add_function(name, r#type, linkage);
|
||||
FunctionDeclaration::new(r#type, value)
|
||||
}
|
||||
|
||||
/// Create the function definition from an existing symbol.
|
||||
pub fn define(
|
||||
module: &inkwell::module::Module<'ctx>,
|
||||
name: &str,
|
||||
) -> Option<FunctionDeclaration<'ctx>> {
|
||||
let value = module.get_function(name)?;
|
||||
value.set_linkage(inkwell::module::Linkage::External);
|
||||
FunctionDeclaration::new(value.get_type(), value).into()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
//! The LLVM IR generator function.
|
||||
|
||||
pub mod block;
|
||||
pub mod declaration;
|
||||
pub mod evmla_data;
|
||||
pub mod intrinsics;
|
||||
pub mod llvm_runtime;
|
||||
pub mod r#return;
|
||||
pub mod runtime;
|
||||
pub mod yul_data;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::optimizer::settings::size_level::SizeLevel;
|
||||
use crate::optimizer::Optimizer;
|
||||
use crate::polkavm::context::attribute::Attribute;
|
||||
use crate::polkavm::context::pointer::Pointer;
|
||||
|
||||
use self::declaration::Declaration;
|
||||
use self::evmla_data::EVMLAData;
|
||||
use self::r#return::Return;
|
||||
use self::yul_data::YulData;
|
||||
|
||||
/// The LLVM IR generator function.
|
||||
#[derive(Debug)]
|
||||
pub struct Function<'ctx> {
|
||||
/// The high-level source code name.
|
||||
name: String,
|
||||
/// The LLVM function declaration.
|
||||
declaration: Declaration<'ctx>,
|
||||
/// The stack representation.
|
||||
stack: HashMap<String, Pointer<'ctx>>,
|
||||
/// The return value entity.
|
||||
r#return: Return<'ctx>,
|
||||
|
||||
/// The entry block. Each LLVM IR functions must have an entry block.
|
||||
entry_block: inkwell::basic_block::BasicBlock<'ctx>,
|
||||
/// The return/leave block. LLVM IR functions may have multiple returning blocks, but it is
|
||||
/// more reasonable to have a single returning block and other high-level language returns
|
||||
/// jumping to it. This way it is easier to implement some additional checks and clean-ups
|
||||
/// before the returning.
|
||||
return_block: inkwell::basic_block::BasicBlock<'ctx>,
|
||||
|
||||
/// The Yul compiler data.
|
||||
yul_data: Option<YulData>,
|
||||
/// The EVM legacy assembly compiler data.
|
||||
evmla_data: Option<EVMLAData<'ctx>>,
|
||||
}
|
||||
|
||||
impl<'ctx> Function<'ctx> {
|
||||
/// The near call ABI function prefix.
|
||||
pub const ZKSYNC_NEAR_CALL_ABI_PREFIX: &'static str = "ZKSYNC_NEAR_CALL";
|
||||
|
||||
/// The near call ABI exception handler name.
|
||||
pub const ZKSYNC_NEAR_CALL_ABI_EXCEPTION_HANDLER: &'static str = "ZKSYNC_CATCH_NEAR_CALL";
|
||||
|
||||
/// The stack hashmap default capacity.
|
||||
const STACK_HASHMAP_INITIAL_CAPACITY: usize = 64;
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn new(
|
||||
name: String,
|
||||
declaration: Declaration<'ctx>,
|
||||
r#return: Return<'ctx>,
|
||||
|
||||
entry_block: inkwell::basic_block::BasicBlock<'ctx>,
|
||||
return_block: inkwell::basic_block::BasicBlock<'ctx>,
|
||||
) -> Self {
|
||||
Self {
|
||||
name,
|
||||
declaration,
|
||||
stack: HashMap::with_capacity(Self::STACK_HASHMAP_INITIAL_CAPACITY),
|
||||
r#return,
|
||||
|
||||
entry_block,
|
||||
return_block,
|
||||
|
||||
yul_data: None,
|
||||
evmla_data: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the function name reference.
|
||||
pub fn name(&self) -> &str {
|
||||
self.name.as_str()
|
||||
}
|
||||
|
||||
/// Checks whether the function is defined outside of the front-end.
|
||||
pub fn is_name_external(name: &str) -> bool {
|
||||
name.starts_with("llvm.")
|
||||
|| (name.starts_with("__")
|
||||
&& name != self::runtime::FUNCTION_ENTRY
|
||||
&& name != self::runtime::FUNCTION_DEPLOY_CODE
|
||||
&& name != self::runtime::FUNCTION_RUNTIME_CODE)
|
||||
}
|
||||
|
||||
/// Checks whether the function is related to the near call ABI.
|
||||
pub fn is_near_call_abi(name: &str) -> bool {
|
||||
name.starts_with(Self::ZKSYNC_NEAR_CALL_ABI_PREFIX)
|
||||
|| name == Self::ZKSYNC_NEAR_CALL_ABI_EXCEPTION_HANDLER
|
||||
}
|
||||
|
||||
/// Returns the LLVM function declaration.
|
||||
pub fn declaration(&self) -> Declaration<'ctx> {
|
||||
self.declaration
|
||||
}
|
||||
|
||||
/// Returns the N-th parameter of the function.
|
||||
pub fn get_nth_param(&self, index: usize) -> inkwell::values::BasicValueEnum<'ctx> {
|
||||
self.declaration()
|
||||
.value
|
||||
.get_nth_param(index as u32)
|
||||
.expect("Always exists")
|
||||
}
|
||||
|
||||
/// Sets the memory writer function attributes.
|
||||
pub fn set_attributes(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
declaration: Declaration<'ctx>,
|
||||
attributes: Vec<Attribute>,
|
||||
force: bool,
|
||||
) {
|
||||
for attribute_kind in attributes.into_iter() {
|
||||
match attribute_kind {
|
||||
Attribute::Memory => unimplemented!("`memory` attributes are not implemented"),
|
||||
attribute_kind @ Attribute::AlwaysInline if force => {
|
||||
let is_optimize_none_set = declaration
|
||||
.value
|
||||
.get_enum_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
Attribute::OptimizeNone as u32,
|
||||
)
|
||||
.is_some();
|
||||
if !is_optimize_none_set {
|
||||
declaration.value.remove_enum_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
Attribute::NoInline as u32,
|
||||
);
|
||||
declaration.value.add_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
llvm.create_enum_attribute(attribute_kind as u32, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
attribute_kind @ Attribute::NoInline if force => {
|
||||
declaration.value.remove_enum_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
Attribute::AlwaysInline as u32,
|
||||
);
|
||||
declaration.value.add_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
llvm.create_enum_attribute(attribute_kind as u32, 0),
|
||||
);
|
||||
}
|
||||
attribute_kind => declaration.value.add_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
llvm.create_enum_attribute(attribute_kind as u32, 0),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove specified attributes existing on the given declaration.
|
||||
pub fn remove_attributes(declaration: Declaration, attributes: &[Attribute]) {
|
||||
for attribute in attributes.iter().filter(|attribute| {
|
||||
declaration
|
||||
.value
|
||||
.get_enum_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
**attribute as u32,
|
||||
)
|
||||
.is_some()
|
||||
}) {
|
||||
declaration.value.remove_enum_attribute(
|
||||
inkwell::attributes::AttributeLoc::Function,
|
||||
*attribute as u32,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the default attributes.
|
||||
/// The attributes only affect the LLVM optimizations.
|
||||
pub fn set_default_attributes(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
declaration: Declaration<'ctx>,
|
||||
optimizer: &Optimizer,
|
||||
) {
|
||||
if optimizer.settings().level_middle_end == inkwell::OptimizationLevel::None {
|
||||
Self::remove_attributes(
|
||||
declaration,
|
||||
&[Attribute::OptimizeForSize, Attribute::AlwaysInline],
|
||||
);
|
||||
Self::set_attributes(
|
||||
llvm,
|
||||
declaration,
|
||||
vec![Attribute::OptimizeNone, Attribute::NoInline],
|
||||
false,
|
||||
);
|
||||
} else if optimizer.settings().level_middle_end_size == SizeLevel::Z {
|
||||
Self::set_attributes(
|
||||
llvm,
|
||||
declaration,
|
||||
vec![Attribute::OptimizeForSize, Attribute::MinSize],
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
Self::set_attributes(llvm, declaration, vec![Attribute::NoFree], false);
|
||||
}
|
||||
|
||||
/// Sets the front-end runtime attributes.
|
||||
pub fn set_frontend_runtime_attributes(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
declaration: Declaration<'ctx>,
|
||||
optimizer: &Optimizer,
|
||||
) {
|
||||
if optimizer.settings().level_middle_end_size == SizeLevel::Z {
|
||||
Self::set_attributes(llvm, declaration, vec![Attribute::NoInline], false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the exception handler attributes.
|
||||
pub fn set_exception_handler_attributes(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
declaration: Declaration<'ctx>,
|
||||
) {
|
||||
Self::set_attributes(llvm, declaration, vec![Attribute::NoInline], false);
|
||||
}
|
||||
|
||||
/// Sets the CXA-throw attributes.
|
||||
pub fn set_cxa_throw_attributes(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
declaration: Declaration<'ctx>,
|
||||
) {
|
||||
Self::set_attributes(llvm, declaration, vec![Attribute::NoProfile], false);
|
||||
}
|
||||
|
||||
/// Sets the pure function attributes.
|
||||
pub fn set_pure_function_attributes(
|
||||
llvm: &'ctx inkwell::context::Context,
|
||||
declaration: Declaration<'ctx>,
|
||||
) {
|
||||
Self::set_attributes(
|
||||
llvm,
|
||||
declaration,
|
||||
vec![
|
||||
Attribute::MustProgress,
|
||||
Attribute::NoUnwind,
|
||||
Attribute::WillReturn,
|
||||
],
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
/// Saves the pointer to a stack variable, returning the pointer to the shadowed variable,
|
||||
/// if it exists.
|
||||
pub fn insert_stack_pointer(
|
||||
&mut self,
|
||||
name: String,
|
||||
pointer: Pointer<'ctx>,
|
||||
) -> Option<Pointer<'ctx>> {
|
||||
self.stack.insert(name, pointer)
|
||||
}
|
||||
|
||||
/// Gets the pointer to a stack variable.
|
||||
pub fn get_stack_pointer(&self, name: &str) -> Option<Pointer<'ctx>> {
|
||||
self.stack.get(name).copied()
|
||||
}
|
||||
|
||||
/// Removes the pointer to a stack variable.
|
||||
pub fn remove_stack_pointer(&mut self, name: &str) {
|
||||
self.stack.remove(name);
|
||||
}
|
||||
|
||||
/// Returns the return entity representation.
|
||||
pub fn r#return(&self) -> Return<'ctx> {
|
||||
self.r#return
|
||||
}
|
||||
|
||||
/// Returns the pointer to the function return value.
|
||||
/// # Panics
|
||||
/// If the pointer has not been set yet.
|
||||
pub fn return_pointer(&self) -> Option<Pointer<'ctx>> {
|
||||
self.r#return.return_pointer()
|
||||
}
|
||||
|
||||
/// Returns the return data size in bytes, based on the default stack alignment.
|
||||
/// # Panics
|
||||
/// If the pointer has not been set yet.
|
||||
pub fn return_data_size(&self) -> usize {
|
||||
self.r#return.return_data_size()
|
||||
}
|
||||
|
||||
/// Returns the function entry block.
|
||||
pub fn entry_block(&self) -> inkwell::basic_block::BasicBlock<'ctx> {
|
||||
self.entry_block
|
||||
}
|
||||
|
||||
/// Returns the function return block.
|
||||
pub fn return_block(&self) -> inkwell::basic_block::BasicBlock<'ctx> {
|
||||
self.return_block
|
||||
}
|
||||
|
||||
/// Sets the EVM legacy assembly data.
|
||||
pub fn set_evmla_data(&mut self, data: EVMLAData<'ctx>) {
|
||||
self.evmla_data = Some(data);
|
||||
}
|
||||
|
||||
/// Returns the EVM legacy assembly data reference.
|
||||
/// # Panics
|
||||
/// If the EVM data has not been initialized.
|
||||
pub fn evmla(&self) -> &EVMLAData<'ctx> {
|
||||
self.evmla_data
|
||||
.as_ref()
|
||||
.expect("The EVM data must have been initialized")
|
||||
}
|
||||
|
||||
/// Returns the EVM legacy assembly data mutable reference.
|
||||
/// # Panics
|
||||
/// If the EVM data has not been initialized.
|
||||
pub fn evmla_mut(&mut self) -> &mut EVMLAData<'ctx> {
|
||||
self.evmla_data
|
||||
.as_mut()
|
||||
.expect("The EVM data must have been initialized")
|
||||
}
|
||||
|
||||
/// Sets the Yul data.
|
||||
pub fn set_yul_data(&mut self, data: YulData) {
|
||||
self.yul_data = Some(data);
|
||||
}
|
||||
|
||||
/// Returns the Yul data reference.
|
||||
/// # Panics
|
||||
/// If the Yul data has not been initialized.
|
||||
pub fn yul(&self) -> &YulData {
|
||||
self.yul_data
|
||||
.as_ref()
|
||||
.expect("The Yul data must have been initialized")
|
||||
}
|
||||
|
||||
/// Returns the Yul data mutable reference.
|
||||
/// # Panics
|
||||
/// If the Yul data has not been initialized.
|
||||
pub fn yul_mut(&mut self) -> &mut YulData {
|
||||
self.yul_data
|
||||
.as_mut()
|
||||
.expect("The Yul data must have been initialized")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! The LLVM IR generator function return entity.
|
||||
|
||||
use crate::polkavm::context::pointer::Pointer;
|
||||
|
||||
/// The LLVM IR generator function return entity.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Return<'ctx> {
|
||||
/// The function does not return a value.
|
||||
None,
|
||||
/// The function returns a primitive value.
|
||||
Primitive {
|
||||
/// The primitive value pointer allocated at the function entry.
|
||||
pointer: Pointer<'ctx>,
|
||||
},
|
||||
/// The function returns a compound value.
|
||||
/// In this case, the return pointer is allocated on the stack by the callee.
|
||||
Compound {
|
||||
/// The structure pointer allocated at the function entry.
|
||||
pointer: Pointer<'ctx>,
|
||||
/// The function return type size.
|
||||
size: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'ctx> Return<'ctx> {
|
||||
/// A shortcut constructor.
|
||||
pub fn none() -> Self {
|
||||
Self::None
|
||||
}
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn primitive(pointer: Pointer<'ctx>) -> Self {
|
||||
Self::Primitive { pointer }
|
||||
}
|
||||
|
||||
/// A shortcut constructor.
|
||||
pub fn compound(pointer: Pointer<'ctx>, size: usize) -> Self {
|
||||
Self::Compound { pointer, size }
|
||||
}
|
||||
|
||||
/// Returns the pointer to the function return value.
|
||||
pub fn return_pointer(&self) -> Option<Pointer<'ctx>> {
|
||||
match self {
|
||||
Return::None => None,
|
||||
Return::Primitive { pointer } => Some(pointer.to_owned()),
|
||||
Return::Compound { pointer, .. } => Some(pointer.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the return data size in bytes, based on the default stack alignment.
|
||||
pub fn return_data_size(&self) -> usize {
|
||||
revive_common::BYTE_LENGTH_WORD
|
||||
* match self {
|
||||
Self::None => 0,
|
||||
Self::Primitive { .. } => 1,
|
||||
Self::Compound { size, .. } => *size,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! The deploy code function.
|
||||
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use crate::polkavm::context::code_type::CodeType;
|
||||
use crate::polkavm::context::function::runtime;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm::WriteLLVM;
|
||||
|
||||
/// The deploy code function.
|
||||
/// Is a special function that is only used by the front-end generated code.
|
||||
#[derive(Debug)]
|
||||
pub struct DeployCode<B, D>
|
||||
where
|
||||
B: WriteLLVM<D>,
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
/// The deploy code AST representation.
|
||||
inner: B,
|
||||
/// The `D` phantom data.
|
||||
_pd: PhantomData<D>,
|
||||
}
|
||||
|
||||
impl<B, D> DeployCode<B, D>
|
||||
where
|
||||
B: WriteLLVM<D>,
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
/// A shortcut constructor.
|
||||
pub fn new(inner: B) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
_pd: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, D> WriteLLVM<D> for DeployCode<B, D>
|
||||
where
|
||||
B: WriteLLVM<D>,
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
let function_type =
|
||||
context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false);
|
||||
context.add_function(
|
||||
runtime::FUNCTION_DEPLOY_CODE,
|
||||
function_type,
|
||||
0,
|
||||
Some(inkwell::module::Linkage::External),
|
||||
)?;
|
||||
|
||||
self.inner.declare(context)
|
||||
}
|
||||
|
||||
fn into_llvm(self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
context.set_current_function(runtime::FUNCTION_DEPLOY_CODE)?;
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
context.set_code_type(CodeType::Deploy);
|
||||
|
||||
self.inner.into_llvm(context)?;
|
||||
match context
|
||||
.basic_block()
|
||||
.get_last_instruction()
|
||||
.map(|instruction| instruction.get_opcode())
|
||||
{
|
||||
Some(inkwell::values::InstructionOpcode::Br) => {}
|
||||
Some(inkwell::values::InstructionOpcode::Switch) => {}
|
||||
_ => context
|
||||
.build_unconditional_branch(context.current_function().borrow().return_block()),
|
||||
}
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().return_block());
|
||||
context.build_return(None);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! The entry function.
|
||||
|
||||
use inkwell::types::BasicType;
|
||||
use inkwell::values::BasicValue;
|
||||
|
||||
use crate::polkavm::context::address_space::AddressSpace;
|
||||
use crate::polkavm::context::function::runtime;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::r#const::*;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm::WriteLLVM;
|
||||
|
||||
/// The entry function.
|
||||
/// The function is a wrapper managing the runtime and deploy code calling logic.
|
||||
/// Is a special runtime function that is only used by the front-end generated code.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Entry {}
|
||||
|
||||
impl Entry {
|
||||
/// The call flags argument index.
|
||||
pub const ARGUMENT_INDEX_CALL_FLAGS: usize = 0;
|
||||
|
||||
/// The number of mandatory arguments.
|
||||
pub const MANDATORY_ARGUMENTS_COUNT: usize = 2;
|
||||
|
||||
/// Reserve 1mb for calldata.
|
||||
pub const MAX_CALLDATA_SIZE: usize = 1024 * 1024;
|
||||
|
||||
/// Reserve 1mb for returndata.
|
||||
pub const MAX_RETURNDATA_SIZE: usize = 1024 * 1024;
|
||||
|
||||
/// Initializes the global variables.
|
||||
/// The pointers are not initialized, because it's not possible to create a null pointer.
|
||||
pub fn initialize_globals<D>(context: &mut Context<D>) -> anyhow::Result<()>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let calldata_type = context.array_type(context.byte_type(), Self::MAX_CALLDATA_SIZE);
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_CALLDATA_POINTER,
|
||||
calldata_type,
|
||||
AddressSpace::Stack,
|
||||
calldata_type.get_undef(),
|
||||
);
|
||||
|
||||
let returndata_type = context.array_type(context.byte_type(), Self::MAX_RETURNDATA_SIZE);
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_RETURN_DATA_POINTER,
|
||||
returndata_type,
|
||||
AddressSpace::Stack,
|
||||
returndata_type.get_undef(),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER,
|
||||
context.llvm().ptr_type(AddressSpace::Heap.into()),
|
||||
AddressSpace::Stack,
|
||||
context.xlen_type().get_undef(),
|
||||
);
|
||||
context.build_store(
|
||||
context
|
||||
.get_global(crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER)?
|
||||
.into(),
|
||||
context.build_sbrk(context.integer_const(crate::polkavm::XLEN, 0))?,
|
||||
)?;
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_CALLDATA_SIZE,
|
||||
context.word_type(),
|
||||
AddressSpace::Stack,
|
||||
context.word_undef(),
|
||||
);
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_RETURN_DATA_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.xlen_type().const_zero().as_basic_value_enum(),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_CALL_FLAGS,
|
||||
context.word_type(),
|
||||
AddressSpace::Stack,
|
||||
context.word_const(0),
|
||||
);
|
||||
|
||||
let extra_abi_data_type = context.array_type(
|
||||
context.word_type().as_basic_type_enum(),
|
||||
crate::polkavm::EXTRA_ABI_DATA_SIZE,
|
||||
);
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_EXTRA_ABI_DATA,
|
||||
extra_abi_data_type,
|
||||
AddressSpace::Stack,
|
||||
extra_abi_data_type.const_zero(),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_I256_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.integer_const(
|
||||
crate::polkavm::XLEN,
|
||||
revive_common::BYTE_LENGTH_X64 as u64 * 4,
|
||||
),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_I160_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.integer_const(
|
||||
crate::polkavm::XLEN,
|
||||
revive_common::BYTE_LENGTH_X64 as u64 * 2 + revive_common::BYTE_LENGTH_X32 as u64,
|
||||
),
|
||||
);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_I64_SIZE,
|
||||
context.xlen_type(),
|
||||
AddressSpace::Stack,
|
||||
context.integer_const(crate::polkavm::XLEN, revive_common::BYTE_LENGTH_X64 as u64),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load the calldata via seal `input` and initialize the calldata end
|
||||
/// and calldata size globals.
|
||||
pub fn load_calldata<D>(context: &mut Context<D>) -> anyhow::Result<()>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let input_pointer = context
|
||||
.get_global(crate::polkavm::GLOBAL_CALLDATA_POINTER)?
|
||||
.value
|
||||
.as_pointer_value();
|
||||
let input_pointer_casted = context.builder.build_ptr_to_int(
|
||||
input_pointer,
|
||||
context.xlen_type(),
|
||||
"input_pointer_casted",
|
||||
)?;
|
||||
|
||||
let length_pointer = context.build_alloca(context.xlen_type(), "len_ptr");
|
||||
let length_pointer_casted = context.builder.build_ptr_to_int(
|
||||
length_pointer.value,
|
||||
context.xlen_type(),
|
||||
"length_pointer_casted",
|
||||
)?;
|
||||
|
||||
context.build_store(
|
||||
length_pointer,
|
||||
context.integer_const(crate::polkavm::XLEN, Self::MAX_CALLDATA_SIZE as u64),
|
||||
)?;
|
||||
context.build_runtime_call(
|
||||
runtime_api::imports::INPUT,
|
||||
&[input_pointer_casted.into(), length_pointer_casted.into()],
|
||||
);
|
||||
|
||||
// Store the calldata size
|
||||
let calldata_size = context
|
||||
.build_load(length_pointer, "input_size")?
|
||||
.into_int_value();
|
||||
let calldata_size_casted = context.builder().build_int_z_extend(
|
||||
calldata_size,
|
||||
context.word_type(),
|
||||
"zext_input_len",
|
||||
)?;
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_CALLDATA_SIZE,
|
||||
context.word_type(),
|
||||
AddressSpace::Stack,
|
||||
calldata_size_casted,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Calls the deploy code if the first function argument was `1`.
|
||||
/// Calls the runtime code otherwise.
|
||||
pub fn leave_entry<D>(context: &mut Context<D>) -> anyhow::Result<()>
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
let is_deploy = context
|
||||
.current_function()
|
||||
.borrow()
|
||||
.get_nth_param(Self::ARGUMENT_INDEX_CALL_FLAGS);
|
||||
|
||||
context.set_global(
|
||||
crate::polkavm::GLOBAL_CALL_FLAGS,
|
||||
is_deploy.get_type(),
|
||||
AddressSpace::Stack,
|
||||
is_deploy.into_int_value(),
|
||||
);
|
||||
|
||||
let deploy_code_call_block = context.append_basic_block("deploy_code_call_block");
|
||||
let runtime_code_call_block = context.append_basic_block("runtime_code_call_block");
|
||||
|
||||
context.build_conditional_branch(
|
||||
is_deploy.into_int_value(),
|
||||
deploy_code_call_block,
|
||||
runtime_code_call_block,
|
||||
)?;
|
||||
|
||||
let deploy_code = context
|
||||
.functions
|
||||
.get(runtime::FUNCTION_DEPLOY_CODE)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("Contract deploy code not found"))?;
|
||||
let runtime_code = context
|
||||
.functions
|
||||
.get(runtime::FUNCTION_RUNTIME_CODE)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("Contract runtime code not found"))?;
|
||||
|
||||
context.set_basic_block(deploy_code_call_block);
|
||||
context.build_call(deploy_code.borrow().declaration, &[], "deploy_code_call");
|
||||
context.build_unconditional_branch(context.current_function().borrow().return_block());
|
||||
|
||||
context.set_basic_block(runtime_code_call_block);
|
||||
context.build_call(runtime_code.borrow().declaration, &[], "runtime_code_call");
|
||||
context.build_unconditional_branch(context.current_function().borrow().return_block());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> WriteLLVM<D> for Entry
|
||||
where
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
let entry_arguments = vec![context.bool_type().as_basic_type_enum()];
|
||||
let entry_function_type = context.function_type(entry_arguments, 0, false);
|
||||
context.add_function(runtime::FUNCTION_ENTRY, entry_function_type, 0, None)?;
|
||||
|
||||
for symbol in runtime_api::exports::EXPORTS {
|
||||
context.declare_extern_function(symbol)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Instead of a single entrypoint, the runtime expects two exports: `call ` and `deploy`.
|
||||
/// `call` and `deploy` directly call `entry`, signaling a deploy if the first arg is `1`.
|
||||
/// The `entry` function loads calldata, sets globals and calls the runtime or deploy code.
|
||||
fn into_llvm(self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
let entry = context
|
||||
.get_function(runtime::FUNCTION_ENTRY)
|
||||
.expect("the entry function should already be declared")
|
||||
.borrow()
|
||||
.declaration;
|
||||
crate::PolkaVMFunction::set_attributes(
|
||||
context.llvm(),
|
||||
entry,
|
||||
vec![crate::PolkaVMAttribute::NoReturn],
|
||||
true,
|
||||
);
|
||||
|
||||
context.set_current_function(runtime_api::exports::DEPLOY)?;
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
|
||||
assert!(context
|
||||
.build_call(entry, &[context.bool_const(true).into()], "entry_deploy")
|
||||
.is_none());
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().return_block);
|
||||
context.build_unreachable();
|
||||
|
||||
context.set_current_function(runtime_api::exports::CALL)?;
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
|
||||
assert!(context
|
||||
.build_call(entry, &[context.bool_const(false).into()], "entry_call")
|
||||
.is_none());
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().return_block);
|
||||
context.build_unreachable();
|
||||
|
||||
context.set_current_function(runtime::FUNCTION_ENTRY)?;
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
|
||||
Self::initialize_globals(context)?;
|
||||
Self::load_calldata(context)?;
|
||||
Self::leave_entry(context)?;
|
||||
|
||||
context.build_unconditional_branch(context.current_function().borrow().return_block());
|
||||
context.set_basic_block(context.current_function().borrow().return_block());
|
||||
context.build_unreachable();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! The front-end runtime functions.
|
||||
|
||||
pub mod deploy_code;
|
||||
pub mod entry;
|
||||
pub mod runtime_code;
|
||||
|
||||
/// The main entry function name.
|
||||
pub const FUNCTION_ENTRY: &str = "__entry";
|
||||
|
||||
/// The deploy code function name.
|
||||
pub const FUNCTION_DEPLOY_CODE: &str = "__deploy";
|
||||
|
||||
/// The runtime code function name.
|
||||
pub const FUNCTION_RUNTIME_CODE: &str = "__runtime";
|
||||
@@ -0,0 +1,79 @@
|
||||
//! The runtime code function.
|
||||
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use crate::polkavm::context::code_type::CodeType;
|
||||
use crate::polkavm::context::function::runtime;
|
||||
use crate::polkavm::context::Context;
|
||||
use crate::polkavm::Dependency;
|
||||
use crate::polkavm::WriteLLVM;
|
||||
|
||||
/// The runtime code function.
|
||||
/// Is a special function that is only used by the front-end generated code.
|
||||
#[derive(Debug)]
|
||||
pub struct RuntimeCode<B, D>
|
||||
where
|
||||
B: WriteLLVM<D>,
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
/// The runtime code AST representation.
|
||||
inner: B,
|
||||
/// The `D` phantom data.
|
||||
_pd: PhantomData<D>,
|
||||
}
|
||||
|
||||
impl<B, D> RuntimeCode<B, D>
|
||||
where
|
||||
B: WriteLLVM<D>,
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
/// A shortcut constructor.
|
||||
pub fn new(inner: B) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
_pd: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, D> WriteLLVM<D> for RuntimeCode<B, D>
|
||||
where
|
||||
B: WriteLLVM<D>,
|
||||
D: Dependency + Clone,
|
||||
{
|
||||
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
let function_type =
|
||||
context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false);
|
||||
context.add_function(
|
||||
runtime::FUNCTION_RUNTIME_CODE,
|
||||
function_type,
|
||||
0,
|
||||
Some(inkwell::module::Linkage::External),
|
||||
)?;
|
||||
|
||||
self.inner.declare(context)
|
||||
}
|
||||
|
||||
fn into_llvm(self, context: &mut Context<D>) -> anyhow::Result<()> {
|
||||
context.set_current_function(runtime::FUNCTION_RUNTIME_CODE)?;
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().entry_block());
|
||||
context.set_code_type(CodeType::Runtime);
|
||||
self.inner.into_llvm(context)?;
|
||||
match context
|
||||
.basic_block()
|
||||
.get_last_instruction()
|
||||
.map(|instruction| instruction.get_opcode())
|
||||
{
|
||||
Some(inkwell::values::InstructionOpcode::Br) => {}
|
||||
Some(inkwell::values::InstructionOpcode::Switch) => {}
|
||||
_ => context
|
||||
.build_unconditional_branch(context.current_function().borrow().return_block()),
|
||||
}
|
||||
|
||||
context.set_basic_block(context.current_function().borrow().return_block());
|
||||
context.build_unreachable();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user