Skip to content

Truly independent web browser

Everywhere: Remove the C++ WebAssembly engine and Cranelift

Andreas Klingbc27e72565a4
diff --git a/.github/workflows/js-and-wasm-artifacts.yml b/.github/workflows/js-and-wasm-artifacts.yml
index 7579172e8c4..63de3dd171a 100644
--- a/.github/workflows/js-and-wasm-artifacts.yml
+++ b/.github/workflows/js-and-wasm-artifacts.yml
@@ -178,11 +178,3 @@ jobs:
name: ladybird-wasm-${{ matrix.package_type }}
path: Build/distribution/ladybird-wasm-*.tar.gz
retention-days: 7
-
- - name: Upload cranelift-compiler binary
- uses: actions/upload-artifact@v7
- with:
- name: ladybird-cranelift-compiler-${{ matrix.package_type }}
- path: Build/distribution/bin/cranelift-compiler
- retention-days: 7
- if-no-files-found: ignore
diff --git a/.github/workflows/js-and-wasm-benchmarks.yml b/.github/workflows/js-and-wasm-benchmarks.yml
index b6ffd629a5a..f9cb338932a 100644
--- a/.github/workflows/js-and-wasm-benchmarks.yml
+++ b/.github/workflows/js-and-wasm-benchmarks.yml
@@ -83,20 +83,6 @@ jobs:
cd wasm-repl
tar -xvzf ladybird-wasm-${{ matrix.os_name }}-${{ matrix.arch }}.tar.gz
- - name: 'Download cranelift-compiler artifact'
- uses: dawidd6/action-download-artifact@v24
- with:
- run_id: ${{ github.event.workflow_run.id }}
- name: ladybird-cranelift-compiler-${{ matrix.package_type }}
- path: cranelift-compiler
- if_no_artifact_found: warn
-
- - name: 'Install cranelift-compiler next to wasm'
- if: ${{ hashFiles('cranelift-compiler/cranelift-compiler') != '' && hashFiles('wasm-repl/bin/wasm') != '' }}
- shell: bash
- run: |
- install -m 0755 cranelift-compiler/cranelift-compiler wasm-repl/bin/cranelift-compiler
-
- name: 'Run the benchmarks'
shell: bash
run: |
diff --git a/AK/COWVector.h b/AK/COWVector.h
deleted file mode 100644
index e7deb2cb036..00000000000
--- a/AK/COWVector.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (c) 2021-2024, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullRefPtr.h>
-#include <AK/RefCounted.h>
-#include <AK/Vector.h>
-
-namespace AK {
-
-template<typename T>
-class COWVector {
- struct Detail : RefCounted<Detail> {
- Vector<T> m_members;
- };
-
-public:
- COWVector()
- : m_detail(make_ref_counted<Detail>())
- {
- }
-
- COWVector(std::initializer_list<T> entries)
- : m_detail(make_ref_counted<Detail>())
- {
- for (auto& entry : entries)
- m_detail->m_members.append(entry);
- }
-
- COWVector(COWVector const&) = default;
- COWVector(COWVector&&) = default;
-
- COWVector& operator=(COWVector const&) = default;
- COWVector& operator=(COWVector&&) = default;
-
- Vector<T> release() &&
- {
- if (m_detail->ref_count() == 1)
- return exchange(m_detail->m_members, Vector<T>());
-
- return m_detail->m_members;
- }
-
- void append(T const& value)
- {
- return append(T { value });
- }
-
- void append(T&& value)
- {
- copy();
- m_detail->m_members.append(move(value));
- }
-
- void extend(Vector<T>&& values)
- {
- copy();
- m_detail->m_members.extend(move(values));
- }
-
- void extend(Vector<T> const& values)
- {
- copy();
- m_detail->m_members.extend(values);
- }
-
- void extend(COWVector<T> const& values)
- {
- copy();
- m_detail->m_members.extend(values.m_detail->m_members);
- }
-
- void resize(size_t size)
- {
- copy();
- m_detail->m_members.resize(size);
- }
-
- void ensure_capacity(size_t capacity)
- {
- if (m_detail->m_members.capacity() >= capacity)
- return;
-
- copy();
- m_detail->m_members.ensure_capacity(capacity);
- }
-
- void prepend(T value)
- {
- copy();
- m_detail->m_members.prepend(move(value));
- }
-
- template<typename... Args>
- void empend(Args&&... args)
- {
- copy();
- m_detail->m_members.empend(forward<Args>(args)...);
- }
-
- void clear()
- {
- if (m_detail->ref_count() > 1)
- m_detail = make_ref_counted<Detail>();
- else
- m_detail->m_members.clear();
- }
-
- T& mutable_at(size_t index)
- {
- // We're handing out a mutable reference, so make sure we own the data exclusively.
- copy();
- return m_detail->m_members.at(index);
- }
-
- T const& at(size_t index) const
- {
- return m_detail->m_members.at(index);
- }
-
- T const& operator[](size_t index) const
- {
- return m_detail->m_members[index];
- }
-
- Span<T const> span() const { return m_detail->m_members; }
- Span<T> mutable_span()
- {
- copy();
- return m_detail->m_members;
- }
-
- size_t capacity() const
- {
- return m_detail->m_members.capacity();
- }
-
- size_t size() const
- {
- return m_detail->m_members.size();
- }
-
- bool is_empty() const
- {
- return m_detail->m_members.is_empty();
- }
-
- T const& first() const
- {
- return m_detail->m_members.first();
- }
-
- T const& last() const
- {
- return m_detail->m_members.last();
- }
-
- auto begin() const { return m_detail->m_members.begin(); }
- auto end() const { return m_detail->m_members.end(); }
-
-private:
- void copy()
- {
- if (m_detail->ref_count() <= 1)
- return;
- auto new_detail = make_ref_counted<Detail>();
- new_detail->m_members = m_detail->m_members;
- m_detail = new_detail;
- }
-
- NonnullRefPtr<Detail> m_detail;
-};
-
-}
-
-#if USING_AK_GLOBALLY
-using AK::COWVector;
-#endif
diff --git a/AK/Debug.h.in b/AK/Debug.h.in
index 458d233f740..3403fc14182 100644
--- a/AK/Debug.h.in
+++ b/AK/Debug.h.in
@@ -282,30 +282,6 @@
# cmakedefine01 VULKAN_VALIDATION_LAYERS_DEBUG
#endif
-#ifndef WASI_DEBUG
-# cmakedefine01 WASI_DEBUG
-#endif
-
-#ifndef WASI_FINE_GRAINED_DEBUG
-# cmakedefine01 WASI_FINE_GRAINED_DEBUG
-#endif
-
-#ifndef WASM_BINPARSER_DEBUG
-# cmakedefine01 WASM_BINPARSER_DEBUG
-#endif
-
-#ifndef WASM_CRANELIFT_DEBUG
-# cmakedefine01 WASM_CRANELIFT_DEBUG
-#endif
-
-#ifndef WASM_TRACE_DEBUG
-# cmakedefine01 WASM_TRACE_DEBUG
-#endif
-
-#ifndef WASM_VALIDATOR_DEBUG
-# cmakedefine01 WASM_VALIDATOR_DEBUG
-#endif
-
#ifndef WEBDRIVER_DEBUG
# cmakedefine01 WEBDRIVER_DEBUG
#endif
diff --git a/AK/SIMDExtras.h b/AK/SIMDExtras.h
deleted file mode 100644
index cab6f1d635e..00000000000
--- a/AK/SIMDExtras.h
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (c) 2021, Stephan Unverwerth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/BitCast.h>
-#include <AK/Concepts.h>
-#include <AK/SIMD.h>
-
-// Functions returning vectors or accepting vector arguments have different calling conventions
-// depending on whether the target architecture supports SSE or not. GCC generates warning "psabi"
-// when compiling for non-SSE architectures. We disable this warning because these functions
-// are static and should never be visible from outside the translation unit that includes this header.
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wpsabi"
-
-namespace AK::SIMD {
-
-// SIMD Vector Expansion
-
-ALWAYS_INLINE static constexpr f32x4 expand4(float f)
-{
- return f32x4 { f, f, f, f };
-}
-
-ALWAYS_INLINE static constexpr i32x4 expand4(i32 i)
-{
- return i32x4 { i, i, i, i };
-}
-
-ALWAYS_INLINE static constexpr u32x4 expand4(u32 u)
-{
- return u32x4 { u, u, u, u };
-}
-
-// Casting
-
-template<typename TSrc>
-ALWAYS_INLINE static u8x4 to_u8x4(TSrc v)
-{
- return __builtin_convertvector(v, u8x4);
-}
-
-template<typename TSrc>
-ALWAYS_INLINE static u16x4 to_u16x4(TSrc v)
-{
- return __builtin_convertvector(v, u16x4);
-}
-
-template<typename TSrc>
-ALWAYS_INLINE static u32x4 to_u32x4(TSrc v)
-{
- return __builtin_convertvector(v, u32x4);
-}
-
-template<typename TSrc>
-ALWAYS_INLINE static i32x4 to_i32x4(TSrc v)
-{
- return __builtin_convertvector(v, i32x4);
-}
-
-template<typename TSrc>
-ALWAYS_INLINE static f32x4 to_f32x4(TSrc v)
-{
- return __builtin_convertvector(v, f32x4);
-}
-
-// Masking
-
-ALWAYS_INLINE static i32 maskbits(i32x4 mask)
-{
-#if defined(__SSE__)
- return __builtin_ia32_movmskps((f32x4)mask);
-#else
- return ((mask[0] & 0x80000000) >> 31) | ((mask[1] & 0x80000000) >> 30) | ((mask[2] & 0x80000000) >> 29) | ((mask[3] & 0x80000000) >> 28);
-#endif
-}
-
-ALWAYS_INLINE static bool all(i32x4 mask)
-{
- return maskbits(mask) == 15;
-}
-
-ALWAYS_INLINE static bool any(i32x4 mask)
-{
- return maskbits(mask) != 0;
-}
-
-ALWAYS_INLINE static bool none(i32x4 mask)
-{
- return maskbits(mask) == 0;
-}
-
-ALWAYS_INLINE static int maskcount(i32x4 mask)
-{
- constexpr static int count_lut[16] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
- return count_lut[maskbits(mask)];
-}
-
-// Load / Store
-
-template<SIMDVector VectorType>
-ALWAYS_INLINE static VectorType load_unaligned(void const* a)
-{
- VectorType v;
- __builtin_memcpy(&v, a, sizeof(VectorType));
- return v;
-}
-
-template<SIMDVector VectorType>
-ALWAYS_INLINE static void store_unaligned(void* a, VectorType const& v)
-{
- // FIXME: Does this generate the right instructions?
- __builtin_memcpy(a, &v, sizeof(VectorType));
-}
-
-ALWAYS_INLINE static f32x4 load4(float const* a, float const* b, float const* c, float const* d)
-{
- return f32x4 { *a, *b, *c, *d };
-}
-
-ALWAYS_INLINE static u32x4 load4(u32 const* a, u32 const* b, u32 const* c, u32 const* d)
-{
- return u32x4 { *a, *b, *c, *d };
-}
-
-ALWAYS_INLINE static f32x4 load4_masked(float const* a, float const* b, float const* c, float const* d, i32x4 mask)
-{
- int bits = maskbits(mask);
- return f32x4 {
- bits & 1 ? *a : 0.f,
- bits & 2 ? *b : 0.f,
- bits & 4 ? *c : 0.f,
- bits & 8 ? *d : 0.f,
- };
-}
-
-ALWAYS_INLINE static i32x4 load4_masked(u8 const* a, u8 const* b, u8 const* c, u8 const* d, i32x4 mask)
-{
- int bits = maskbits(mask);
- return i32x4 {
- bits & 1 ? *a : 0,
- bits & 2 ? *b : 0,
- bits & 4 ? *c : 0,
- bits & 8 ? *d : 0,
- };
-}
-
-ALWAYS_INLINE static u32x4 load4_masked(u32 const* a, u32 const* b, u32 const* c, u32 const* d, i32x4 mask)
-{
- int bits = maskbits(mask);
- return u32x4 {
- bits & 1 ? *a : 0u,
- bits & 2 ? *b : 0u,
- bits & 4 ? *c : 0u,
- bits & 8 ? *d : 0u,
- };
-}
-
-template<typename VectorType, typename UnderlyingType = decltype(declval<VectorType>()[0])>
-ALWAYS_INLINE static void store4(VectorType v, UnderlyingType* a, UnderlyingType* b, UnderlyingType* c, UnderlyingType* d)
-{
- *a = v[0];
- *b = v[1];
- *c = v[2];
- *d = v[3];
-}
-
-template<typename VectorType, typename UnderlyingType = decltype(declval<VectorType>()[0])>
-ALWAYS_INLINE static void store4_masked(VectorType v, UnderlyingType* a, UnderlyingType* b, UnderlyingType* c, UnderlyingType* d, i32x4 mask)
-{
- int bits = maskbits(mask);
- if (bits & 1)
- *a = v[0];
- if (bits & 2)
- *b = v[1];
- if (bits & 4)
- *c = v[2];
- if (bits & 8)
- *d = v[3];
-}
-
-// Shuffle
-namespace Detail {
-
-template<SIMDVector T, SIMDVector Control, size_t... Idx>
-ALWAYS_INLINE static T shuffle_impl(T a, Control control, IndexSequence<Idx...>)
-{
- // FIXME: Maybe make the VERIFYs optional, eg on SIMD-DEBUG, to avoid the overhead in performance oriented users, like LibWasm::SIMD
- // Note: - instead of _ to make the linter happy, as SIMD-DEBUG does not (yet) exist
- constexpr Conditional<IsSigned<ElementOf<Control>>, ssize_t, size_t> N = vector_length<T>;
- // If you hit this verify and want a 0 in these cases instead, use shuffle_or_0
- (([control] { VERIFY(control[Idx] < N); })(), ...);
-
- // __builtin_shuffle is only available with GCC, and has quite good codegen
- if constexpr (__has_builtin(__builtin_shuffle))
- return __builtin_shuffle(a, control);
-
- return T {
- a[control[Idx]]...
- };
-}
-
-// FIXME: AppleClang somehow unconditionally executes the `a[control[Idx]]` path,
-// even if its in the false branch of the ternary
-// This leads to a presumably out of bounds access, which is UB
-// Reenable the sanitizer once this is fixed
-// As a side note UBsan makes a total mess of the codegen anyway
-template<SIMDVector T, SIMDVector Control, size_t... Idx>
-#ifdef AK_COMPILER_CLANG
-[[clang::no_sanitize("undefined")]]
-#endif
-ALWAYS_INLINE static T shuffle_or_0_impl(T a, Control control, IndexSequence<Idx...>)
-{
- constexpr Conditional<IsSigned<ElementOf<Control>>, ssize_t, size_t> N = vector_length<T>;
- using E = ElementOf<T>;
-
- if constexpr (__has_builtin(__builtin_shuffle)) {
- auto vector = __builtin_shuffle(a, control);
- for (size_t i = 0; i < N; ++i)
- vector[i] = control[i] < 0 || control[i] >= N ? 0 : vector[i];
- return vector;
- }
- // 1. Set all out of bounds values to ~0
- // Note: This is done so that the optimization mentioned down below works
- // Note: Vector compares result in bitmasks, aka all 1s or all 0s per element
- control |= ~((control >= 0) & (control < N));
- // 2. Selectively set out of bounds values to 0
- // Note: Clang successfully optimizes this to a few instructions on x86-ssse3, GCC does not
- // Vector Optimizations/Instruction-Selection on ArmV8 seem to not be as powerful as of Clang18
- // FIXME: We could recreate the bit mask Clang uses for the select for u32 and u16
- // control = control * explode_byte(sizeof(E)) + 0x03020100;
- // return (T)shuffle_unchecked(Bytes(a), Bytes(control));
- // Note: On x86-ssse3, `pshufb` inserts a zero if the control byte has the highest bit set
- // On ArmV8, `tbl` inserts a zero if the control byte is out of bounds in general
- // On RiscV `vrgather.vv` inserts a 0 if the control index is out of bounds
- // and is more powerful than the other two as it is able to use bigger item widths than a byte
- // Note: For u64x2 Clang seems to always unroll the compare instead of doing the fancy `phufb`
-
- return T {
- ((E)(control[Idx] != ~0 ? a[control[Idx]] : 0))...
- };
-}
-
-template<SIMDVector T, size_t... Idx>
-ALWAYS_INLINE static T item_reverse_impl(T a, IndexSequence<Idx...>)
-{
- constexpr size_t N = vector_length<T>;
- return __builtin_shufflevector(a, a, N - 1 - Idx...);
-}
-
-template<SIMDVector T, size_t... Idx>
-ALWAYS_INLINE static T byte_reverse_impl(T a, IndexSequence<Idx...>)
-{
- static_assert(sizeof...(Idx) == sizeof(T));
- constexpr size_t N = sizeof(T);
- // FIXME: GCC silently ignores the dependent vector_size attribute, this seems to be a bug
- // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68703
- // Hence this giant conditional
- using BytesVector = Conditional<sizeof(T) == 2, u8x2, Conditional<sizeof(T) == 4, u8x4, Conditional<sizeof(T) == 8, u8x8, Conditional<sizeof(T) == 16, u8x16, Conditional<sizeof(T) == 32, u8x32, void>>>>>;
- static_assert(sizeof(BytesVector) == sizeof(T));
- return bit_cast<T>(
- __builtin_shufflevector(
- bit_cast<BytesVector>(a),
- bit_cast<BytesVector>(a),
- N - 1 - Idx...));
-}
-
-template<SIMDVector T, size_t... Idx>
-ALWAYS_INLINE static T elementwise_byte_reverse_impl(T a, IndexSequence<Idx...>)
-{
- static_assert(sizeof...(Idx) == vector_length<T>);
- using Element = ElementOf<T>;
- if constexpr (sizeof(Element) == 1) {
- return a;
- } else if constexpr (sizeof(Element) == 2) {
- return T {
- static_cast<Element>(__builtin_bswap16(static_cast<u16>(a[Idx])))...
- };
- } else if constexpr (sizeof(Element) == 4) {
- return T {
- static_cast<Element>(__builtin_bswap32(static_cast<u32>(a[Idx])))...
- };
- } else if constexpr (sizeof(Element) == 8) {
- return T {
- static_cast<Element>(__builtin_bswap64(static_cast<u64>(a[Idx])))...
- };
- } else {
- static_assert(DependentFalse<T>);
- }
-}
-
-}
-
-// FIXME: Shuffles only work with integral types for now
-template<SIMDVector T>
-ALWAYS_INLINE static T shuffle(T a, IndexVectorFor<T> control)
-{
- return Detail::shuffle_impl(a, control, MakeIndexSequence<vector_length<T>>());
-}
-
-template<SIMDVector T>
-ALWAYS_INLINE static T shuffle_or_0(T a, IndexVectorFor<T> control)
-{
- return Detail::shuffle_or_0_impl(a, control, MakeIndexSequence<vector_length<T>>());
-}
-
-template<SIMDVector T>
-ALWAYS_INLINE static T item_reverse(T a)
-{
- return Detail::item_reverse_impl(a, MakeIndexSequence<vector_length<T>>());
-}
-
-template<SIMDVector T>
-ALWAYS_INLINE static T byte_reverse(T a)
-{
- return Detail::byte_reverse_impl(a, MakeIndexSequence<sizeof(T)>());
-}
-
-template<SIMDVector T>
-ALWAYS_INLINE static T elementwise_byte_reverse(T a)
-{
- return Detail::elementwise_byte_reverse_impl(a, MakeIndexSequence<vector_length<T>>());
-}
-
-}
-
-#pragma GCC diagnostic pop
diff --git a/AK/ScopeLogger.h b/AK/ScopeLogger.h
deleted file mode 100644
index 98951f391c1..00000000000
--- a/AK/ScopeLogger.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (c) 2020, Denis Campredon <[email protected]>
- * Copyright (c) 2021, the SerenityOS developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteString.h>
-#include <AK/SourceLocation.h>
-#include <AK/StringBuilder.h>
-
-namespace AK {
-
-template<bool = true>
-class ScopeLogger {
-public:
- ScopeLogger(StringView extra, SourceLocation const& location = SourceLocation::current())
- : m_location(location)
- , m_extra(extra)
- {
- StringBuilder sb;
-
- for (auto indent = m_depth++; indent > 0; indent--)
- sb.append(' ');
- if (m_extra.is_empty())
- dbgln("\033[1;{}m{}entering {}\033[0m", m_depth % 8 + 30, sb.to_byte_string(), m_location);
- else
- dbgln("\033[1;{}m{}entering {}\033[0m ({})", m_depth % 8 + 30, sb.to_byte_string(), m_location, m_extra);
- }
-
- ScopeLogger(SourceLocation location = SourceLocation::current())
- : ScopeLogger({}, move(location))
- {
- }
-
- ~ScopeLogger()
- {
- StringBuilder sb;
-
- auto depth = m_depth;
- for (auto indent = --m_depth; indent > 0; indent--)
- sb.append(' ');
- if (m_extra.is_empty())
- dbgln("\033[1;{}m{}leaving {}\033[0m", depth % 8 + 30, sb.to_byte_string(), m_location);
- else
- dbgln("\033[1;{}m{}leaving {}\033[0m ({})", depth % 8 + 30, sb.to_byte_string(), m_location, m_extra);
- }
-
-private:
- static inline size_t m_depth = 0;
- SourceLocation m_location;
- ByteString m_extra;
-};
-
-template<>
-class ScopeLogger<false> {
-public:
- template<typename... Args>
- ScopeLogger(Args...) { }
-};
-
-}
-
-#if USING_AK_GLOBALLY
-using AK::ScopeLogger;
-#endif
diff --git a/AK/ScopedValueRollback.h b/AK/ScopedValueRollback.h
deleted file mode 100644
index 6f9e920b37c..00000000000
--- a/AK/ScopedValueRollback.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2018-2020, Andreas Kling <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-namespace AK {
-
-template<typename T>
-class ScopedValueRollback {
-public:
- ScopedValueRollback(T& variable)
- : m_variable(variable)
- , m_saved_value(variable)
- {
- }
-
- ~ScopedValueRollback()
- {
- m_variable = m_saved_value;
- }
-
- void set_override_rollback_value(T const& value)
- {
- m_saved_value = value;
- }
-
-private:
- T& m_variable;
- T m_saved_value;
-};
-
-}
-
-#if USING_AK_GLOBALLY
-using AK::ScopedValueRollback;
-#endif
diff --git a/Cargo.lock b/Cargo.lock
index 49f72d807f2..c2176adab68 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -112,12 +112,6 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
-[[package]]
-name = "arbitrary"
-version = "1.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
-
[[package]]
name = "array-init"
version = "2.1.0"
@@ -151,15 +145,6 @@ dependencies = [
"serde_core",
]
-[[package]]
-name = "bumpalo"
-version = "3.20.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
-dependencies = [
- "allocator-api2",
-]
-
[[package]]
name = "byteorder"
version = "1.5.0"
@@ -270,155 +255,6 @@ dependencies = [
"libm",
]
-[[package]]
-name = "cranelift-assembler-x64"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f6d504c8c7ba3f3accaf8e98b7096beb98e1a271404357744c7e9e730c6865ff"
-dependencies = [
- "cranelift-assembler-x64-meta",
-]
-
-[[package]]
-name = "cranelift-assembler-x64-meta"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c065757905596bc06e82969ebd7b92d691b7fd710a7e9e8181ae0c30dab588d0"
-dependencies = [
- "cranelift-srcgen",
-]
-
-[[package]]
-name = "cranelift-bforest"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ca7162cd4d4fc5f9f2f88d1459d939882203d93a8c5a19ef2c405b2e82ef13f"
-dependencies = [
- "cranelift-entity",
- "wasmtime-internal-core",
-]
-
-[[package]]
-name = "cranelift-bitset"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ec2ba2d4f3d959ec4023a10266c3dcfb28381d1938d507a9a5e1abb78bbcc88"
-dependencies = [
- "wasmtime-internal-core",
-]
-
-[[package]]
-name = "cranelift-codegen"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "51a64cb821d5fed56bdd6053acd36fa928cd82b70bf6b19b8b14b8b27d047b9a"
-dependencies = [
- "bumpalo",
- "cranelift-assembler-x64",
- "cranelift-bforest",
- "cranelift-bitset",
- "cranelift-codegen-meta",
- "cranelift-codegen-shared",
- "cranelift-control",
- "cranelift-entity",
- "cranelift-isle",
- "gimli",
- "hashbrown 0.17.1",
- "libm",
- "log",
- "regalloc2",
- "rustc-hash",
- "serde",
- "smallvec",
- "target-lexicon",
- "wasmtime-internal-core",
-]
-
-[[package]]
-name = "cranelift-codegen-meta"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "142be1e267a7497ba3c2b5a829eaf5387b92b9bcdba6e0a6020f1ffccae7f2b8"
-dependencies = [
- "cranelift-assembler-x64-meta",
- "cranelift-codegen-shared",
- "cranelift-srcgen",
- "heck",
-]
-
-[[package]]
-name = "cranelift-codegen-shared"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e41f75410da6cce8601330137d73718f679db81cb790a33de3871b5c90a0de3"
-
-[[package]]
-name = "cranelift-control"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0c2616c6d01c14921ac9289ef65eb7702d9c760dfdc4537a8ee5bf38ea2832c6"
-dependencies = [
- "arbitrary",
-]
-
-[[package]]
-name = "cranelift-entity"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a03e8b44c4877cf2fb21e5788d514af6fd291a066ed9ae37adf114a25fecb4aa"
-dependencies = [
- "cranelift-bitset",
- "wasmtime-internal-core",
-]
-
-[[package]]
-name = "cranelift-frontend"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "366ff7cb014bd08752210eba55a650969f8db9b52670d69d2ea0b23e1e9e3edf"
-dependencies = [
- "cranelift-codegen",
- "hashbrown 0.17.1",
- "log",
- "smallvec",
- "target-lexicon",
-]
-
-[[package]]
-name = "cranelift-isle"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9ea6526ebf9064fff8ce3b1e26afad7027f9e6bb0e45d2b9200e4cbab8343345"
-
-[[package]]
-name = "cranelift-module"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9d429c66b47fc0482e2398f660bda8f4cae30e5ae4e82a281b04f9beaefe1cf"
-dependencies = [
- "anyhow",
- "cranelift-codegen",
- "cranelift-control",
- "hashbrown 0.17.1",
-]
-
-[[package]]
-name = "cranelift-native"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b44d323f3e5108a8a5bc61f3acd227285ece066e19afe9aece211d66b34a64ea"
-dependencies = [
- "cranelift-codegen",
- "libc",
- "target-lexicon",
-]
-
-[[package]]
-name = "cranelift-srcgen"
-version = "0.136.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc173168f291ff3b95b5d0769d6a05b1eaef5e6d74c2600affab8396b4e7b420"
-
[[package]]
name = "displaydoc"
version = "0.2.5"
@@ -501,12 +337,6 @@ dependencies = [
"rustc_version",
]
-[[package]]
-name = "fnv"
-version = "1.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
-
[[package]]
name = "foldhash"
version = "0.1.5"
@@ -541,18 +371,6 @@ dependencies = [
"wasip3",
]
-[[package]]
-name = "gimli"
-version = "0.33.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c"
-dependencies = [
- "fnv",
- "hashbrown 0.16.1",
- "indexmap",
- "stable_deref_trait",
-]
-
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -1006,21 +824,6 @@ dependencies = [
"rustc-demangle",
]
-[[package]]
-name = "libwasm_cranelift"
-version = "0.1.0"
-dependencies = [
- "ak",
- "cbindgen",
- "cranelift-codegen",
- "cranelift-frontend",
- "cranelift-module",
- "cranelift-native",
- "libc",
- "regex",
- "target-lexicon",
-]
-
[[package]]
name = "libwasm_engine"
version = "0.1.0"
@@ -1242,20 +1045,6 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
-[[package]]
-name = "regalloc2"
-version = "0.15.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85"
-dependencies = [
- "allocator-api2",
- "bumpalo",
- "hashbrown 0.17.1",
- "log",
- "rustc-hash",
- "smallvec",
-]
-
[[package]]
name = "regex"
version = "1.12.3"
@@ -1468,12 +1257,6 @@ dependencies = [
"syn 2.0.117",
]
-[[package]]
-name = "target-lexicon"
-version = "0.13.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
-
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -1665,16 +1448,6 @@ dependencies = [
"semver",
]
-[[package]]
-name = "wasmtime-internal-core"
-version = "49.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ba00c5db77adb0749ee059068e5a417bfac3d8969f5a3479d9bd1ca8c1ba248d"
-dependencies = [
- "hashbrown 0.17.1",
- "libm",
-]
-
[[package]]
name = "windows-link"
version = "0.2.1"
diff --git a/Cargo.toml b/Cargo.toml
index e7685307569..174ee3dbace 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -15,7 +15,6 @@ members = [
"Libraries/LibUnicode/Rust",
"Libraries/LibURL/Rust",
"Libraries/LibWasm/Engine",
- "Libraries/LibWasm/Rust",
"Libraries/LibWeb/Bindings/Rust",
"Libraries/LibWeb/ContentBlocker/Rust",
"Libraries/LibWeb/Rust",
diff --git a/Documentation/CrashReports.md b/Documentation/CrashReports.md
index 47ebafe6c55..1e757ad0d69 100644
--- a/Documentation/CrashReports.md
+++ b/Documentation/CrashReports.md
@@ -1,8 +1,8 @@
# Crash reports
On macOS and Linux, Ladybird saves local text reports when the browser or a
-helper process crashes: WebContent, WebWorker, RequestServer, ImageDecoder,
-Compositor and WasmCompiler. Reports are stored in
+helper process crashes: WebContent, WebWorker, RequestServer, ImageDecoder
+and Compositor. Reports are stored in
`~/Library/Application Support/Ladybird/CrashReports/` on macOS and
`~/.local/share/Ladybird/CrashReports/` on Linux, or under
`$XDG_DATA_HOME/Ladybird/CrashReports/` if that variable is set.
diff --git a/Documentation/StatsLog.md b/Documentation/StatsLog.md
index 0470d2799db..2fd22cf41cd 100644
--- a/Documentation/StatsLog.md
+++ b/Documentation/StatsLog.md
@@ -24,7 +24,7 @@ Every record has these fields:
| --- | --- |
| `type` | `sample` or `event` |
| `time_ns` | Integer nanoseconds from `CLOCK_MONOTONIC`, shared across processes on a host |
-| `process` | `Ladybird`, `WebDriver`, `WebContent`, `WebWorker`, `RequestServer`, `Compositor`, `ImageDecoder`, `AudioServer`, `MediaServer`, `VideoDecoderServer`, or `WasmCompiler` |
+| `process` | `Ladybird`, `WebDriver`, `WebContent`, `WebWorker`, `RequestServer`, `Compositor`, `ImageDecoder`, `AudioServer`, `MediaServer`, or `VideoDecoderServer` |
| `pid` | Integer operating system process ID |
For example:
diff --git a/Libraries/CMakeLists.txt b/Libraries/CMakeLists.txt
index 86dc148058a..fcfc0578d64 100644
--- a/Libraries/CMakeLists.txt
+++ b/Libraries/CMakeLists.txt
@@ -37,9 +37,6 @@ if (ENABLE_GUI_TARGETS)
add_subdirectory(LibMediaCodecs)
add_subdirectory(LibMedia)
add_subdirectory(LibMediaClient)
- if (ENABLE_CRANELIFT_JIT)
- add_subdirectory(LibWasmCompilerClient)
- endif()
add_subdirectory(LibWebCommon)
add_subdirectory(LibCompositing)
add_subdirectory(LibWeb)
diff --git a/Libraries/LibHTTP/Cache/Utilities.cpp b/Libraries/LibHTTP/Cache/Utilities.cpp
index b697c7c1cba..bc3d5f9f687 100644
--- a/Libraries/LibHTTP/Cache/Utilities.cpp
+++ b/Libraries/LibHTTP/Cache/Utilities.cpp
@@ -210,8 +210,6 @@ static constexpr StringView cache_entry_associated_data_suffix(CacheEntryAssocia
switch (associated_data) {
case CacheEntryAssociatedData::JavaScriptBytecode:
return "jsbc"sv;
- case CacheEntryAssociatedData::WebAssemblyCompiledCode:
- return "wasmjit"sv;
}
VERIFY_NOT_REACHED();
}
diff --git a/Libraries/LibHTTP/Cache/Utilities.h b/Libraries/LibHTTP/Cache/Utilities.h
index 447bc7430f7..673b386f187 100644
--- a/Libraries/LibHTTP/Cache/Utilities.h
+++ b/Libraries/LibHTTP/Cache/Utilities.h
@@ -29,11 +29,9 @@ constexpr inline size_t MAXIMUM_CACHE_ENTRY_VARIANT_COUNT = 16;
enum class CacheEntryAssociatedData {
JavaScriptBytecode,
- WebAssemblyCompiledCode,
};
constexpr inline Array CACHE_ENTRY_ASSOCIATED_DATA_TYPES {
CacheEntryAssociatedData::JavaScriptBytecode,
- CacheEntryAssociatedData::WebAssemblyCompiledCode,
};
i64 compute_maximum_disk_cache_size(u64 free_bytes, u64 limit_maximum_disk_cache_size = DEFAULT_MAXIMUM_DISK_CACHE_SIZE);
diff --git a/Libraries/LibRequests/RequestClient.cpp b/Libraries/LibRequests/RequestClient.cpp
index 1512311e6da..d117eb55dbd 100644
--- a/Libraries/LibRequests/RequestClient.cpp
+++ b/Libraries/LibRequests/RequestClient.cpp
@@ -150,11 +150,6 @@ ErrorOr<Optional<Core::AnonymousBuffer>> RequestClient::retrieve_cache_associate
return IPCProxy::retrieve_cache_associated_data(network_isolation_key, url, method, headers, vary_key, associated_data);
}
-ErrorOr<bool> RequestClient::create_synthetic_cache_entry(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, URL::URL const& url, ByteString const& method)
-{
- return IPCProxy::create_synthetic_cache_entry(network_isolation_key, url, method);
-}
-
bool RequestClient::stop_request(Badge<Request>, Request& request)
{
auto stopped_request = m_requests.take(request.id());
diff --git a/Libraries/LibRequests/RequestClient.h b/Libraries/LibRequests/RequestClient.h
index 7fa9a7a52f4..3946c33fa58 100644
--- a/Libraries/LibRequests/RequestClient.h
+++ b/Libraries/LibRequests/RequestClient.h
@@ -71,8 +71,6 @@ public:
ErrorOr<Optional<Core::ImmutableBytes>> store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const&, URL::URL const&, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData, Core::AnonymousBuffer);
ErrorOr<Optional<Core::AnonymousBuffer>> retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const&, URL::URL const&, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData);
- ErrorOr<bool> create_synthetic_cache_entry(Optional<HTTP::NetworkIsolationKey> const&, URL::URL const&, ByteString const& method);
-
Function<void()> on_request_server_died;
private:
diff --git a/Libraries/LibSandbox/Sandbox.h b/Libraries/LibSandbox/Sandbox.h
index e6a517134e2..dfe4ac08c1c 100644
--- a/Libraries/LibSandbox/Sandbox.h
+++ b/Libraries/LibSandbox/Sandbox.h
@@ -57,7 +57,7 @@ enum class SystemService : u8 {
VideoDecoding = 1 << 2,
GPU = 1 << 3,
IOSurface = 1 << 4,
- // Mapping MAP_JIT memory, for WebAssembly code compiled by Cranelift.
+ // Mapping MAP_JIT memory, for the code that JIT compilers generate.
JIT = 1 << 5,
// Enumerating displays and following their refresh, which CoreGraphics and CoreVideo do through the window server.
Display = 1 << 6,
diff --git a/Libraries/LibWasm/AbstractMachine/AbstractMachine.cpp b/Libraries/LibWasm/AbstractMachine/AbstractMachine.cpp
deleted file mode 100644
index afdf1835212..00000000000
--- a/Libraries/LibWasm/AbstractMachine/AbstractMachine.cpp
+++ /dev/null
@@ -1,1289 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Checked.h>
-#include <AK/Enumerate.h>
-#include <AK/MutexProtected.h>
-#include <AK/NeverDestroyed.h>
-#include <AK/SaturatingMath.h>
-#include <LibGC/Heap.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
-#include <LibWasm/AbstractMachine/Configuration.h>
-#include <LibWasm/AbstractMachine/Interpreter.h>
-#include <LibWasm/AbstractMachine/Validator.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-AbstractMachine::AbstractMachine(GC::Heap* heap)
-{
- if (heap)
- adopt_heap(*heap);
-}
-
-AbstractMachine::~AbstractMachine() = default;
-
-static auto& module_stats()
-{
- static NeverDestroyed<MutexProtected<Vector<ModuleStats>>> stats;
- return *stats;
-}
-
-void record_module_stats(ModuleStats stats)
-{
- module_stats().with_locked([&](auto& v) {
- v.append(move(stats));
- });
-}
-
-void dump_module_stats()
-{
- module_stats().with_locked([&](auto& v) {
- if (v.is_empty()) {
- warnln("wasm-stats: no modules compiled yet");
- return;
- }
-
- warnln("wasm-stats: {} module(s) compiled", v.size());
- warnln("wasm-stats: hash input KiB parse ms validate ms cl ms cl blob KiB funcs tu fns tu pts cache");
-
- AK::Duration total_parse;
- AK::Duration total_validate;
- AK::Duration total_cranelift;
- size_t total_input = 0;
- size_t total_blob = 0;
- size_t total_hits = 0;
- size_t total_tier_up_functions = 0;
- size_t total_tier_up_checkpoints = 0;
-
- for (auto const& s : v) {
- StringBuilder hash_prefix;
- for (size_t i = 0; i < 4; ++i)
- hash_prefix.appendff("{:02x}", s.wasm_hash[i]);
-
- warnln("wasm-stats: {} {:>9} {:>8} {:>11} {:>5} {:>11} {:>5} {:>7} {:>7} {}",
- hash_prefix.to_byte_string(),
- s.input_size_bytes / 1024,
- s.parse_time.to_milliseconds(),
- s.validate_time.to_milliseconds(),
- s.cranelift_time.to_milliseconds(),
- s.cranelift_blob_size_bytes / 1024,
- s.function_count,
- s.tier_up_function_count,
- s.tier_up_checkpoint_count,
- s.cache_hit ? "HIT" : "miss");
-
- total_parse = total_parse + s.parse_time;
- total_validate = total_validate + s.validate_time;
- total_cranelift = total_cranelift + s.cranelift_time;
- total_input += s.input_size_bytes;
- total_blob += s.cranelift_blob_size_bytes;
- total_tier_up_functions += s.tier_up_function_count;
- total_tier_up_checkpoints += s.tier_up_checkpoint_count;
- if (s.cache_hit)
- ++total_hits;
- }
-
- warnln("wasm-stats: ---- {:>9} {:>8} {:>11} {:>5} {:>11} {:>5} {:>7} {:>7} hits={}",
- total_input / 1024,
- total_parse.to_milliseconds(),
- total_validate.to_milliseconds(),
- total_cranelift.to_milliseconds(),
- total_blob / 1024,
- ""sv,
- total_tier_up_functions,
- total_tier_up_checkpoints,
- total_hits);
- });
-}
-
-GC_DEFINE_ALLOCATOR(StructInstance);
-GC_DEFINE_ALLOCATOR(ArrayInstance);
-
-void StructInstance::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto& field : m_fields) {
- if (auto* cell = field.gc_cell())
- visitor.visit(cell);
- }
-}
-
-void ArrayInstance::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto& element : m_elements) {
- if (auto* cell = element.gc_cell())
- visitor.visit(cell);
- }
-}
-
-void AbstractMachine::adopt_heap(GC::Heap& heap)
-{
- VERIFY(!m_heap);
- m_heap = &heap;
- m_store.set_heap(heap);
- m_roots_provider = make<RootsProvider>(heap, m_store);
-}
-
-void AbstractMachine::create_own_heap()
-{
- m_owned_heap = make<GC::Heap>([](auto&) { }, GC::Heap::BecomeProcessDefault::No);
- adopt_heap(*m_owned_heap);
-}
-
-void AbstractMachine::RootsProvider::for_each_conservative_range(AK::Function<void(ReadonlySpan<FlatPtr>)> const& callback) const
-{
- static_assert(sizeof(Value) % sizeof(FlatPtr) == 0);
- auto report_values = [&](Value const* data, size_t count) {
- if (count == 0)
- return;
- callback({ reinterpret_cast<FlatPtr const*>(data), count * (sizeof(Value) / sizeof(FlatPtr)) });
- };
- auto report_references = [&](ReadonlySpan<Reference> references) {
- if (references.is_empty())
- return;
- callback({ reinterpret_cast<FlatPtr const*>(references.data()), references.size() * (sizeof(Reference) / sizeof(FlatPtr)) });
- };
-
- for (auto* configuration : m_store.active_configurations()) {
- report_values(configuration->value_stack().data(), configuration->value_stack().conservative_scan_size());
- report_values(configuration->regs.data(), configuration->regs.size());
- report_values(configuration->m_call_record_stack.data(), configuration->m_call_record_stack.conservative_scan_size());
- for (auto& arguments : configuration->m_call_argument_freelist)
- report_values(arguments.data(), arguments.capacity());
- for (auto& owned_locals : configuration->m_owned_locals_stack)
- report_values(owned_locals.data(), owned_locals.size());
- }
-
- for (auto& table : m_store.tables())
- report_references(table.elements().span());
- for (auto& element : m_store.elements())
- report_references(element.references().span());
- for (auto& global : m_store.globals())
- report_values(&global->value(), 1);
- for (auto& exception : m_store.exceptions())
- report_values(exception.params().data(), exception.params().size());
-}
-
-MemoryBuffer::~MemoryBuffer()
-{
- clear();
-}
-
-MemoryBuffer::MemoryBuffer(MemoryBuffer&& other)
- : m_size(exchange(other.m_size, 0))
- , m_reserved_capacity(exchange(other.m_reserved_capacity, 0))
- , m_handle(exchange(other.m_handle, {}))
- , m_storage_offset(exchange(other.m_storage_offset, GC::PrimitiveStorage::invalid_offset))
-{
-}
-
-MemoryBuffer& MemoryBuffer::operator=(MemoryBuffer&& other)
-{
- if (this != &other) {
- clear();
- m_size = exchange(other.m_size, 0);
- m_reserved_capacity = exchange(other.m_reserved_capacity, 0);
- m_handle = exchange(other.m_handle, {});
- m_storage_offset = exchange(other.m_storage_offset, GC::PrimitiveStorage::invalid_offset);
- }
- return *this;
-}
-
-void MemoryBuffer::clear()
-{
- if (m_handle.is_valid())
- GC::PrimitiveStorage::the().free(m_handle);
- m_reserved_capacity = 0;
- m_size = 0;
- m_handle = {};
- m_storage_offset = GC::PrimitiveStorage::invalid_offset;
-}
-
-void MemoryBuffer::update_storage_offset()
-{
- m_storage_offset = GC::PrimitiveStorage::the().offset(m_handle);
-}
-
-ErrorOr<void> MemoryBuffer::try_reserve(size_t capacity, size_t guard_size)
-{
- if (m_handle.is_valid()) {
- if (capacity <= m_reserved_capacity)
- return {};
- TRY(GC::PrimitiveStorage::the().try_reserve(m_handle, capacity));
- m_reserved_capacity = GC::PrimitiveStorage::the().capacity(m_handle);
- update_storage_offset();
- return {};
- }
-
- m_handle = TRY(GC::PrimitiveStorage::the().try_reserve(0, capacity, GC::PrimitiveStorage::ZeroFillNewBytes::Yes, guard_size));
- m_reserved_capacity = capacity;
- update_storage_offset();
- return {};
-}
-
-ErrorOr<void> MemoryBuffer::try_resize(size_t new_size)
-{
- VERIFY(new_size >= m_size);
- if (m_handle.is_valid()) {
- TRY(GC::PrimitiveStorage::the().try_resize(m_handle, new_size, GC::PrimitiveStorage::ZeroFillNewBytes::Yes));
- m_reserved_capacity = GC::PrimitiveStorage::the().capacity(m_handle);
- m_size = new_size;
- update_storage_offset();
- return {};
- }
-
- if (new_size == 0)
- return {};
-
- auto capacity = max(new_size, m_reserved_capacity);
- m_handle = TRY(GC::PrimitiveStorage::the().try_reserve(new_size, capacity, GC::PrimitiveStorage::ZeroFillNewBytes::Yes));
- m_reserved_capacity = capacity;
- m_size = new_size;
- update_storage_offset();
- return {};
-}
-
-ErrorOr<void> MemoryBuffer::try_resize(size_t new_size, size_t reserved_capacity)
-{
- VERIFY(new_size >= m_size);
- VERIFY(new_size <= reserved_capacity);
- if (m_handle.is_valid()) {
- TRY(GC::PrimitiveStorage::the().try_resize_and_reserve(m_handle, new_size, reserved_capacity, GC::PrimitiveStorage::ZeroFillNewBytes::Yes));
- m_reserved_capacity = GC::PrimitiveStorage::the().capacity(m_handle);
- m_size = new_size;
- update_storage_offset();
- return {};
- }
-
- if (reserved_capacity == 0)
- return {};
-
- m_handle = TRY(GC::PrimitiveStorage::the().try_reserve(new_size, reserved_capacity, GC::PrimitiveStorage::ZeroFillNewBytes::Yes));
- m_reserved_capacity = reserved_capacity;
- m_size = new_size;
- update_storage_offset();
- return {};
-}
-
-size_t MemoryBuffer::contiguous_bytes_from(size_t offset, size_t count) const
-{
- if (count == 0 || m_storage_offset == GC::PrimitiveStorage::invalid_offset)
- return count;
- auto caged_offset = GC::PrimitiveStorage::mask_offset(m_storage_offset + offset);
- return min(count, GC::PrimitiveStorage::default_cage_size - caged_offset);
-}
-
-size_t MemoryBuffer::contiguous_bytes_before(size_t offset, size_t count) const
-{
- if (count == 0 || m_storage_offset == GC::PrimitiveStorage::invalid_offset)
- return count;
- VERIFY(offset > 0);
- auto caged_offset = GC::PrimitiveStorage::mask_offset(m_storage_offset + offset - 1);
- return min(count, caged_offset + 1);
-}
-
-void MemoryBuffer::copy_to(size_t offset, Bytes destination) const
-{
- VERIFY(offset <= size());
- VERIFY(destination.size() <= size() - offset);
-
- size_t copied = 0;
- while (copied < destination.size()) {
- auto chunk_size = contiguous_bytes_from(offset + copied, destination.size() - copied);
- __builtin_memcpy(destination.data() + copied, offset_pointer(offset + copied), chunk_size);
- copied += chunk_size;
- }
-}
-
-void MemoryBuffer::copy_from(MemoryBuffer const& source, size_t source_offset, size_t destination_offset, size_t count)
-{
- VERIFY(source_offset <= source.size());
- VERIFY(count <= source.size() - source_offset);
- VERIFY(destination_offset <= size());
- VERIFY(count <= size() - destination_offset);
-
- if (&source == this) {
- move_data(destination_offset, source_offset, count);
- return;
- }
-
- size_t copied = 0;
- while (copied < count) {
- auto source_chunk_size = source.contiguous_bytes_from(source_offset + copied, count - copied);
- auto destination_chunk_size = contiguous_bytes_from(destination_offset + copied, count - copied);
- auto chunk_size = min(source_chunk_size, destination_chunk_size);
- __builtin_memcpy(offset_pointer(destination_offset + copied), source.offset_pointer(source_offset + copied), chunk_size);
- copied += chunk_size;
- }
-}
-
-void MemoryBuffer::fill(size_t offset, u8 value, size_t count)
-{
- VERIFY(offset <= size());
- VERIFY(count <= size() - offset);
-
- size_t filled = 0;
- while (filled < count) {
- auto chunk_size = contiguous_bytes_from(offset + filled, count - filled);
- __builtin_memset(offset_pointer(offset + filled), value, chunk_size);
- filled += chunk_size;
- }
-}
-
-void MemoryBuffer::overwrite(size_t offset, void const* source, size_t count)
-{
- VERIFY(offset <= size());
- VERIFY(count <= size() - offset);
-
- auto const* source_bytes = static_cast<u8 const*>(source);
- size_t copied = 0;
- while (copied < count) {
- auto chunk_size = contiguous_bytes_from(offset + copied, count - copied);
- __builtin_memcpy(offset_pointer(offset + copied), source_bytes + copied, chunk_size);
- copied += chunk_size;
- }
-}
-
-void MemoryBuffer::move_data(size_t destination_offset, size_t source_offset, size_t count)
-{
- VERIFY(destination_offset <= size());
- VERIFY(count <= size() - destination_offset);
- VERIFY(source_offset <= size());
- VERIFY(count <= size() - source_offset);
-
- if (count == 0 || destination_offset == source_offset)
- return;
-
- if (source_offset < destination_offset && destination_offset < source_offset + count) {
- size_t remaining = count;
- while (remaining > 0) {
- auto source_chunk_size = contiguous_bytes_before(source_offset + remaining, remaining);
- auto destination_chunk_size = contiguous_bytes_before(destination_offset + remaining, remaining);
- auto chunk_size = min(source_chunk_size, destination_chunk_size);
- remaining -= chunk_size;
- __builtin_memmove(offset_pointer(destination_offset + remaining), offset_pointer(source_offset + remaining), chunk_size);
- }
- return;
- }
-
- size_t copied = 0;
- while (copied < count) {
- auto source_chunk_size = contiguous_bytes_from(source_offset + copied, count - copied);
- auto destination_chunk_size = contiguous_bytes_from(destination_offset + copied, count - copied);
- auto chunk_size = min(source_chunk_size, destination_chunk_size);
- __builtin_memmove(offset_pointer(destination_offset + copied), offset_pointer(source_offset + copied), chunk_size);
- copied += chunk_size;
- }
-}
-
-bool MemoryBuffer::contains_virtual_address(void const* address) const
-{
- if (!m_handle.is_valid())
- return false;
- return GC::PrimitiveStorage::the().contains(m_handle, address);
-}
-
-static ErrorOr<size_t> size_from_page_count(u64 pages)
-{
- Checked<size_t> size { pages };
- size *= Constants::page_size;
- if (size.has_overflow())
- return Error::from_errno(ENOMEM);
- return size.value();
-}
-
-static ErrorOr<size_t> maximum_memory_size(MemoryType const& type)
-{
- auto supported_max_pages = type.limits().address_type() == AddressType::I32 ? Constants::wasm32_max_pages : Constants::wasm64_max_pages;
- auto max_pages = min(type.limits().max().value_or(supported_max_pages), supported_max_pages);
- return size_from_page_count(max_pages);
-}
-
-static ErrorOr<size_t> initial_memory_reservation_size(MemoryType const& type)
-{
- auto maximum_size = TRY(maximum_memory_size(type));
- auto initial_size = TRY(size_from_page_count(type.limits().min()));
- if (initial_size > maximum_size)
- return Error::from_errno(ENOMEM);
-
- // memory32 storage must never move: compiled code caches its base address for unchecked
- // accesses, so the backing allocation has to be able to grow to the maximum in place.
- if (type.limits().address_type() == AddressType::I32)
- return maximum_size;
-
- if (type.limits().max().has_value())
- return maximum_size;
-
- return initial_size;
-}
-
-static size_t grown_memory_reservation_size(size_t current_capacity, size_t required_size, size_t maximum_size)
-{
- auto new_capacity = max(current_capacity, static_cast<size_t>(Constants::default_memory_reservation_size));
- while (new_capacity < required_size) {
- if (new_capacity > maximum_size / 2) {
- new_capacity = maximum_size;
- break;
- }
- new_capacity *= 2;
- }
- return min(max(new_capacity, required_size), maximum_size);
-}
-
-ErrorOr<MemoryInstance> MemoryInstance::create(MemoryType const& type)
-{
- MemoryInstance instance { type };
-
- auto reserved_capacity = TRY(initial_memory_reservation_size(type));
- size_t guard_size = 0;
- if (type.limits().address_type() == AddressType::I32)
- guard_size = Constants::wasm32_guarded_reservation_size - reserved_capacity;
- TRY(instance.m_data.try_reserve(reserved_capacity, guard_size));
-
- auto initial_size = TRY(size_from_page_count(type.limits().min()));
- if (!instance.grow(initial_size, GrowType::No))
- return Error::from_string_literal("Failed to grow to requested size");
-
- return { move(instance) };
-}
-
-MemoryInstance::MemoryInstance(MemoryType const& type)
- : m_type(type)
-{
-}
-
-bool MemoryInstance::grow(size_t size_to_grow, GrowType grow_type, InhibitGrowCallback inhibit_callback)
-{
- if (size_to_grow == 0)
- return true;
-
- auto maximum_size = maximum_memory_size(m_type);
- if (maximum_size.is_error())
- return false;
-
- Checked<size_t> new_size { m_data.size() };
- new_size += size_to_grow;
- if (new_size.has_overflow() || new_size.value() > maximum_size.value())
- return false;
-
- auto new_capacity = m_data.capacity();
- if (new_size.value() > new_capacity)
- new_capacity = m_type.limits().max().has_value()
- ? maximum_size.value()
- : grown_memory_reservation_size(new_capacity, new_size.value(), maximum_size.value());
-
- if (m_data.try_resize(new_size.value(), new_capacity).is_error())
- return false;
- if (inhibit_callback == InhibitGrowCallback::No && successful_grow_hook)
- successful_grow_hook();
-
- if (grow_type == GrowType::Yes)
- m_type = MemoryType { Limits(m_type.limits().address_type(), m_type.limits().min() + size_to_grow / Constants::page_size, m_type.limits().max()) };
-
- return true;
-}
-
-MemoryInstanceTable ModuleInstance::resolved_memories(Store& store) const
-{
- if (m_resolved_memories_built)
- return m_resolved_memories.data();
-
- m_resolved_memories.ensure_capacity(m_memories.size());
- for (auto address : m_memories)
- m_resolved_memories.unchecked_append(store.unsafe_get(address));
- m_resolved_memories_built = true;
- return m_resolved_memories.data();
-}
-
-GlobalInstanceTable ModuleInstance::resolved_globals(Store& store) const
-{
- if (m_resolved_globals_built)
- return m_resolved_globals.data();
-
- m_resolved_globals.ensure_capacity(m_globals.size());
- for (auto address : m_globals)
- m_resolved_globals.unchecked_append(store.unsafe_get(address));
- m_resolved_globals_built = true;
- return m_resolved_globals.data();
-}
-
-Vector<CompiledFunctionEntry> const& ModuleInstance::compiled_fn_table(Store& store) const
-{
- if (m_compiled_fn_table_built)
- return m_compiled_fn_table;
-
- auto count = m_functions.size();
- if (count == 0) {
- m_compiled_fn_table_built = true;
- return m_compiled_fn_table;
- }
-
- m_compiled_fn_table.resize_with_default_value_and_keep_capacity(count, {});
- auto* entries = m_compiled_fn_table.data();
-
- // Since we asynchronously compile the code to native, we'll need to rebuild this table incrementally until all functions have been compiled.
- bool all_ready = true;
- for (size_t i = 0; i < count; i++) {
- auto* instance = store.unsafe_get(m_functions[i]);
- auto* wasm_fn = instance->get_pointer<WasmFunction>();
- if (!wasm_fn)
- continue;
- if (auto src = wasm_fn->module_ref(); src && !src->has_attempted_cranelift_compilation())
- all_ready = false;
- auto& ci = wasm_fn->code().func().body().compiled_instructions;
- auto native = cranelift_entry_acquire(ci);
- if (native == 0)
- continue;
-
- auto& entry = entries[i];
- entry.handler_ptr = native;
- entry.dispatches_ptr = bit_cast<FlatPtr>(ci.dispatches.data());
- entry.src_dst_ptr = bit_cast<FlatPtr>(ci.src_dst_mappings.data());
- entry.first_insn = ci.dispatches[0].instruction;
- entry.expression = &wasm_fn->code().func().body();
- entry.module = &wasm_fn->module();
- entry.total_local_count = static_cast<u32>(wasm_fn->code().func().total_local_count()) + ci.cranelift_inlined_locals;
- entry.arity = static_cast<u32>(wasm_fn->type().results().size());
- entry.max_call_rec_size = static_cast<u32>(ci.max_call_rec_size);
- }
- m_compiled_fn_table_built = all_ready;
- return m_compiled_fn_table;
-}
-
-Optional<FunctionAddress> Store::allocate(ModuleInstance& instance, Module const& module, CodeSection::Code const& code, TypeIndex type_index)
-{
- FunctionAddress address { m_functions.size() };
- if (type_index.value() >= instance.types().size())
- return {};
-
- auto& type = instance.types()[type_index.value()].function();
- auto const* defined_type = instance.canonical_types()[type_index.value()];
- m_functions.empend(WasmFunction { type, defined_type, instance, module, code });
- return address;
-}
-
-Optional<FunctionAddress> Store::allocate(HostFunction&& function)
-{
- FunctionAddress address { m_functions.size() };
- if (!function.defined_type())
- function.set_defined_type(canonicalize_type(TypeSection::Type { FunctionType { function.type() } }, TypeContext {}));
- m_functions.empend(HostFunction { move(function) });
- return address;
-}
-
-Optional<TableAddress> Store::allocate(TableType const& type)
-{
- if (type.limits().min() > Constants::max_allowed_table_size)
- return {};
-
- TableAddress address { m_tables.size() };
- Vector<Reference> elements;
- elements.ensure_capacity(type.limits().min());
- for (size_t i = 0; i < type.limits().min(); i++)
- elements.append(Wasm::Reference { Wasm::Reference::Null { type.element_type() } });
- elements.resize(type.limits().min());
- m_tables.empend(TableInstance { type, move(elements) });
- return address;
-}
-
-Optional<MemoryAddress> Store::allocate(MemoryType const& type)
-{
- MemoryAddress address { m_memories.size() };
- auto instance = MemoryInstance::create(type);
- if (instance.is_error() && m_heap) {
- m_heap->collect_garbage();
- instance = MemoryInstance::create(type);
- }
- if (instance.is_error())
- return {};
-
- m_memories.append(make<MemoryInstance>(instance.release_value()));
- return address;
-}
-
-Optional<GlobalAddress> Store::allocate(GlobalType const& type, Value value)
-{
- GlobalAddress address { m_globals.size() };
- m_globals.append(make<GlobalInstance>(value, type.is_mutable(), type.type()));
- return address;
-}
-
-Optional<DataAddress> Store::allocate_data(Vector<u8> initializer)
-{
- DataAddress address { m_datas.size() };
- m_datas.append(DataInstance { move(initializer) });
- return address;
-}
-
-Optional<ElementAddress> Store::allocate(ValueType const& type, Vector<Reference> references)
-{
- ElementAddress address { m_elements.size() };
- m_elements.append(ElementInstance { type, move(references) });
- return address;
-}
-
-Optional<TagAddress> Store::allocate(FunctionType const& type, DefinedType const* defined_type, TagType::Flags flags)
-{
- TagAddress address { m_tags.size() };
- m_tags.append({ type, defined_type, flags });
- return address;
-}
-
-Optional<ExceptionAddress> Store::allocate(TagAddress tag_address, Vector<Value> params)
-{
- ExceptionAddress address { m_exceptions.size() };
- m_exceptions.append(ExceptionInstance { tag_address, move(params) });
- return address;
-}
-
-FunctionInstance* Store::get(FunctionAddress address)
-{
- auto value = address.value();
- if (m_functions.size() <= value)
- return nullptr;
- auto& instance = m_functions[value];
- if (auto const* wasm = instance.get_pointer<WasmFunction>()) {
- if (!wasm->try_module())
- return nullptr;
- }
- return &instance;
-}
-
-Module const* Store::get_module_for(Wasm::FunctionAddress address)
-{
- auto* function = get(address);
- if (!function || function->has<HostFunction>())
- return nullptr;
- return function->get<WasmFunction>().module_ref().ptr();
-}
-
-RefPtr<ModuleInstance const> Store::get_module_instance_for(FunctionAddress address)
-{
- auto* function = get(address);
- if (!function || function->has<HostFunction>())
- return nullptr;
- return function->get<WasmFunction>().try_module();
-}
-
-TableInstance* Store::get(TableAddress address)
-{
- auto value = address.value();
- if (m_tables.size() <= value)
- return nullptr;
- return &m_tables[value];
-}
-
-MemoryInstance* Store::get(MemoryAddress address)
-{
- auto value = address.value();
- if (m_memories.size() <= value)
- return nullptr;
- return m_memories[value].ptr();
-}
-
-GlobalInstance* Store::get(GlobalAddress address)
-{
- auto value = address.value();
- if (m_globals.size() <= value)
- return nullptr;
- return m_globals[value].ptr();
-}
-
-ElementInstance* Store::get(ElementAddress address)
-{
- auto value = address.value();
- if (m_elements.size() <= value)
- return nullptr;
- return &m_elements[value];
-}
-
-DataInstance* Store::get(DataAddress address)
-{
- auto value = address.value();
- if (m_datas.size() <= value)
- return nullptr;
- return &m_datas[value];
-}
-
-TagInstance* Store::get(TagAddress address)
-{
- auto value = address.value();
- if (m_tags.size() <= value)
- return nullptr;
- return &m_tags[value];
-}
-
-ExceptionInstance* Store::get(ExceptionAddress address)
-{
- auto value = address.value();
- if (m_exceptions.size() <= value)
- return nullptr;
- return &m_exceptions[value];
-}
-
-ErrorOr<void, ValidationError> AbstractMachine::validate(Module& module, Optional<CompileCacheConfig> cache_config, CompileToNative compile_to_native)
-{
- if (module.validation_status() != Module::ValidationStatus::Unchecked) {
- if (module.validation_status() == Module::ValidationStatus::Valid)
- return {};
-
- return ValidationError { module.validation_error() };
- }
-
- Validator validator;
- auto result = validator.validate(module);
- if (result.is_error()) {
- module.set_validation_error(result.error().error_string);
- return result.release_error();
- }
-
- if (compile_to_native == CompileToNative::Yes && module.try_begin_cranelift_compilation()) {
- if (cache_config.has_value())
- module.set_cranelift_cache_config(cache_config.release_value());
- compile_module_to_native(module);
- module.finish_cranelift_compilation();
- }
-
- return {};
-}
-InstantiationResult AbstractMachine::instantiate(Module const& module, Vector<ExternValue> externs)
-{
- // FIXME: Only create a heap if we actually have GC used in the module.
- heap();
-
- if (auto result = validate(const_cast<Module&>(module)); result.is_error())
- return InstantiationError { ByteString::formatted("Validation failed: {}", result.error()) };
-
- auto main_module_instance_pointer = adopt_ref(*new ModuleInstance);
- main_module_instance_pointer->cached_minimum_call_record_allocation_size = module.minimum_call_record_allocation_size();
- auto& main_module_instance = *main_module_instance_pointer;
-
- main_module_instance.types() = module.type_section().types();
- main_module_instance.canonical_types() = module.canonical_types();
-
- Vector<Value> global_values;
- Vector<Vector<Reference>> elements;
- auto auxiliary_instance_ptr = adopt_ref(*new ModuleInstance);
- auto& auxiliary_instance = *auxiliary_instance_ptr;
-
- auxiliary_instance.cached_minimum_call_record_allocation_size = module.minimum_call_record_allocation_size();
- auxiliary_instance.types() = module.type_section().types();
- auxiliary_instance.canonical_types() = module.canonical_types();
-
- // https://webassembly.github.io/spec/core/exec/modules.html#instantiation
- // https://webassembly.github.io/spec/core/valid/matching.html#external-types
- TypeContext const import_type_context { module.canonical_types().span() };
- for (auto [i, import_] : enumerate(module.import_section().imports())) {
- auto extern_ = externs.at(i);
- auto invalid = import_.description().visit(
- [&](MemoryType const& mem_type) -> Optional<ByteString> {
- if (!extern_.has<MemoryAddress>())
- return "Expected memory import"sv;
- auto other_mem_type = m_store.get(extern_.get<MemoryAddress>())->type();
- if (matches_memory_type(other_mem_type, mem_type))
- return {};
- return ByteString::formatted("Memory import and extern do not match: {}-{} vs {}-{}", mem_type.limits().min(), mem_type.limits().max(), other_mem_type.limits().min(), other_mem_type.limits().max());
- },
- [&](TableType const& table_type) -> Optional<ByteString> {
- if (!extern_.has<TableAddress>())
- return "Expected table import"sv;
- auto other_table_type = m_store.get(extern_.get<TableAddress>())->type();
- if (matches_table_type(other_table_type, table_type, TypeContext {}, import_type_context))
- return {};
-
- return ByteString::formatted("Table import and extern do not match: {}-{} vs {}-{}", table_type.limits().min(), table_type.limits().max(), other_table_type.limits().min(), other_table_type.limits().max());
- },
- [&](GlobalType const& global_type) -> Optional<ByteString> {
- if (!extern_.has<GlobalAddress>())
- return "Expected global import"sv;
- auto other_global_type = m_store.get(extern_.get<GlobalAddress>())->type();
- if (matches_global_type(other_global_type, global_type, TypeContext {}, import_type_context))
- return {};
- return "Global import and extern do not match"sv;
- },
- [&](FunctionType const& type) -> Optional<ByteString> {
- if (!extern_.has<FunctionAddress>())
- return "Expected function import"sv;
- auto other_type = m_store.get(extern_.get<FunctionAddress>())->visit([&](WasmFunction const& wasm_func) { return wasm_func.type(); }, [&](HostFunction const& host_func) { return host_func.type(); });
- if (type.results() != other_type.results())
- return ByteString::formatted("Function import and extern do not match, results: {} vs {}", type.results(), other_type.results());
- if (type.parameters() != other_type.parameters())
- return ByteString::formatted("Function import and extern do not match, parameters: {} vs {}", type.parameters(), other_type.parameters());
- return {};
- },
- [&](TagType const& type) -> Optional<ByteString> {
- if (!extern_.has<TagAddress>())
- return "Expected tag import"sv;
- auto other_tag_instance = m_store.get(extern_.get<TagAddress>());
- if (other_tag_instance->flags() != type.flags())
- return "Tag import and extern do not match"sv;
-
- auto const* defined_type = module.canonical_types()[type.type().value()];
- if (other_tag_instance->defined_type() && defined_type) {
- if (!matches_tag_type(*other_tag_instance->defined_type(), *defined_type))
- return "Tag import and extern do not match"sv;
- return {};
- }
-
- auto& this_type = module.type_section().types()[type.type().value()];
- if (other_tag_instance->type().parameters() != this_type.function().parameters())
- return "Tag import and extern do not match"sv;
- return {};
- },
- [&](TypeIndex type_index) -> Optional<ByteString> {
- if (!extern_.has<FunctionAddress>())
- return "Expected function import"sv;
- auto const* other_defined_type = m_store.get(extern_.get<FunctionAddress>())->visit([&](WasmFunction const& wasm_func) { return wasm_func.defined_type(); }, [&](HostFunction const& host_func) { return host_func.defined_type(); });
- auto const* defined_type = module.canonical_types()[type_index.value()];
- VERIFY(other_defined_type && defined_type);
- if (!matches_defined_type(*other_defined_type, *defined_type))
- return ByteString::formatted("Function import and extern do not match: {} vs {}", module.type_section().types()[type_index.value()].name(), other_defined_type->sub_type().name());
- return {};
- });
- if (invalid.has_value())
- return InstantiationError { ByteString::formatted("{}::{}: {}", import_.module(), import_.name(), invalid.release_value()) };
- }
-
- for (auto& entry : externs) {
- if (auto* ptr = entry.get_pointer<GlobalAddress>())
- auxiliary_instance.globals().append(*ptr);
- else if (auto* ptr = entry.get_pointer<FunctionAddress>())
- auxiliary_instance.functions().append(*ptr);
- }
-
- Vector<FunctionAddress> module_functions;
- module_functions.ensure_capacity(module.function_section().types().size());
-
- size_t i = 0;
- for (auto& code : module.code_section().functions()) {
- auto type_index = module.function_section().types()[i];
- auto address = m_store.allocate(main_module_instance, module, code, type_index);
- VERIFY(address.has_value());
- auxiliary_instance.functions().append(*address);
- module_functions.append(*address);
- ++i;
- }
-
- BytecodeInterpreter interpreter(m_stack_info);
- auto handle = register_scoped(interpreter);
-
- for (auto& entry : module.global_section().entries()) {
- Configuration config { m_store };
- if (m_should_limit_instruction_count)
- config.enable_instruction_count_limit();
- config.set_frame(IsTailcall::No,
- auxiliary_instance,
- Vector<Value, ArgumentsStaticSize> {},
- entry.expression(),
- 1uz);
- auto result = config.execute(interpreter);
- if (result.is_trap())
- return InstantiationError { "Global instantiation trapped", move(result.trap()) };
- global_values.append(result.values().first());
- auto addr = m_store.allocate(entry.type(), result.values().first()).release_value();
- auxiliary_instance.globals().append(addr);
- }
-
- Vector<Value> table_initial_values;
- for (auto& table : module.table_section().tables()) {
- Configuration config { m_store };
- if (m_should_limit_instruction_count)
- config.enable_instruction_count_limit();
- config.set_frame(IsTailcall::No,
- auxiliary_instance,
- Vector<Value, ArgumentsStaticSize> {},
- table.initializer(),
- 1uz);
- auto result = config.execute(interpreter);
- if (result.is_trap())
- return InstantiationError { "Table initializer trapped", move(result.trap()) };
- table_initial_values.append(result.values().first());
- }
-
- if (auto result = allocate_all_initial_phase(module, main_module_instance, externs, global_values, table_initial_values, module_functions); result.has_value())
- return result.release_value();
-
- for (auto& segment : module.element_section().segments()) {
- Vector<Reference> references;
- for (auto& entry : segment.init) {
- Configuration config { m_store };
- if (m_should_limit_instruction_count)
- config.enable_instruction_count_limit();
- // https://webassembly.github.io/spec/core/exec/modules.html#instantiation
- config.set_frame(IsTailcall::No,
- main_module_instance,
- Vector<Value, ArgumentsStaticSize> {},
- entry,
- 1uz);
- auto result = config.execute(interpreter);
- if (result.is_trap())
- return InstantiationError { "Element section initialisation trapped", move(result.trap()) };
-
- for (auto& value : result.values()) {
- auto reference = value.to<Reference>();
- references.append(reference);
- }
- }
- elements.append(move(references));
- }
-
- if (auto result = allocate_all_final_phase(module, main_module_instance, elements); result.has_value())
- return result.release_value();
-
- size_t index = 0;
- for (auto& segment : module.element_section().segments()) {
- auto current_index = index;
- ++index;
- if (current_index >= main_module_instance.elements().size())
- return InstantiationError { "Invalid element referenced by active element segment" };
- auto active_ptr = segment.mode.get_pointer<ElementSection::Active>();
- auto elem_instance = m_store.get(main_module_instance.elements()[current_index]);
- if (!active_ptr) {
- if (segment.mode.has<ElementSection::Declarative>())
- *elem_instance = ElementInstance(elem_instance->type(), {});
- continue;
- }
- if (active_ptr->index.value() >= main_module_instance.tables().size())
- return InstantiationError { "Invalid table referenced by active element segment" };
- Configuration config { m_store };
- if (m_should_limit_instruction_count)
- config.enable_instruction_count_limit();
- config.set_frame(IsTailcall::No,
- main_module_instance,
- Vector<Value, ArgumentsStaticSize> {},
- active_ptr->expression,
- 1uz);
- auto result = config.execute(interpreter);
- if (result.is_trap())
- return InstantiationError { "Element section initialisation trapped", move(result.trap()) };
- auto table_instance = m_store.get(main_module_instance.tables()[active_ptr->index.value()]);
- if (!table_instance || !elem_instance)
- return InstantiationError { "Invalid element referenced by active element segment" };
-
- auto d = result.values().first().to<u64>();
- if (table_instance->type().limits().address_type() == AddressType::I32)
- d = static_cast<u32>(d);
-
- auto total_size = saturating_add<u64>(elem_instance->references().size(), d);
-
- if (total_size > table_instance->elements().size())
- return InstantiationError { "Table instantiation out of bounds" };
-
- size_t i = 0;
- for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it) {
- RefPtr<ModuleInstance const> anchor;
- if (auto const* func = it->ref().template get_pointer<Reference::Func>())
- anchor = m_store.get_module_instance_for(func->address);
- table_instance->set_element(i + d, *it, move(anchor));
- }
- // Drop element
- *m_store.get(main_module_instance.elements()[current_index]) = ElementInstance(elem_instance->type(), {});
- }
-
- for (auto& segment : module.data_section().data()) {
- Optional<InstantiationError> result = segment.value().visit(
- [&](DataSection::Data::Active const& data) -> Optional<InstantiationError> {
- Configuration config { m_store };
- if (m_should_limit_instruction_count)
- config.enable_instruction_count_limit();
- config.set_frame(IsTailcall::No,
- main_module_instance,
- Vector<Value, ArgumentsStaticSize> {},
- data.offset,
- 1uz);
- auto result = config.execute(interpreter);
- if (result.is_trap())
- return InstantiationError { "Data section initialisation trapped", move(result.trap()) };
- if (main_module_instance.memories().size() <= data.index.value()) {
- return InstantiationError {
- ByteString::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries",
- data.index.value(), main_module_instance.memories().size())
- };
- }
- auto maybe_data_address = m_store.allocate_data(data.init);
- if (!maybe_data_address.has_value()) {
- return InstantiationError { "Failed to allocate a data instance for an active data segment"sv };
- }
- main_module_instance.datas().append(*maybe_data_address);
-
- auto address = main_module_instance.memories()[data.index.value()];
- auto instance = m_store.get(address);
- u64 offset = result.values().first().to<u64>();
- if (instance->type().limits().address_type() == AddressType::I32)
- offset = static_cast<u32>(offset);
- Checked<size_t> checked_offset = data.init.size();
- checked_offset += offset;
- if (checked_offset.has_overflow() || checked_offset > instance->size()) {
- return InstantiationError {
- ByteString::formatted("Data segment attempted to write to out-of-bounds memory ({}) in memory of size {}",
- offset, instance->size())
- };
- }
- if (!data.init.is_empty())
- instance->data().overwrite(offset, data.init.data(), data.init.size());
- return {};
- },
- [&](DataSection::Data::Passive const& passive) -> Optional<InstantiationError> {
- auto maybe_data_address = m_store.allocate_data(passive.init);
- if (!maybe_data_address.has_value()) {
- return InstantiationError { "Failed to allocate a data instance for a passive data segment"sv };
- }
- main_module_instance.datas().append(*maybe_data_address);
- return {};
- });
- if (result.has_value())
- return result.release_value();
- }
-
- if (module.start_section().function().has_value()) {
- auto& functions = main_module_instance.functions();
- auto index = module.start_section().function()->index();
- if (functions.size() <= index.value())
- return InstantiationError { ByteString::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
- auto result = invoke(functions[index.value()], {});
- if (result.is_trap())
- return InstantiationError { "Start function trapped", move(result.trap()), InstantiationErrorSource::StartFunction };
- }
-
- return InstantiationResult { move(main_module_instance_pointer) };
-}
-
-Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(Module const& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values, Vector<Value>& table_initial_values, Vector<FunctionAddress>& own_functions)
-{
- Optional<InstantiationError> result;
-
- for (auto& entry : externs) {
- entry.visit(
- [&](FunctionAddress const& address) { module_instance.functions().append(address); },
- [&](TableAddress const& address) { module_instance.tables().append(address); },
- [&](MemoryAddress const& address) { module_instance.memories().append(address); },
- [&](GlobalAddress const& address) { module_instance.globals().append(address); },
- [&](TagAddress const& address) { module_instance.tags().append(address); });
- }
-
- module_instance.functions().extend(own_functions);
-
- // https://webassembly.github.io/spec/core/valid/conventions.html#aux-clostype
- TypeContext const module_type_context { module.canonical_types().span() };
-
- for (auto [table_index, table] : enumerate(module.table_section().tables())) {
- auto table_address = m_store.allocate(TableType { canonicalized(table.type().element_type(), module_type_context), table.type().limits() });
- if (!table_address.has_value())
- return InstantiationError { "Failed to allocate a table instance" };
- module_instance.tables().append(*table_address);
-
- auto reference = table_initial_values[table_index].to<Reference>();
- if (!reference.ref().has<Reference::Null>()) {
- auto* table_instance = m_store.get(*table_address);
- RefPtr<ModuleInstance const> anchor;
- if (reference.ref().has<Reference::Func>())
- anchor = &module_instance;
- for (size_t i = 0; i < table_instance->elements().size(); ++i)
- table_instance->set_element(i, reference, anchor);
- }
- }
-
- for (auto& memory : module.memory_section().memories()) {
- auto memory_address = m_store.allocate(memory.type());
- if (!memory_address.has_value())
- return InstantiationError { "Failed to allocate a memory instance" };
- module_instance.memories().append(*memory_address);
- }
-
- size_t index = 0;
- for (auto& entry : module.global_section().entries()) {
- auto address = m_store.allocate(GlobalType { canonicalized(entry.type().type(), module_type_context), entry.type().is_mutable() }, move(global_values[index]));
- VERIFY(address.has_value());
- module_instance.globals().append(*address);
- index++;
- }
-
- for (auto& entry : module.tag_section().tags()) {
- auto& type = module.type_section().types()[entry.type().value()];
- auto const* defined_type = module.canonical_types()[entry.type().value()];
- auto address = m_store.allocate(type.function(), defined_type, entry.flags());
- VERIFY(address.has_value());
- module_instance.tags().append(*address);
- }
-
- for (auto& entry : module.export_section().entries()) {
- Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, TagAddress, Empty> address {};
- entry.description().visit(
- [&](FunctionIndex const& index) {
- if (module_instance.functions().size() > index.value())
- address = FunctionAddress { module_instance.functions()[index.value()] };
- else
- dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
- },
- [&](TableIndex const& index) {
- if (module_instance.tables().size() > index.value())
- address = TableAddress { module_instance.tables()[index.value()] };
- else
- dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
- },
- [&](MemoryIndex const& index) {
- if (module_instance.memories().size() > index.value())
- address = MemoryAddress { module_instance.memories()[index.value()] };
- else
- dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
- },
- [&](GlobalIndex const& index) {
- if (module_instance.globals().size() > index.value())
- address = GlobalAddress { module_instance.globals()[index.value()] };
- else
- dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
- },
- [&](TagIndex const& index) {
- if (module_instance.tags().size() > index.value())
- address = TagAddress { module_instance.tags()[index.value()] };
- else
- dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tags().size());
- });
-
- if (address.has<Empty>()) {
- result = InstantiationError { "An export could not be resolved" };
- continue;
- }
-
- module_instance.exports().append(ExportInstance {
- entry.name(),
- move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, TagAddress>(),
- });
- }
-
- return result;
-}
-
-Optional<InstantiationError> AbstractMachine::allocate_all_final_phase(Module const& module, ModuleInstance& module_instance, Vector<Vector<Reference>>& elements)
-{
- size_t index = 0;
- for (auto& segment : module.element_section().segments()) {
- auto address = m_store.allocate(segment.type, move(elements[index]));
- VERIFY(address.has_value());
- module_instance.elements().append(*address);
- index++;
- }
-
- return {};
-}
-
-Result AbstractMachine::invoke(FunctionAddress address, Vector<Value, ArgumentsStaticSize> arguments)
-{
- auto interpreter = m_available_interpreters.is_empty()
- ? make<BytecodeInterpreter>(m_stack_info)
- : m_available_interpreters.take_last();
-
- auto result = [&] {
- auto handle = register_scoped(*interpreter);
- return invoke(*interpreter, address, move(arguments));
- }();
-
- interpreter->clear_trap();
- if (m_available_interpreters.size() < MAX_AVAILABLE_EXECUTION_STATES)
- m_available_interpreters.append(move(interpreter));
- return result;
-}
-
-Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value, ArgumentsStaticSize> arguments)
-{
- auto configuration = m_available_configurations.is_empty()
- ? make<Configuration>(m_store)
- : m_available_configurations.take_last();
- if (m_should_limit_instruction_count)
- configuration->enable_instruction_count_limit();
-
- auto result = configuration->call(interpreter, address, arguments);
-
- configuration->reset_after_invoke({});
- if (m_available_configurations.size() < MAX_AVAILABLE_EXECUTION_STATES)
- m_available_configurations.append(move(configuration));
- return result;
-}
-
-void Linker::link(ModuleInstance const& instance)
-{
- populate();
- if (m_unresolved_imports.is_empty())
- return;
-
- HashTable<Name> resolved_imports;
- for (auto& import_ : m_unresolved_imports) {
- auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
- if (!it.is_end()) {
- resolved_imports.set(import_);
- m_resolved_imports.set(import_, it->value());
- }
- }
-
- for (auto& entry : resolved_imports)
- m_unresolved_imports.remove(entry);
-}
-
-void Linker::link(HashMap<Linker::Name, ExternValue> const& exports)
-{
- populate();
- if (m_unresolved_imports.is_empty())
- return;
-
- if (exports.is_empty())
- return;
-
- HashTable<Name> resolved_imports;
- for (auto& import_ : m_unresolved_imports) {
- auto export_ = exports.get(import_);
- if (export_.has_value()) {
- resolved_imports.set(import_);
- m_resolved_imports.set(import_, export_.value());
- }
- }
-
- for (auto& entry : resolved_imports)
- m_unresolved_imports.remove(entry);
-}
-
-AK::ErrorOr<Vector<ExternValue>, LinkError> Linker::finish()
-{
- populate();
- if (!m_unresolved_imports.is_empty()) {
- if (!m_error.has_value())
- m_error = LinkError {};
- for (auto& entry : m_unresolved_imports)
- m_error->missing_imports.append(entry.name);
- return *m_error;
- }
-
- if (m_error.has_value())
- return *m_error;
-
- // Result must be in the same order as the module imports
- Vector<ExternValue> exports;
- exports.ensure_capacity(m_ordered_imports.size());
- for (auto& import_ : m_ordered_imports)
- exports.unchecked_append(*m_resolved_imports.get(import_));
- return exports;
-}
-
-void Linker::populate()
-{
- if (!m_ordered_imports.is_empty())
- return;
-
- for (auto& import_ : m_module.import_section().imports()) {
- m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
- m_unresolved_imports.set(m_ordered_imports.last());
- }
-}
-
-void AbstractMachine::visit_external_resources(HostVisitOps const& host)
-{
- for (auto interpreter_ptr : m_active_interpreters)
- interpreter_ptr->visit_external_resources(host);
-}
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/AbstractMachine.h b/Libraries/LibWasm/AbstractMachine/AbstractMachine.h
deleted file mode 100644
index 384ad2a99fb..00000000000
--- a/Libraries/LibWasm/AbstractMachine/AbstractMachine.h
+++ /dev/null
@@ -1,1112 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Function.h>
-#include <AK/HashMap.h>
-#include <AK/HashTable.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/StackInfo.h>
-#include <AK/UFixedBigInt.h>
-#include <AK/Weakable.h>
-#include <LibGC/Cell.h>
-#include <LibGC/CellAllocator.h>
-#include <LibGC/ConservativeRangeProvider.h>
-#include <LibGC/Heap.h>
-#include <LibGC/PrimitiveStorage.h>
-#include <LibWasm/Export.h>
-#include <LibWasm/TypeSystem.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-constexpr inline size_t ArgumentsStaticSize = 3;
-constexpr inline size_t ResultsStaticSize = 1;
-
-class Configuration;
-class Result;
-struct BytecodeInterpreter;
-struct Interpreter;
-struct Trap;
-
-struct LinkError {
- enum OtherErrors {
- InvalidImportedModule,
- };
- Vector<ByteString> missing_imports;
- Vector<OtherErrors> other_errors;
-};
-
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, FunctionAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, ExternAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, TableAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, GlobalAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, ElementAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, DataAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, MemoryAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, TagAddress, Arithmetic, Comparison, Increment);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, ExceptionAddress, Arithmetic, Comparison, Increment);
-
-// FIXME: These should probably be made generic/virtual if/when we decide to do something more
-// fancy than just a dumb interpreter.
-class Reference {
-public:
- struct Null {
- ValueType type;
- };
- struct Func {
- FunctionAddress address;
- RefPtr<Module const> source_module; // null if host function.
- };
- struct Extern {
- ExternAddress address;
- };
- struct Exception {
- ExceptionAddress address;
- };
- // https://webassembly.github.io/spec/core/exec/runtime.html#values
- // ref.i31 i31: an unboxed 31-bit scalar reference.
- struct I31 {
- u32 value; // using only low 31 bits
- };
- // A reference to a structure or array instance (a GC::Cell, see StructInstance and ArrayInstance below).
- struct GcObject {
- GC::Ptr<GC::Cell> ptr;
- };
-
- using RefType = Variant<Null, Func, Extern, Exception, I31, GcObject>;
- explicit Reference(RefType ref)
- : m_ref(move(ref))
- {
- }
- explicit Reference()
- : m_ref(Reference::Null { ValueType(ValueType::Kind::FunctionReference) })
- {
- }
-
- auto& ref() const { return m_ref; }
-
-private:
- RefType m_ref;
-};
-
-class Value {
-public:
- Value() = default;
-
- explicit Value(ValueType type)
- : m_value(u128())
- {
- switch (type.kind()) {
- case ValueType::I32:
- case ValueType::I64:
- case ValueType::F32:
- case ValueType::F64:
- case ValueType::V128:
- case ValueType::I8:
- case ValueType::I16:
- break;
- case ValueType::FunctionReference:
- case ValueType::NoFunctionReference:
- // ref.null func | ref.null nofunc
- m_value = u128(0, 2);
- break;
- case ValueType::ExternReference:
- case ValueType::NoExternReference:
- // ref.null extern | ref.null noextern
- m_value = u128(0, 3);
- break;
- case ValueType::ExceptionReference:
- case ValueType::NoExceptionReference:
- // ref.null exn | ref.null noexn
- m_value = u128(0, 4);
- break;
- case ValueType::AnyReference:
- case ValueType::EqReference:
- case ValueType::I31Reference:
- case ValueType::StructReference:
- case ValueType::ArrayReference:
- case ValueType::NoneReference:
- case ValueType::TypeUseReference:
- m_value = u128(0, 8);
- break;
- }
- }
-
- template<typename T>
- requires(sizeof(T) == sizeof(u64)) explicit Value(T raw_value)
- : m_value(u128(bit_cast<i64>(raw_value), 0))
- {
- }
-
- template<typename T>
- requires(sizeof(T) == sizeof(u32)) explicit Value(T raw_value)
- : m_value(u128(static_cast<i64>(bit_cast<i32>(raw_value)), 0))
- {
- }
-
- template<typename T>
- requires(sizeof(T) == sizeof(u8) && Signed<T>) explicit Value(T raw_value)
- : m_value(u128(static_cast<i64>(bit_cast<i8>(raw_value)), 0))
- {
- }
-
- template<typename T>
- requires(sizeof(T) == sizeof(u8) && Unsigned<T>) explicit Value(T raw_value)
- : m_value(u128(static_cast<u64>(bit_cast<u8>(raw_value)), 0))
- {
- }
-
- template<typename T>
- requires(sizeof(T) == sizeof(u16) && Signed<T>) explicit Value(T raw_value)
- : m_value(u128(static_cast<i64>(bit_cast<i16>(raw_value)), 0))
- {
- }
-
- template<typename T>
- requires(sizeof(T) == sizeof(u16) && Unsigned<T>) explicit Value(T raw_value)
- : m_value(u128(static_cast<u64>(bit_cast<u16>(raw_value)), 0))
- {
- }
-
- explicit Value(Reference const& ref)
- {
- // Reference variant is encoded in the high storage of the u128:
- // 1: externref
- // 2: null funcref
- // 3: null externref
- // 4: null exnref
- // 5: exnref
- // 6: a gc object
- // 7: an i31 reference
- // 8: a null reference in the any hierarchy
- // 9 | (tag << 8): an "externalized" internal reference (extern.convert_any)
- // 10: a host externref viewed as a value in the any hierarchy (any.convert_extern)
- // anything else: funcref, where high is the defining Module* (null for host functions)
- ref.ref().visit(
- [&](Reference::Func const& func) { m_value = u128(bit_cast<u64>(func.address), bit_cast<u64>(func.source_module.ptr())); },
- [&](Reference::Extern const& func) { m_value = u128(bit_cast<u64>(func.address), 1); },
- [&](Reference::Null const& null) {
- switch (null.type.kind()) {
- case ValueType::Kind::FunctionReference:
- case ValueType::Kind::NoFunctionReference:
- m_value = u128(0, 2);
- break;
- case ValueType::Kind::ExternReference:
- case ValueType::Kind::NoExternReference:
- m_value = u128(0, 3);
- break;
- case ValueType::Kind::ExceptionReference:
- case ValueType::Kind::NoExceptionReference:
- m_value = u128(0, 4);
- break;
- default:
- m_value = u128(0, 8);
- break;
- }
- },
- [&](Reference::Exception const& exn) { m_value = u128(bit_cast<u64>(exn.address), 5); },
- [&](Reference::I31 const& i31) { m_value = u128(static_cast<u64>(i31.value & 0x7fffffff), 7); },
- [&](Reference::GcObject const& object) { m_value = u128(bit_cast<u64>(object.ptr.ptr()), 6); });
- }
-
- // The gc cell behind this value if it holds a gc object reference, otherwise null.
- GC::Cell* gc_cell() const
- {
- // A gc object, either plain (tag 6) or externalized by extern.convert_any (tag 9
- // wrapping tag 6).
- if (m_value.high() == 6 || m_value.high() == (9 | (6 << 8)))
- return bit_cast<GC::Cell*>(m_value.low());
- return nullptr;
- }
-
- template<SameAs<u128> T>
- explicit Value(T raw_value)
- : m_value(raw_value)
- {
- }
-
- ALWAYS_INLINE Value(Value const& value) = default;
- ALWAYS_INLINE Value(Value&& value) = default;
- ALWAYS_INLINE Value& operator=(Value&& value) = default;
- ALWAYS_INLINE Value& operator=(Value const& value) = default;
-
- template<typename T>
- ALWAYS_INLINE T to() const
- {
- static_assert(IsOneOf<T, u128, u64, i64, f32, f64, Reference> || IsIntegral<T>, "Unsupported type for Value::to()");
-
- if constexpr (IsSame<T, u128>) {
- return m_value;
- }
- if constexpr (IsOneOf<T, u64, i64>) {
- return bit_cast<T>(m_value.low());
- }
- if constexpr (IsIntegral<T> && sizeof(T) < 8) {
- return bit_cast<T>(static_cast<MakeUnsigned<T>>(m_value.low() & NumericLimits<MakeUnsigned<T>>::max()));
- }
- if constexpr (IsSame<T, f32>) {
- u32 low = m_value.low() & 0xFFFFFFFF;
- return bit_cast<f32>(low);
- }
- if constexpr (IsSame<T, f64>) {
- return bit_cast<f64>(m_value.low());
- }
- if constexpr (IsSame<T, Reference>) {
- switch (m_value.high()) {
- case 1:
- return Reference { Reference::Extern { bit_cast<ExternAddress>(m_value.low()) } };
- case 2:
- return Reference { Reference::Null { ValueType(ValueType::Kind::FunctionReference) } };
- case 3:
- return Reference { Reference::Null { ValueType(ValueType::Kind::ExternReference) } };
- case 4:
- return Reference { Reference::Null { ValueType(ValueType::Kind::ExceptionReference) } };
- case 5:
- return Reference { Reference::Exception { bit_cast<ExceptionAddress>(m_value.low()) } };
- case 6:
- return Reference { Reference::GcObject { bit_cast<GC::Cell*>(m_value.low()) } };
- case 7:
- return Reference { Reference::I31 { static_cast<u32>(m_value.low()) } };
- case 8:
- return Reference { Reference::Null { ValueType(ValueType::Kind::AnyReference) } };
- case 9 | (6 << 8):
- // An externalized gc object; boxing drops the extern.convert_any wrapper.
- return Reference { Reference::GcObject { bit_cast<GC::Cell*>(m_value.low()) } };
- case 9 | (7 << 8):
- // An externalized i31; boxing drops the extern.convert_any wrapper.
- return Reference { Reference::I31 { static_cast<u32>(m_value.low()) } };
- case 10:
- // A host externref internalized by any.convert_extern; boxing drops the wrapper.
- return Reference { Reference::Extern { bit_cast<ExternAddress>(m_value.low()) } };
- default:
- return Reference { Reference::Func { bit_cast<FunctionAddress>(m_value.low()), bit_cast<Wasm::Module*>(m_value.high()) } };
- }
- }
- VERIFY_NOT_REACHED();
- }
-
- auto& value() const { return m_value; }
-
-private:
- u128 m_value;
-};
-static_assert(IsTriviallyDestructible<Value>);
-static_assert(IsTriviallyConstructible<Value>);
-
-struct ExternallyManagedTrap {
- Array<u8, 64> data;
-
- template<typename T>
- T const& unsafe_external_object_as() const
- {
- static_assert(sizeof(T) <= sizeof(data), "Object size is too large for ExternallyManagedTrap");
- return *reinterpret_cast<T const*>(data.data());
- }
-};
-
-// https://webassembly.github.io/spec/core/exec/runtime.html#results
-struct UncaughtException {
- ExceptionAddress address;
-};
-
-struct Trap {
- Variant<ByteString, ExternallyManagedTrap, UncaughtException> data;
-
- ByteString format() const
- {
- if (auto const* ptr = data.get_pointer<ByteString>())
- return *ptr;
- if (data.has<UncaughtException>())
- return "uncaught exception";
- return "<Externally managed Trap Data>";
- }
-
- template<typename T>
- static Trap from_external_object(T&& object)
- {
- static_assert(sizeof(T) <= sizeof(ExternallyManagedTrap::data), "Object size is too large for ExternallyManagedTrap");
- static_assert(IsTriviallyCopyable<T>, "Object must be trivially copyable");
- static_assert(IsTriviallyDestructible<T>, "Object must be trivially destructible");
-
- ExternallyManagedTrap externally_managed_trap;
- new (externally_managed_trap.data.data()) T(forward<T>(object));
- return Trap { externally_managed_trap };
- }
-
- static Trap from_string(ByteString string)
- {
- return Trap { move(string) };
- }
-};
-
-class Result {
-public:
- explicit Result(Vector<Value, ResultsStaticSize> values)
- : m_result(move(values))
- {
- }
-
- Result(Trap trap)
- : m_result(move(trap))
- {
- }
-
- auto is_trap() const { return m_result.has<Trap>(); }
- auto& values() const { return m_result.get<Vector<Value, ResultsStaticSize>>(); }
- auto& values() { return m_result.get<Vector<Value, ResultsStaticSize>>(); }
- auto& trap() const { return m_result.get<Trap>(); }
- auto& trap() { return m_result.get<Trap>(); }
-
-private:
- explicit Result(Variant<Vector<Value, ResultsStaticSize>, Trap>&& result)
- : m_result(move(result))
- {
- }
-
- Variant<Vector<Value, ResultsStaticSize>, Trap> m_result;
-};
-
-enum class InstantiationErrorSource : u8 {
- Linking,
- StartFunction,
-};
-
-struct InstantiationError {
- ByteString error { "Unknown error" };
- Optional<Trap> relevant_trap {};
- InstantiationErrorSource source { InstantiationErrorSource::Linking };
-};
-
-using ExternValue = Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, TagAddress>;
-
-class Store;
-class ModuleInstance;
-class MemoryInstance;
-class GlobalInstance;
-
-using MemoryInstanceTable = MemoryInstance**;
-using GlobalInstanceTable = GlobalInstance**;
-
-struct CompiledFunctionEntry {
- FlatPtr handler_ptr { 0 }; // 0 = not compiled, use slow path
- FlatPtr dispatches_ptr { 0 }; // Dispatch const*
- FlatPtr src_dst_ptr { 0 }; // SourcesAndDestination const*
- Instruction const* first_insn { nullptr };
- Expression const* expression { nullptr };
- ModuleInstance const* module { nullptr };
- u32 total_local_count { 0 };
- u32 arity { 0 };
- u32 max_call_rec_size { 0 };
-};
-
-class ExportInstance {
-public:
- explicit ExportInstance(ByteString name, ExternValue value)
- : m_name(move(name))
- , m_value(move(value))
- {
- }
-
- auto& name() const { return m_name; }
- auto& value() const { return m_value; }
-
-private:
- ByteString m_name;
- ExternValue m_value;
-};
-
-class WASM_API ModuleInstance : public RefCounted<ModuleInstance>
- , public Weakable<ModuleInstance> {
-public:
- explicit ModuleInstance(
- Vector<TypeSection::Type> types, Vector<FunctionAddress> function_addresses, Vector<TableAddress> table_addresses, Vector<MemoryAddress> memory_addresses, Vector<GlobalAddress> global_addresses, Vector<DataAddress> data_addresses, Vector<TagAddress> tag_addresses, Vector<TagType> tag_types, Vector<ExportInstance> exports, size_t minimum_call_record_allocation_size)
- : cached_minimum_call_record_allocation_size(minimum_call_record_allocation_size)
- , m_types(move(types))
- , m_tag_types(move(tag_types))
- , m_functions(move(function_addresses))
- , m_tables(move(table_addresses))
- , m_memories(move(memory_addresses))
- , m_globals(move(global_addresses))
- , m_datas(move(data_addresses))
- , m_tags(move(tag_addresses))
- , m_exports(move(exports))
- {
- }
-
- ModuleInstance() = default;
-
- auto& types() const { return m_types; }
- auto& canonical_types() const { return m_canonical_types; }
- auto& canonical_types() { return m_canonical_types; }
- auto& functions() const { return m_functions; }
- auto& tables() const { return m_tables; }
- auto& memories() const { return m_memories; }
- auto& globals() const { return m_globals; }
- auto& elements() const { return m_elements; }
- auto& datas() const { return m_datas; }
- auto& exports() const { return m_exports; }
- auto& tags() const { return m_tags; }
- auto& tag_types() const { return m_tag_types; }
-
- auto& types() { return m_types; }
- auto& functions() { return m_functions; }
- auto& tables() { return m_tables; }
- auto& memories() { return m_memories; }
- auto& globals() { return m_globals; }
- auto& elements() { return m_elements; }
- auto& datas() { return m_datas; }
- auto& exports() { return m_exports; }
- auto& tags() { return m_tags; }
- auto& tag_types() { return m_tag_types; }
-
- size_t cached_minimum_call_record_allocation_size { 0 };
-
- MemoryInstanceTable resolved_memories(Store&) const;
- GlobalInstanceTable resolved_globals(Store&) const;
- Vector<CompiledFunctionEntry> const& compiled_fn_table(Store&) const;
-
-private:
- Vector<TypeSection::Type> m_types;
- Vector<DefinedType const*> m_canonical_types;
- Vector<TagType> m_tag_types;
- Vector<FunctionAddress> m_functions;
- Vector<TableAddress> m_tables;
- Vector<MemoryAddress> m_memories;
- Vector<GlobalAddress> m_globals;
- Vector<ElementAddress> m_elements;
- Vector<DataAddress> m_datas;
- Vector<TagAddress> m_tags;
- Vector<ExportInstance> m_exports;
-
- mutable Vector<MemoryInstance*> m_resolved_memories;
- mutable bool m_resolved_memories_built { false };
- mutable Vector<GlobalInstance*> m_resolved_globals;
- mutable bool m_resolved_globals_built { false };
- mutable Vector<CompiledFunctionEntry> m_compiled_fn_table;
- mutable bool m_compiled_fn_table_built { false };
-};
-
-class WasmFunction {
-public:
- explicit WasmFunction(FunctionType const& type, DefinedType const* defined_type, ModuleInstance const& instance, Module const& module, CodeSection::Code const& code)
- : m_type(type)
- , m_defined_type(defined_type)
- , m_module(module.make_weak_ptr())
- , m_module_instance(instance.make_weak_ptr<ModuleInstance const>())
- , m_code(&code)
- {
- }
-
- auto& type() const { return m_type; }
- // https://webassembly.github.io/spec/core/exec/runtime.html#function-instances
- DefinedType const* defined_type() const { return m_defined_type; }
- ModuleInstance const& module() const { return *m_module_instance.strong_ref(); }
- RefPtr<ModuleInstance const> try_module() const { return m_module_instance.strong_ref(); }
- auto& code() const { return *m_code; }
- RefPtr<Module const> module_ref() const { return m_module.strong_ref(); }
-
-private:
- FunctionType m_type;
- DefinedType const* m_defined_type { nullptr };
- WeakPtr<Module const> m_module;
- WeakPtr<ModuleInstance const> m_module_instance;
- CodeSection::Code const* m_code;
-};
-
-class HostFunction {
-public:
- explicit HostFunction(AK::Function<Result(Configuration&, Span<Value>)> function, FunctionType const& type, ByteString name)
- : m_function(move(function))
- , m_type(type)
- , m_name(move(name))
- {
- }
-
- auto& function() { return m_function; }
- auto& type() const { return m_type; }
- auto& name() const { return m_name; }
-
- // Interned on the store.
- DefinedType const* defined_type() const { return m_defined_type; }
- void set_defined_type(DefinedType const* defined_type) { m_defined_type = defined_type; }
-
-private:
- AK::Function<Result(Configuration&, Span<Value>)> m_function;
- FunctionType m_type;
- DefinedType const* m_defined_type { nullptr };
- ByteString m_name;
-};
-
-using FunctionInstance = Variant<WasmFunction, HostFunction>;
-
-class TableInstance {
-public:
- explicit TableInstance(TableType const& type, Vector<Reference> elements)
- : m_elements(move(elements))
- , m_type(type)
- {
- m_module_anchors.resize(m_elements.size());
- }
-
- auto& elements() const { return m_elements; }
- auto& elements() { return m_elements; }
- auto& type() const { return m_type; }
-
- // MUST use this if a function reference can be stored in the table
- void set_element(size_t index, Reference ref, RefPtr<ModuleInstance const> module_anchor = {})
- {
- m_elements[index] = move(ref);
- m_module_anchors[index] = move(module_anchor);
- }
-
- // Strong ref pinning the element's defining ModuleInstance (null for non-Func).
- RefPtr<ModuleInstance const> module_anchor_at(size_t index) const { return m_module_anchors[index]; }
-
- bool grow(u32 size_to_grow, Reference const& fill_value, RefPtr<ModuleInstance const> fill_module_anchor = {})
- {
- if (size_to_grow == 0)
- return true;
- size_t new_size = m_elements.size() + size_to_grow;
- if (auto max = m_type.limits().max(); max.has_value()) {
- if (max.value() < new_size)
- return false;
- }
- if (new_size >= NumericLimits<u32>::max()) {
- return false;
- }
- auto previous_size = m_elements.size();
- if (m_elements.try_resize(new_size).is_error())
- return false;
- if (m_module_anchors.try_resize(new_size).is_error())
- return false;
- for (size_t i = previous_size; i < m_elements.size(); ++i) {
- m_elements[i] = fill_value;
- m_module_anchors[i] = fill_module_anchor;
- }
-
- m_type = TableType { m_type.element_type(), Limits(m_type.limits().address_type(), m_type.limits().min() + size_to_grow, m_type.limits().max()) };
-
- return true;
- }
-
-private:
- Vector<Reference> m_elements;
- Vector<RefPtr<ModuleInstance const>> m_module_anchors;
- TableType m_type;
-};
-
-class WASM_API MemoryBuffer {
-public:
- MemoryBuffer() = default;
- ~MemoryBuffer();
-
- MemoryBuffer(MemoryBuffer&&);
- MemoryBuffer& operator=(MemoryBuffer&&);
-
- MemoryBuffer(MemoryBuffer const&) = delete;
- MemoryBuffer& operator=(MemoryBuffer const&) = delete;
-
- ErrorOr<void> try_reserve(size_t capacity, size_t guard_size = 0);
- ErrorOr<void> try_resize(size_t new_size);
- ErrorOr<void> try_resize(size_t new_size, size_t reserved_capacity);
-
- auto size() const { return m_size; }
- auto capacity() const { return m_reserved_capacity; }
- auto data() const { return GC::PrimitiveStorage::the().data(m_handle); }
- auto data() { return GC::PrimitiveStorage::the().data(m_handle); }
- auto storage_offset() const { return m_storage_offset; }
- GC::PrimitiveStorageHandle primitive_storage_handle() const { return m_handle; }
- Bytes bytes() { return { data(), size() }; }
- ReadonlyBytes bytes() const { return { data(), size() }; }
- Bytes span() { return bytes(); }
- ReadonlyBytes span() const { return bytes(); }
- u8* offset_pointer(size_t offset)
- {
- if (m_storage_offset == GC::PrimitiveStorage::invalid_offset)
- return nullptr;
- auto* cage_base = GC::PrimitiveStorage::the().cage_base();
- VERIFY(cage_base);
- return cage_base + GC::PrimitiveStorage::mask_offset(m_storage_offset + offset);
- }
- u8 const* offset_pointer(size_t offset) const { return const_cast<MemoryBuffer&>(*this).offset_pointer(offset); }
- u8& operator[](size_t index) { return *offset_pointer(index); }
- u8 const& operator[](size_t index) const { return *offset_pointer(index); }
- size_t contiguous_bytes_from(size_t offset, size_t count) const;
- size_t contiguous_bytes_before(size_t offset, size_t count) const;
- void copy_to(size_t offset, Bytes destination) const;
- void copy_from(MemoryBuffer const& source, size_t source_offset, size_t destination_offset, size_t count);
- void fill(size_t offset, u8 value, size_t count);
- void overwrite(size_t offset, void const* source, size_t count);
- void move_data(size_t destination_offset, size_t source_offset, size_t count);
- bool contains_virtual_address(void const* address) const;
-
- static constexpr size_t storage_offset_offset() { return __builtin_offsetof(MemoryBuffer, m_storage_offset); }
-
-private:
- void clear();
- void update_storage_offset();
-
- size_t m_size { 0 };
- size_t m_reserved_capacity { 0 };
- GC::PrimitiveStorageHandle m_handle;
- size_t m_storage_offset { GC::PrimitiveStorage::invalid_offset };
-};
-
-class WASM_API MemoryInstance {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- static ErrorOr<MemoryInstance> create(MemoryType const& type);
-
- auto& type() const { return m_type; }
- auto size() const { return m_data.size(); }
- auto& data() const { return m_data; }
- auto& data() { return m_data; }
- bool contains_virtual_address(void const* address) const { return m_data.contains_virtual_address(address); }
-
- enum class InhibitGrowCallback {
- No,
- Yes,
- };
-
- enum class GrowType {
- No,
- Yes,
- };
-
- bool grow(size_t size_to_grow, GrowType grow_type = GrowType::Yes, InhibitGrowCallback inhibit_callback = InhibitGrowCallback::No);
-
- Function<void()> successful_grow_hook;
-
- static constexpr size_t data_offset() { return __builtin_offsetof(MemoryInstance, m_data); }
-
-private:
- explicit MemoryInstance(MemoryType const& type);
-
- MemoryType m_type;
- MemoryBuffer m_data;
-};
-
-class GlobalInstance {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- explicit GlobalInstance(Value value, bool is_mutable, ValueType type)
- : m_mutable(is_mutable)
- , m_value(value)
- , m_type(type)
- {
- }
-
- auto is_mutable() const { return m_mutable; }
- auto& value() const { return m_value; }
- GlobalType type() const { return { m_type, is_mutable() }; }
- void set_value(Value value)
- {
- VERIFY(is_mutable());
- m_value = move(value);
- }
-
- static constexpr size_t value_offset() { return __builtin_offsetof(GlobalInstance, m_value); }
-
-private:
- bool m_mutable { false };
- Value m_value;
- ValueType m_type;
-};
-
-class DataInstance {
-public:
- explicit DataInstance(Vector<u8> data)
- : m_data(move(data))
- {
- }
-
- size_t size() const { return m_data.size(); }
-
- Vector<u8>& data() { return m_data; }
- Vector<u8> const& data() const { return m_data; }
-
-private:
- Vector<u8> m_data;
-};
-
-class ElementInstance {
-public:
- explicit ElementInstance(ValueType type, Vector<Reference> references)
- : m_type(move(type))
- , m_references(move(references))
- {
- }
-
- auto& type() const { return m_type; }
- auto& references() const { return m_references; }
-
-private:
- ValueType m_type;
- Vector<Reference> m_references;
-};
-
-class TagInstance {
-public:
- TagInstance(FunctionType const& type, DefinedType const* defined_type, TagType::Flags flags)
- : m_type(type)
- , m_defined_type(defined_type)
- , m_flags(flags)
- {
- }
-
- auto& type() const { return m_type; }
- // https://webassembly.github.io/spec/core/exec/runtime.html#tag-instances
- DefinedType const* defined_type() const { return m_defined_type; }
- auto flags() const { return m_flags; }
-
-private:
- FunctionType m_type;
- DefinedType const* m_defined_type { nullptr };
- TagType::Flags m_flags;
-};
-
-// https://webassembly.github.io/spec/core/exec/runtime.html#exception-instances
-class ExceptionInstance {
-public:
- explicit ExceptionInstance(TagAddress tag, Vector<Value> params)
- : m_tag(tag)
- , m_params(move(params))
- {
- }
-
- auto tag() const { return m_tag; }
- auto& params() const { return m_params; }
-
-private:
- TagAddress m_tag;
- Vector<Value> m_params;
-};
-
-// https://webassembly.github.io/spec/core/exec/runtime.html#aggregate-instances
-class WASM_API StructInstance final : public GC::Cell {
- GC_CELL(StructInstance, GC::Cell);
- GC_DECLARE_ALLOCATOR(StructInstance);
-
-public:
- DefinedType const& type() const { return *m_type; }
- ReadonlySpan<Value> fields() const { return m_fields; }
- Span<Value> fields() { return m_fields; }
-
-private:
- StructInstance(DefinedType const& type, Vector<Value> fields)
- : m_type(&type)
- , m_fields(move(fields))
- {
- }
-
- virtual void visit_edges(Visitor&) override;
-
- DefinedType const* m_type { nullptr };
- Vector<Value> m_fields;
-};
-
-class WASM_API ArrayInstance final : public GC::Cell {
- GC_CELL(ArrayInstance, GC::Cell);
- GC_DECLARE_ALLOCATOR(ArrayInstance);
-
-public:
- DefinedType const& type() const { return *m_type; }
- ReadonlySpan<Value> elements() const { return m_elements; }
- Span<Value> elements() { return m_elements; }
-
-private:
- ArrayInstance(DefinedType const& type, Vector<Value> elements)
- : m_type(&type)
- , m_elements(move(elements))
- {
- }
-
- virtual void visit_edges(Visitor&) override;
-
- DefinedType const* m_type { nullptr };
- Vector<Value> m_elements;
-};
-
-class WASM_API Store {
-public:
- Store() = default;
-
- Optional<FunctionAddress> allocate(ModuleInstance&, Module const&, CodeSection::Code const&, TypeIndex);
- Optional<FunctionAddress> allocate(HostFunction&&);
- Optional<TableAddress> allocate(TableType const&);
- Optional<MemoryAddress> allocate(MemoryType const&);
- Optional<DataAddress> allocate_data(Vector<u8>);
- Optional<GlobalAddress> allocate(GlobalType const&, Value);
- Optional<ElementAddress> allocate(ValueType const&, Vector<Reference>);
- Optional<TagAddress> allocate(FunctionType const&, DefinedType const*, TagType::Flags);
- Optional<ExceptionAddress> allocate(TagAddress, Vector<Value>);
-
- Module const* get_module_for(FunctionAddress);
- RefPtr<ModuleInstance const> get_module_instance_for(FunctionAddress); // Obtains strong ref for module.
- FunctionInstance* get(FunctionAddress);
- TableInstance* get(TableAddress);
- MemoryInstance* get(MemoryAddress);
- GlobalInstance* get(GlobalAddress);
- DataInstance* get(DataAddress);
- ElementInstance* get(ElementAddress);
- TagInstance* get(TagAddress);
- ExceptionInstance* get(ExceptionAddress);
-
- ALWAYS_INLINE FunctionInstance* unsafe_get(FunctionAddress address) { return &m_functions.data()[address.value()]; }
- ALWAYS_INLINE MemoryInstance* unsafe_get(MemoryAddress address) { return m_memories.data()[address.value()].ptr(); }
- ALWAYS_INLINE GlobalInstance* unsafe_get(GlobalAddress address) { return m_globals.data()[address.value()].ptr(); }
-
- GC::Heap& heap() { return *m_heap; }
- void set_heap(GC::Heap& heap) { m_heap = &heap; }
-
- void register_configuration(Badge<Configuration>, Configuration& configuration) { m_active_configurations.set(&configuration); }
- void unregister_configuration(Badge<Configuration>, Configuration& configuration) { m_active_configurations.remove(&configuration); }
- auto& active_configurations() const { return m_active_configurations; }
-
- auto& tables() const { return m_tables; }
- auto& globals() const { return m_globals; }
- auto& elements() const { return m_elements; }
- auto& exceptions() const { return m_exceptions; }
-
-private:
- Vector<FunctionInstance> m_functions;
- Vector<TableInstance> m_tables;
- Vector<NonnullOwnPtr<MemoryInstance>> m_memories;
- Vector<NonnullOwnPtr<GlobalInstance>> m_globals;
- Vector<ElementInstance> m_elements;
- Vector<DataInstance> m_datas;
- Vector<TagInstance> m_tags;
- Vector<ExceptionInstance> m_exceptions;
-
- GC::Heap* m_heap { nullptr };
- HashTable<Configuration*> m_active_configurations;
-};
-
-class Label {
-public:
- explicit Label(size_t arity, InstructionPointer continuation, size_t stack_height, Instruction const* try_table_instruction = nullptr)
- : m_arity(arity)
- , m_stack_height(stack_height)
- , m_continuation(continuation)
- , m_try_table_instruction(try_table_instruction)
- {
- }
-
- auto continuation() const { return m_continuation; }
- auto arity() const { return m_arity; }
- auto stack_height() const { return m_stack_height; }
- // https://webassembly.github.io/spec/core/exec/instructions.html#exec-try-table
- Instruction const* try_table_instruction() const { return m_try_table_instruction; }
-
-private:
- size_t m_arity { 0 };
- size_t m_stack_height { 0 };
- InstructionPointer m_continuation { 0 };
- Instruction const* m_try_table_instruction { nullptr };
-};
-
-class Frame {
-public:
- // An owning frame's pointer can be invalidated when m_owned_locals_stack grows, so re-derive teh pointer from the stack's data() when needed.
- explicit Frame(ModuleInstance const& module, Value* locals_ptr, Expression const& expression, size_t arity, bool owns_locals = false)
- : m_module(module)
- , m_locals_ptr(locals_ptr)
- , m_expression(expression)
- , m_arity(arity)
- , m_owns_locals(owns_locals)
- {
- }
-
- Frame(Frame&& other)
- : m_module(other.m_module)
- , m_locals_ptr(other.m_locals_ptr)
- , m_expression(other.m_expression)
- , m_arity(other.m_arity)
- , m_label_index(other.m_label_index)
- , m_owns_locals(other.m_owns_locals)
- , m_compiled_fn_table(other.m_compiled_fn_table)
- {
- }
-
- Frame& operator=(Frame&&) = delete;
-
- Frame(Frame const&) = delete;
- Frame& operator=(Frame const&) = delete;
-
- auto& module() const { return m_module; }
- Value* locals_data() const { return m_locals_ptr; }
- bool owns_locals() const { return m_owns_locals; }
- auto& expression() const { return m_expression; }
- auto arity() const { return m_arity; }
- auto label_index() const { return m_label_index; }
- auto& label_index() { return m_label_index; }
-
- Vector<CompiledFunctionEntry> const* compiled_fn_table() const { return m_compiled_fn_table; }
- void set_compiled_fn_table(Vector<CompiledFunctionEntry> const* table) { m_compiled_fn_table = table; }
-
-private:
- ModuleInstance const& m_module;
- Value* m_locals_ptr { nullptr };
- Expression const& m_expression;
- size_t m_arity { 0 };
- size_t m_label_index { 0 };
- bool m_owns_locals { false };
- Vector<CompiledFunctionEntry> const* m_compiled_fn_table { nullptr };
-};
-
-using InstantiationResult = AK::ErrorOr<NonnullRefPtr<ModuleInstance>, InstantiationError>;
-
-struct HostVisitOps {
- Function<void(ExternallyManagedTrap&)> visit_trap;
-};
-
-class WASM_API AbstractMachine {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- explicit AbstractMachine(GC::Heap* heap = nullptr);
- ~AbstractMachine();
-
- GC::Heap& heap()
- {
- if (!m_heap) [[unlikely]]
- create_own_heap();
- return *m_heap;
- }
-
- // For embedders that decide on a (shared) heap after constructing the machine. Must
- // happen before any code runs.
- bool has_heap() const { return m_heap != nullptr; }
- void adopt_heap(GC::Heap&);
-
- // Validate a module; permanently sets the module's validity status.
- ErrorOr<void, ValidationError> validate(Module&, Optional<CompileCacheConfig> cache_config = {}, CompileToNative = CompileToNative::Yes);
- // Load and instantiate a module, and link it into this interpreter.
- InstantiationResult instantiate(Module const&, Vector<ExternValue>);
- Result invoke(FunctionAddress, Vector<Value, ArgumentsStaticSize>);
- Result invoke(Interpreter&, FunctionAddress, Vector<Value, ArgumentsStaticSize>);
-
- auto& store() const { return m_store; }
- auto& store() { return m_store; }
-
- void enable_instruction_count_limit() { m_should_limit_instruction_count = true; }
-
- void visit_external_resources(HostVisitOps const&);
-
-private:
- class InterpreterHandle {
- public:
- explicit InterpreterHandle(AbstractMachine& machine, Interpreter& interpreter)
- : m_machine(machine)
- , m_interpreter(interpreter)
- {
- m_machine.m_active_interpreters.set(&m_interpreter);
- }
-
- ~InterpreterHandle()
- {
- m_machine.m_active_interpreters.remove(&m_interpreter);
- }
-
- private:
- AbstractMachine& m_machine;
- Interpreter& m_interpreter;
- };
-
- [[nodiscard]] InterpreterHandle register_scoped(Interpreter& interpreter)
- {
- return InterpreterHandle(*this, interpreter);
- }
-
- Optional<InstantiationError> allocate_all_initial_phase(Module const&, ModuleInstance&, Vector<ExternValue>&, Vector<Value>& global_values, Vector<Value>& table_initial_values, Vector<FunctionAddress>& own_functions);
- Optional<InstantiationError> allocate_all_final_phase(Module const&, ModuleInstance&, Vector<Vector<Reference>>& elements);
-
- void create_own_heap();
-
- class RootsProvider final : public GC::ConservativeRangeProvider {
- public:
- AK_ALLOC_WITH_KMALLOC;
-
- RootsProvider(GC::Heap& heap, Store& store)
- : GC::ConservativeRangeProvider(heap)
- , m_store(store)
- {
- }
-
- private:
- virtual void for_each_conservative_range(AK::Function<void(ReadonlySpan<FlatPtr>)> const&) const override;
-
- Store& m_store;
- };
-
- Store m_store;
- OwnPtr<GC::Heap> m_owned_heap;
- GC::Heap* m_heap { nullptr };
- OwnPtr<RootsProvider> m_roots_provider;
- StackInfo m_stack_info;
- HashTable<Interpreter*> m_active_interpreters;
- bool m_should_limit_instruction_count { false };
-
- // Host functions may reenter Wasm, so retain typical nesting while bounding idle state.
- static constexpr size_t MAX_AVAILABLE_EXECUTION_STATES = 32;
- Vector<NonnullOwnPtr<BytecodeInterpreter>, MAX_AVAILABLE_EXECUTION_STATES> m_available_interpreters;
- Vector<NonnullOwnPtr<Configuration>, MAX_AVAILABLE_EXECUTION_STATES> m_available_configurations;
-};
-
-class WASM_API Linker {
-public:
- struct Name {
- ByteString module;
- ByteString name;
- ImportSection::Import::ImportDesc type;
- };
-
- explicit Linker(Module const& module)
- : m_module(module)
- {
- }
-
- // Link a module, the import 'module name' is ignored with this.
- void link(ModuleInstance const&);
-
- // Link a bunch of qualified values, also matches 'module name'.
- void link(HashMap<Name, ExternValue> const&);
-
- auto& unresolved_imports()
- {
- populate();
- return m_unresolved_imports;
- }
-
- AK::ErrorOr<Vector<ExternValue>, LinkError> finish();
-
-private:
- void populate();
-
- Module const& m_module;
- HashMap<Name, ExternValue> m_resolved_imports;
- HashTable<Name> m_unresolved_imports;
- Vector<Name> m_ordered_imports;
- Optional<LinkError> m_error;
-};
-
-}
-
-template<>
-struct AK::Traits<Wasm::Linker::Name> : public AK::DefaultTraits<Wasm::Linker::Name> {
- static constexpr bool is_trivial() { return false; }
- static unsigned hash(Wasm::Linker::Name const& entry) { return pair_int_hash(entry.module.hash(), entry.name.hash()); }
- static bool equals(Wasm::Linker::Name const& a, Wasm::Linker::Name const& b) { return a.name == b.name && a.module == b.module; }
-};
-
-template<>
-struct AK::Traits<Wasm::Value> : public AK::DefaultTraits<Wasm::Value> {
- static constexpr bool is_trivial() { return true; }
-};
diff --git a/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.cpp b/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.cpp
deleted file mode 100644
index 89823c8e02a..00000000000
--- a/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.cpp
+++ /dev/null
@@ -1,8699 +0,0 @@
-/*
- * Copyright (c) 2021-2025, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Bitmap.h>
-#include <AK/ByteReader.h>
-#include <AK/Debug.h>
-#include <AK/Endian.h>
-#include <AK/GenericShorthands.h>
-#include <AK/MemoryStream.h>
-#include <AK/NumericLimits.h>
-#include <AK/QuickSort.h>
-#include <AK/RedBlackTree.h>
-#include <AK/SIMDExtras.h>
-#include <AK/SaturatingMath.h>
-#include <AK/ScopeGuard.h>
-#include <AK/ScopedValueRollback.h>
-#include <AK/Time.h>
-#include <AK/TypeCasts.h>
-#include <LibCore/File.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
-#include <LibWasm/AbstractMachine/Configuration.h>
-#include <LibWasm/AbstractMachine/Operators.h>
-#include <LibWasm/Opcode.h>
-#include <LibWasm/Printer/Printer.h>
-#include <LibWasm/Types.h>
-#include <setjmp.h>
-
-#if defined(AK_OS_WINDOWS)
-# include <AK/Windows.h>
-#else
-# include <signal.h>
-# include <unistd.h>
-# if defined(AK_OS_MACOS)
-# include <sys/ucontext.h>
-# else
-# include <ucontext.h>
-# endif
-#endif
-
-using namespace AK::SIMD;
-
-namespace {
-
-enum class CompiledFaultKind : u8 {
- None,
- Memory,
- CraneliftTrap,
-};
-
-struct CompiledFaultRecoveryContext {
- Wasm::BytecodeInterpreter* interpreter { nullptr };
- Wasm::Configuration* configuration { nullptr };
- CompiledFaultRecoveryContext* previous { nullptr };
- jmp_buf jump_buffer;
- bool faulted { false };
- CompiledFaultKind fault_kind { CompiledFaultKind::None };
- u8 cranelift_trap_code { 0 };
-};
-
-thread_local CompiledFaultRecoveryContext* s_compiled_fault_recovery = nullptr;
-
-#if WASM_COMPILED_FAULT_RECOVERY_SUPPORTED
-
-static StringView cranelift_trap_message(u8 trap_code)
-{
- // Cranelift reserves trap codes at the high end of u8:
- // stack_overflow=251, int_overflow=252, heap_oob=253, int_divz=254, bad_toint=255.
- switch (trap_code) {
- case 251:
- return Wasm::Constants::stack_exhaustion_message;
- case 252:
- case 254:
- return "Integer division overflow"sv;
- case 253:
- return "Memory access out of bounds"sv;
- case 255:
- return "Truncation out of range"sv;
- default:
- return "unreachable executed"sv;
- }
-}
-
-static bool is_wasm_memory_fault(Wasm::Configuration& configuration, void* address)
-{
- auto const& memories = configuration.frame().module().memories();
- for (auto const& memory_address : memories) {
- auto* memory = configuration.store().unsafe_get(memory_address);
- if (memory && memory->contains_virtual_address(address))
- return true;
- }
- return false;
-}
-
-extern "C" {
-[[noreturn, gnu::used]] static void wasm_compiled_fault_trampoline()
-{
- auto* recovery = s_compiled_fault_recovery;
- // NOTE: The segfault handler redirects sigreturn flow to here, which then runs on the normal stack.
- longjmp(recovery->jump_buffer, 1);
-}
-}
-
-# if defined(AK_OS_WINDOWS)
-
-static LONG WINAPI compiled_fault_exception_handler(EXCEPTION_POINTERS* exception_info)
-{
- if (exception_info->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION
- && exception_info->ExceptionRecord->ExceptionCode != EXCEPTION_IN_PAGE_ERROR)
- return EXCEPTION_CONTINUE_SEARCH;
-
- auto* fault_address = reinterpret_cast<void*>(exception_info->ExceptionRecord->ExceptionInformation[1]);
- if (auto* recovery = s_compiled_fault_recovery; recovery && is_wasm_memory_fault(*recovery->configuration, fault_address)) {
- recovery->faulted = true;
- auto* ctx = exception_info->ContextRecord;
-# if ARCH(AARCH64)
- ctx->Pc = reinterpret_cast<DWORD64>(&wasm_compiled_fault_trampoline);
-# elif ARCH(X86_64)
- ctx->Rip = reinterpret_cast<DWORD64>(&wasm_compiled_fault_trampoline);
-# endif
- return EXCEPTION_CONTINUE_EXECUTION;
- }
- return EXCEPTION_CONTINUE_SEARCH;
-}
-
-static void install_compiled_fault_handlers()
-{
- static bool s_installed = false;
- if (s_installed)
- return;
- s_installed = true;
- AddVectoredExceptionHandler(1, compiled_fault_exception_handler);
-}
-
-# else
-
-static struct sigaction s_old_sigsegv;
-static struct sigaction s_old_sigbus;
-static struct sigaction s_old_sigill;
-static struct sigaction s_old_sigfpe;
-
-[[noreturn]] static void chain_fault_signal(int signal, siginfo_t* info, void* context, struct sigaction const& previous_action)
-{
- if (previous_action.sa_flags & SA_SIGINFO) {
- previous_action.sa_sigaction(signal, info, context);
- __builtin_unreachable();
- }
-
- if (previous_action.sa_handler == SIG_IGN)
- goto no_handler;
-
- if (previous_action.sa_handler != SIG_DFL) {
- previous_action.sa_handler(signal);
- __builtin_unreachable();
- }
-
- {
- struct sigaction default_action {};
- default_action.sa_handler = SIG_DFL;
- sigemptyset(&default_action.sa_mask);
- sigaction(signal, &default_action, nullptr);
- raise(signal);
- }
-
-no_handler:
- _exit(128 + signal);
-}
-
-static void compiled_fault_signal_handler(int signal, siginfo_t* info, void* context)
-{
- auto* recovery = s_compiled_fault_recovery;
- auto* uc = static_cast<ucontext_t*>(context);
-
- auto redirect_to_trampoline = [&] {
-# if defined(AK_OS_MACOS)
-# if ARCH(AARCH64)
- uc->uc_mcontext->__ss.__pc = reinterpret_cast<uintptr_t>(&wasm_compiled_fault_trampoline);
-# elif ARCH(X86_64)
- uc->uc_mcontext->__ss.__rip = reinterpret_cast<uintptr_t>(&wasm_compiled_fault_trampoline);
-# endif
-# else
-# if ARCH(AARCH64)
- uc->uc_mcontext.pc = reinterpret_cast<uintptr_t>(&wasm_compiled_fault_trampoline);
-# elif ARCH(X86_64)
- uc->uc_mcontext.gregs[REG_RIP] = reinterpret_cast<greg_t>(&wasm_compiled_fault_trampoline);
-# endif
-# endif
- };
-
- if (recovery && info && (signal == SIGSEGV || signal == SIGBUS) && is_wasm_memory_fault(*recovery->configuration, info->si_addr)) {
- recovery->faulted = true;
- recovery->fault_kind = CompiledFaultKind::Memory;
- // Redirect the resumed PC to our trampoline and return.
- // sigreturn (or the platform equivalent) will take the flow to the trampoline on the faulting thread's "normal" stack,
- // from where we can then longjmp to the recovery code.
- redirect_to_trampoline();
- return;
- }
-
- if (recovery && (signal == SIGILL || signal == SIGFPE)) {
-# if defined(AK_OS_MACOS)
-# if ARCH(AARCH64)
- auto pc = static_cast<FlatPtr>(uc->uc_mcontext->__ss.__pc);
-# elif ARCH(X86_64)
- auto pc = static_cast<FlatPtr>(uc->uc_mcontext->__ss.__rip);
-# else
- auto pc = static_cast<FlatPtr>(0);
-# endif
-# else
-# if ARCH(AARCH64)
- auto pc = static_cast<FlatPtr>(uc->uc_mcontext.pc);
-# elif ARCH(X86_64)
- auto pc = static_cast<FlatPtr>(uc->uc_mcontext.gregs[REG_RIP]);
-# else
- auto pc = static_cast<FlatPtr>(0);
-# endif
-# endif
-
- auto const& compiled = recovery->configuration->frame().expression().compiled_instructions;
- auto const code_start = compiled.cranelift_entry;
- auto const code_size = compiled.cranelift_code_size;
- if (compiled.cranelift_compiled && code_start != 0 && pc >= code_start && pc < code_start + code_size) {
- auto const offset = static_cast<u32>(pc - code_start);
- for (size_t i = 0; i < compiled.cranelift_trap_count; ++i) {
- auto const& trap = compiled.cranelift_traps[i];
- if (trap.offset != offset)
- continue;
-
- recovery->faulted = true;
- recovery->fault_kind = CompiledFaultKind::CraneliftTrap;
- recovery->cranelift_trap_code = trap.code;
- redirect_to_trampoline();
- return;
- }
- }
- }
-
- if (signal == SIGSEGV)
- chain_fault_signal(signal, info, context, s_old_sigsegv);
- if (signal == SIGILL)
- chain_fault_signal(signal, info, context, s_old_sigill);
- if (signal == SIGFPE)
- chain_fault_signal(signal, info, context, s_old_sigfpe);
- chain_fault_signal(signal, info, context, s_old_sigbus);
-}
-
-static void install_compiled_fault_handlers()
-{
- static bool s_installed = false;
- if (s_installed)
- return;
- s_installed = true;
- struct sigaction action {};
- action.sa_sigaction = compiled_fault_signal_handler;
- // Preserve alternate-stack crash handling when forwarding non-Wasm faults.
- action.sa_flags = SA_SIGINFO | SA_ONSTACK;
- sigemptyset(&action.sa_mask);
- sigaction(SIGSEGV, &action, &s_old_sigsegv);
- sigaction(SIGBUS, &action, &s_old_sigbus);
- sigaction(SIGILL, &action, &s_old_sigill);
- sigaction(SIGFPE, &action, &s_old_sigfpe);
-}
-
-# endif
-
-#else
-
-static void install_compiled_fault_handlers() { }
-
-#endif
-
-}
-
-#ifdef AK_COMPILER_CLANG
-# define TAILCALL [[clang::musttail]]
-# define HAS_TAILCALL
-#elif defined(AK_COMPILER_GCC)
-# if ((__GNUC__ > 15) || ((__GNUC__ == 15) && defined(NDEBUG) && !defined(HAS_ADDRESS_SANITIZER)))
-# define TAILCALL [[gnu::musttail]]
-# define HAS_TAILCALL
-# else
-# define TAILCALL
-# endif
-#else
-# define TAILCALL
-#endif
-
-// Disable direct threading when tail calls are not supported at all (gcc < 15);
-// as without guaranteed tailcall optimization we cannot ensure that the stack
-// will not grow uncontrollably.
-#if !defined(HAS_TAILCALL) || defined(HAS_ADDRESS_SANITIZER)
-constexpr static auto should_try_to_use_direct_threading = false;
-#else
-constexpr static auto should_try_to_use_direct_threading = true;
-#endif
-
-namespace Wasm {
-
-struct InstructionOperandCounts {
- ssize_t inputs;
- ssize_t outputs;
-};
-
-static InstructionOperandCounts instruction_operand_counts(OpCode opcode)
-{
- switch (opcode.value()) {
-#define XM(name, _, ins, outs) \
- case Wasm::Instructions::name.value(): \
- return { ins, outs };
-
- ENUMERATE_WASM_OPCODES(XM)
-#undef XM
- }
-
- VERIFY_NOT_REACHED();
-}
-
-constexpr auto regname = [](auto regnum) -> ByteString {
- if (regnum == Dispatch::Stack)
- return "stack";
- if (regnum >= Dispatch::CallRecord)
- return ByteString::formatted("cr{}", to_underlying(regnum) - to_underlying(Dispatch::CallRecord));
- return ByteString::formatted("reg{}", to_underlying(regnum));
-};
-
-template<typename T>
-struct ConvertToRaw {
- T operator()(T value)
- {
- return LittleEndian<T>(value);
- }
-};
-
-template<>
-struct ConvertToRaw<float> {
- u32 operator()(float value) const { return bit_cast<LittleEndian<u32>>(value); }
-};
-
-template<>
-struct ConvertToRaw<double> {
- u64 operator()(double value) const { return bit_cast<LittleEndian<u64>>(value); }
-};
-
-// Memory address operands are typed as the memory's address type (proposal 'memory64').
-// 32-bit addresses are stored sign-extended in the Value, so they must be truncated back to u32; 64-bit addresses are used as-is.
-static ALWAYS_INLINE u64 memory_base_address(MemoryInstance const& memory, Value const& entry)
-{
- auto base = entry.to<u64>();
- if (memory.type().limits().address_type() == AddressType::I32)
- return static_cast<u32>(base);
- return base;
-}
-
-#define TRAP_IF_NOT(x, ...) \
- do { \
- if (trap_if_not(x, #x##sv __VA_OPT__(, ) __VA_ARGS__)) { \
- dbgln_if(WASM_TRACE_DEBUG, "Trapped because {} failed, at line {}", #x, __LINE__); \
- return Outcome::Return; \
- } \
- } while (false)
-
-#define TRAP_IN_LOOP_IF_NOT(x, ...) \
- do { \
- if (interpreter.trap_if_not(x, #x##sv __VA_OPT__(, ) __VA_ARGS__)) { \
- dbgln_if(WASM_TRACE_DEBUG, "Trapped in loop because {} failed, at line {}", #x, __LINE__); \
- return Outcome::Return; \
- } \
- } while (false)
-
-static constexpr u64 trace_missing = NumericLimits<u64>::max();
-
-#define LOG_INSN_UNGUARDED \
- do { \
- LOAD_ADDRESSES(); \
- auto [in_count, out_count] = instruction_operand_counts(instruction->opcode()); \
- u64 src_lows[3] { trace_missing, trace_missing, trace_missing }; \
- u64 src_highs[3] { trace_missing, trace_missing, trace_missing }; \
- auto saved_stack_size = configuration.value_stack().size(); \
- ScopeGuard restore_stack { [&] { configuration.value_stack().restore_size(saved_stack_size); } }; \
- for (ssize_t i = 0; i < in_count; ++i) { \
- auto value = configuration.take_source<source_address_mix>(i, addresses.sources); \
- src_lows[i] = value.value().low(); \
- src_highs[i] = value.value().high(); \
- } \
- warnln("WASMTRACE ip={} op={} in={} out={} depth={} stack={} dst={} s0={} s0l={:x} s0h={:x} s1={} s1l={:x} s1h={:x} s2={} s2l={:x} s2h={:x} r0l={:x} r0h={:x} r1l={:x} r1h={:x} r2l={:x} r2h={:x} r3l={:x} r3h={:x}", \
- short_ip.current_ip_value, instruction_name(instruction->opcode()), in_count, out_count, configuration.depth(), configuration.value_stack().size(), \
- to_underlying(addresses.destination), \
- to_underlying(addresses.sources[0]), src_lows[0], src_highs[0], \
- to_underlying(addresses.sources[1]), src_lows[1], src_highs[1], \
- to_underlying(addresses.sources[2]), src_lows[2], src_highs[2], \
- configuration.regs[0].value().low(), configuration.regs[0].value().high(), \
- configuration.regs[1].value().low(), configuration.regs[1].value().high(), \
- configuration.regs[2].value().low(), configuration.regs[2].value().high(), \
- configuration.regs[3].value().low(), configuration.regs[3].value().high()); \
- } while (0)
-
-#define LOG_INSN \
- do { \
- if constexpr (WASM_TRACE_DEBUG) { \
- LOG_INSN_UNGUARDED; \
- } \
- } while (0)
-
-#define LOAD_ADDRESSES() auto addresses = addresses_ptr[short_ip.current_ip_value]
-
-void BytecodeInterpreter::interpret(Configuration& configuration)
-{
- m_trap = Empty {};
- auto& expression = configuration.frame().expression();
- auto const native_entry = cranelift_entry_acquire(expression.compiled_instructions);
- // We may end up running native code either at entry (native_entry != 0) or mid-loop via a tier-up checkpoint, so install fault recovery in either case.
- bool const may_run_native = native_entry != 0 || expression.compiled_instructions.has_tier_up_checkpoints;
- CompiledFaultRecoveryContext compiled_fault_recovery;
- bool did_install_compiled_fault_recovery = false;
- if (may_run_native) {
- // A host function can reenter Wasm with a different configuration (and therefore a different memory).
- // Keep the innermost configuration active so its compiled faults are classified and recovered correctly.
- install_compiled_fault_handlers();
- compiled_fault_recovery.interpreter = this;
- compiled_fault_recovery.configuration = &configuration;
- compiled_fault_recovery.previous = s_compiled_fault_recovery;
- s_compiled_fault_recovery = &compiled_fault_recovery;
- did_install_compiled_fault_recovery = true;
- if (setjmp(compiled_fault_recovery.jump_buffer) != 0) {
- s_compiled_fault_recovery = compiled_fault_recovery.previous;
- if (compiled_fault_recovery.fault_kind == CompiledFaultKind::CraneliftTrap)
- m_trap = Trap::from_string(cranelift_trap_message(compiled_fault_recovery.cranelift_trap_code));
- else
- m_trap = Trap::from_string("Memory access out of bounds");
- return;
- }
- }
- if (native_entry != 0) {
- (void)run_native_entry(configuration);
- goto done;
- }
- {
- auto const should_limit_instruction_count = configuration.should_limit_instruction_count();
- if (!expression.compiled_instructions.dispatches.is_empty()) {
- if (expression.compiled_instructions.direct) {
- if (should_limit_instruction_count) {
- interpret_impl<true, true, true>(configuration, expression);
- goto done;
- }
- interpret_impl<true, false, true>(configuration, expression);
- goto done;
- }
- interpret_impl<true, false, false>(configuration, expression);
- goto done;
- }
- if (should_limit_instruction_count) {
- interpret_impl<false, true, false>(configuration, expression);
- goto done;
- }
- interpret_impl<false, false, false>(configuration, expression);
- }
-
-done:
- if (did_install_compiled_fault_recovery)
- s_compiled_fault_recovery = compiled_fault_recovery.previous;
-}
-
-constexpr static u32 default_sources_and_destination = (to_underlying(Dispatch::RegisterOrStack::Stack) | (to_underlying(Dispatch::RegisterOrStack::Stack) << 2) | (to_underlying(Dispatch::RegisterOrStack::Stack) << 4));
-
-template<u64 opcode>
-struct InstructionHandler { };
-
-struct ShortenedIP {
- u32 current_ip_value;
-};
-
-static_assert(sizeof(ShortenedIP) == sizeof(u32));
-
-#define HANDLER_PARAMS(S) \
- S(BytecodeInterpreter&, interpreter), \
- S(Configuration&, configuration), \
- S(Instruction const*, instruction), \
- S(ShortenedIP, short_ip), \
- S(Dispatch const*, cc), \
- S(SourcesAndDestination const*, addresses_ptr)
-
-#define DECOMPOSE_PARAMS(t, n) [[maybe_unused]] t n
-#define DECOMPOSE_PARAMS_NAME_ONLY(t, n) n
-#define DECOMPOSE_PARAMS_TYPE_ONLY(t, ...) t
-
-Outcome BytecodeInterpreter::run_compiled_function_direct(Configuration& configuration)
-{
- m_trap = Empty {};
- auto& expression = configuration.frame().expression();
- VERIFY(expression.compiled_instructions.direct);
- auto const* cc = expression.compiled_instructions.dispatches.data();
- auto const* addresses_ptr = expression.compiled_instructions.src_dst_mappings.data();
- ShortenedIP short_ip { .current_ip_value = 0 };
- auto const instruction = cc[0].instruction;
- auto const handler = bit_cast<Outcome (*)(HANDLER_PARAMS(DECOMPOSE_PARAMS_TYPE_ONLY))>(cc[0].handler_ptr);
- return handler(*this, configuration, instruction, short_ip, cc, addresses_ptr);
-}
-
-// Enter the Cranelift-compiled native code for this function. The native entry conforms to the
-// same handler ABI as the direct-threaded interpreter, but lives in CompiledInstructions::cranelift_entry
-// (dispatches[0].handler_ptr stays the C++ handler). Caller must have confirmed the entry is non-zero.
-Outcome BytecodeInterpreter::run_native_entry(Configuration& configuration)
-{
- m_trap = Empty {};
- auto& expression = configuration.frame().expression();
- auto const* cc = expression.compiled_instructions.dispatches.data();
- auto const* addresses_ptr = expression.compiled_instructions.src_dst_mappings.data();
- ShortenedIP short_ip { .current_ip_value = 0 };
- auto const instruction = cc[0].instruction;
- auto const handler = bit_cast<Outcome (*)(HANDLER_PARAMS(DECOMPOSE_PARAMS_TYPE_ONLY))>(cranelift_entry_acquire(expression.compiled_instructions));
- return handler(*this, configuration, instruction, short_ip, cc, addresses_ptr);
-}
-
-#define HANDLE_INSTRUCTION(name, ...) \
- template<> \
- struct InstructionHandler<Instructions::name.value()> { \
- template<bool HasDynamicInsnLimit, typename Continue, SourceAddressMix source_address_mix> \
- static Outcome operator()(HANDLER_PARAMS(DECOMPOSE_PARAMS)); \
- }; \
- template<bool HasDynamicInsnLimit, typename Continue, SourceAddressMix source_address_mix> \
- FLATTEN Outcome InstructionHandler<Instructions::name.value()>::operator()(HANDLER_PARAMS(DECOMPOSE_PARAMS))
-#define ALIAS_INSTRUCTION(new_name, existing_name) \
- template<> \
- struct InstructionHandler<Instructions::new_name.value()> { \
- template<bool HasDynamicInsnLimit, typename Continue, SourceAddressMix source_address_mix> \
- FLATTEN static Outcome operator()(HANDLER_PARAMS(DECOMPOSE_PARAMS)) \
- { \
- TAILCALL return InstructionHandler<Instructions::existing_name.value()>::operator()<HasDynamicInsnLimit, Continue, source_address_mix>( \
- HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY)); \
- } \
- };
-
-struct Continue {
- ALWAYS_INLINE FLATTEN static Outcome operator()(BytecodeInterpreter& interpreter, Configuration& configuration, Instruction const*, ShortenedIP short_ip, Dispatch const* cc, SourcesAndDestination const* addresses_ptr)
- {
- short_ip.current_ip_value++;
-
- auto const instruction = cc[short_ip.current_ip_value].instruction;
- auto const handler = bit_cast<Outcome (*)(HANDLER_PARAMS(DECOMPOSE_PARAMS_TYPE_ONLY))>(cc[short_ip.current_ip_value].handler_ptr);
- TAILCALL return handler(interpreter, configuration, instruction, short_ip, cc, addresses_ptr);
- }
-};
-
-struct Skip {
- static Outcome operator()(BytecodeInterpreter&, Configuration&, Instruction const*, ShortenedIP short_ip, Dispatch const*, SourcesAndDestination const*)
- {
- return static_cast<Outcome>(short_ip.current_ip_value);
- }
-};
-
-#define continue_(...) Continue::operator()(__VA_ARGS__)
-
-HANDLE_INSTRUCTION(synthetic_end_expression)
-{
- LOG_INSN;
- return Outcome::Return;
-}
-
-HANDLE_INSTRUCTION(f64_reinterpret_i64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, double, Operators::Reinterpret<double>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_extend8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, i32, Operators::SignExtend<i8>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_extend16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, i32, Operators::SignExtend<i16>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_extend8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i64, Operators::SignExtend<i8>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_extend16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i64, Operators::SignExtend<i16>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_extend32_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i64, Operators::SignExtend<i32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_sat_f32_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i32, Operators::SaturatingTruncate<i32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_sat_f32_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i32, Operators::SaturatingTruncate<u32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_sat_f64_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i32, Operators::SaturatingTruncate<i32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_sat_f64_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i32, Operators::SaturatingTruncate<u32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_sat_f32_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i64, Operators::SaturatingTruncate<i64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_sat_f32_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i64, Operators::SaturatingTruncate<u64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_sat_f64_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i64, Operators::SaturatingTruncate<i64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_sat_f64_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i64, Operators::SaturatingTruncate<u64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_const)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(instruction->arguments().get<u128>()), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<u128, u128, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load8x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_mxn<8, 8, MakeSigned>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load8x8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_mxn<8, 8, MakeUnsigned>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load16x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_mxn<16, 4, MakeSigned>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load16x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_mxn<16, 4, MakeUnsigned>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load32x2_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_mxn<32, 2, MakeSigned>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load32x2_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_mxn<32, 2, MakeUnsigned>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load8_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_m_splat<8>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load16_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_m_splat<16>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load32_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_m_splat<32>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load64_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_m_splat<64>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- interpreter.pop_and_push_m_splat<8, NativeIntegralType>(configuration, *instruction, addresses);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- interpreter.pop_and_push_m_splat<16, NativeIntegralType>(configuration, *instruction, addresses);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- interpreter.pop_and_push_m_splat<32, NativeIntegralType>(configuration, *instruction, addresses);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- interpreter.pop_and_push_m_splat<64, NativeIntegralType>(configuration, *instruction, addresses);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- interpreter.pop_and_push_m_splat<32, NativeFloatingType>(configuration, *instruction, addresses);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_splat)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- interpreter.pop_and_push_m_splat<64, NativeFloatingType>(configuration, *instruction, addresses);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_shuffle)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& arg = instruction->arguments().get<Instruction::ShuffleArgument>();
- auto b = interpreter.pop_vector<u8, MakeUnsigned>(configuration, 0, addresses);
- auto a = interpreter.pop_vector<u8, MakeUnsigned>(configuration, 1, addresses);
- using VectorType = Native128ByteVectorOf<u8, MakeUnsigned>;
- VectorType result;
- for (size_t i = 0; i < 16; ++i)
- if (arg.lanes[i] < 16)
- result[i] = a[arg.lanes[i]];
- else
- result[i] = b[arg.lanes[i] - 16];
- configuration.push_to_destination<source_address_mix>(Value(bit_cast<u128>(result)), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_store)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<u128, u128>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_ge)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, i32, Operators::GreaterThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_clz)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, i32, Operators::CountLeadingZeros, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_ctz)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, i32, Operators::CountTrailingZeros, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_popcnt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, i32, Operators::PopCount, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::Add, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::Subtract, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::Multiply, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_divs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::Divide, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_divu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::Divide, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_rems)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::Modulo, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_remu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::Modulo, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_and)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::BitAnd, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_or)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::BitOr, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_xor)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::BitXor, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_shl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::BitShiftLeft, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_shrs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::BitShiftRight, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_shru)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::BitShiftRight, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_rotl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::BitRotateLeft, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_rotr)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::BitRotateRight, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_clz)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i64, Operators::CountLeadingZeros, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_ctz)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i64, Operators::CountTrailingZeros, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_popcnt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i64, Operators::PopCount, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::Add, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::Subtract, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::Multiply, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_divs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i64, Operators::Divide, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_divu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::Divide, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_rems)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i64, Operators::Modulo, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_remu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::Modulo, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_and)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i64, Operators::BitAnd, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_or)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i64, Operators::BitOr, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_xor)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i64, Operators::BitXor, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_shl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::BitShiftLeft, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_shrs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i64, Operators::BitShiftRight, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_shru)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::BitShiftRight, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_rotl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::BitRotateLeft, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_rotr)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i64, Operators::BitRotateRight, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, float, Operators::Absolute, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, float, Operators::Negate, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_ceil)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, float, Operators::Ceil, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_floor)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, float, Operators::Floor, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_trunc)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, float, Operators::Truncate, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_nearest)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, float, Operators::NearbyIntegral, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_sqrt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, float, Operators::SquareRoot, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, float, Operators::Add, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, float, Operators::Subtract, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, float, Operators::Multiply, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_div)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, float, Operators::Divide, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_min)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, float, Operators::Minimum, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_max)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, float, Operators::Maximum, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_copysign)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, float, Operators::CopySign, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, double, Operators::Absolute, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, double, Operators::Negate, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_ceil)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, double, Operators::Ceil, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_floor)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, double, Operators::Floor, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_trunc)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, double, Operators::Truncate, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_nearest)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, double, Operators::NearbyIntegral, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_sqrt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, double, Operators::SquareRoot, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, double, Operators::Add, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, double, Operators::Subtract, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, double, Operators::Multiply, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_div)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, double, Operators::Divide, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_min)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, double, Operators::Minimum, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_max)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, double, Operators::Maximum, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_copysign)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, double, Operators::CopySign, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_wrap_i64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i32, Operators::Wrap<i32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_sf32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i32, Operators::CheckedTruncate<i32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_uf32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i32, Operators::CheckedTruncate<u32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_sf64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i32, Operators::CheckedTruncate<i32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_trunc_uf64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i32, Operators::CheckedTruncate<u32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_sf32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i64, Operators::CheckedTruncate<i64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_uf32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i64, Operators::CheckedTruncate<u64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_sf64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i64, Operators::CheckedTruncate<i64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_trunc_uf64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i64, Operators::CheckedTruncate<u64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_extend_si32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, i64, Operators::Extend<i64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_extend_ui32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u32, i64, Operators::Extend<i64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_convert_si32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, float, Operators::Convert<float>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_convert_ui32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u32, float, Operators::Convert<float>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_convert_si64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, float, Operators::Convert<float>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_convert_ui64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u64, float, Operators::Convert<float>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_demote_f64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, float, Operators::Demote, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_convert_si32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, double, Operators::Convert<double>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_convert_ui32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u32, double, Operators::Convert<double>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_convert_si64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, double, Operators::Convert<double>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_convert_ui64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u64, double, Operators::Convert<double>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_promote_f32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, double, Operators::Promote, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_reinterpret_f32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<float, i32, Operators::Reinterpret<i32>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_reinterpret_f64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<double, i64, Operators::Reinterpret<i64>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_reinterpret_i32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, float, Operators::Reinterpret<float>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(local_get)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(configuration.local(instruction->local_index()), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-#define HANDLE_SPECIALIZED_LOCAL_GET(N) \
- HANDLE_INSTRUCTION(synthetic_local_get_##N) \
- { \
- LOG_INSN; \
- LOAD_ADDRESSES(); \
- configuration.push_to_destination<source_address_mix>(configuration.local(N), addresses.destination); \
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY)); \
- }
-
-HANDLE_SPECIALIZED_LOCAL_GET(0)
-HANDLE_SPECIALIZED_LOCAL_GET(1)
-HANDLE_SPECIALIZED_LOCAL_GET(2)
-HANDLE_SPECIALIZED_LOCAL_GET(3)
-HANDLE_SPECIALIZED_LOCAL_GET(4)
-HANDLE_SPECIALIZED_LOCAL_GET(5)
-HANDLE_SPECIALIZED_LOCAL_GET(6)
-HANDLE_SPECIALIZED_LOCAL_GET(7)
-
-HANDLE_INSTRUCTION(synthetic_argument_get)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(configuration.local(instruction->local_index()), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_const)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(instruction->arguments().unsafe_get<i32>()), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_add2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(static_cast<i32>(Operators::Add {}(
- configuration.local(instruction->local_index()).to<u32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u32>()))),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_addconstlocal)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(static_cast<i32>(Operators::Add {}(configuration.local(instruction->local_index()).to<u32>(), instruction->arguments().unsafe_get<i32>()))), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_andconstlocal)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(Operators::BitAnd {}(configuration.local(instruction->local_index()).to<i32>(), instruction->arguments().unsafe_get<i32>())), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_sub2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(static_cast<i32>(Operators::Subtract {}(
- configuration.local(instruction->local_index()).to<u32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u32>()))),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_mul2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(static_cast<i32>(Operators::Multiply {}(
- configuration.local(instruction->local_index()).to<u32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u32>()))),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_and2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitAnd {}(
- configuration.local(instruction->local_index()).to<i32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<i32>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_or2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitOr {}(
- configuration.local(instruction->local_index()).to<i32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<i32>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_xor2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitXor {}(
- configuration.local(instruction->local_index()).to<i32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<i32>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_shl2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitShiftLeft {}(
- configuration.local(instruction->local_index()).to<u32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u32>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_shru2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitShiftRight {}(
- configuration.local(instruction->local_index()).to<u32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u32>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_shrs2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitShiftRight {}(
- configuration.local(instruction->local_index()).to<i32>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u32>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i32_storelocal)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.store_value(configuration, *instruction, ConvertToRaw<i32> {}(configuration.local(instruction->local_index()).to<i32>()), 0, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_storelocal)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.store_value(configuration, *instruction, ConvertToRaw<i64> {}(configuration.local(instruction->local_index()).to<i64>()), 0, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_add2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(static_cast<i64>(Operators::Add {}(
- configuration.local(instruction->local_index()).to<u64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u64>()))),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_addconstlocal)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(static_cast<i64>(Operators::Add {}(configuration.local(instruction->local_index()).to<u64>(), instruction->arguments().unsafe_get<i64>()))), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_andconstlocal)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(Operators::BitAnd {}(configuration.local(instruction->local_index()).to<i64>(), instruction->arguments().unsafe_get<i64>())), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_sub2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(static_cast<i64>(Operators::Subtract {}(
- configuration.local(instruction->local_index()).to<u64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u64>()))),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_mul2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(static_cast<i64>(Operators::Multiply {}(
- configuration.local(instruction->local_index()).to<u64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u64>()))),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_and2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitAnd {}(
- configuration.local(instruction->local_index()).to<i64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<i64>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_or2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitOr {}(
- configuration.local(instruction->local_index()).to<i64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<i64>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_xor2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitXor {}(
- configuration.local(instruction->local_index()).to<i64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<i64>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_shl2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitShiftLeft {}(
- configuration.local(instruction->local_index()).to<u64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u64>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_shru2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitShiftRight {}(
- configuration.local(instruction->local_index()).to<u64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u64>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_i64_shrs2local)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(
- Value(Operators::BitShiftRight {}(
- configuration.local(instruction->local_index()).to<i64>(),
- configuration.local(instruction->arguments().get<LocalIndex>()).to<u64>())),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_local_seti32_const)
-{
- LOG_INSN;
- configuration.local(instruction->local_index()) = Value(instruction->arguments().unsafe_get<i32>());
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_local_seti64_const)
-{
- LOG_INSN;
- configuration.local(instruction->local_index()) = Value(instruction->arguments().unsafe_get<i64>());
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_br_table_cont)
-{
- VERIFY_NOT_REACHED();
-}
-
-HANDLE_INSTRUCTION(synthetic_tier_up)
-{
- LOG_INSN;
- auto& ci = configuration.frame().expression().compiled_instructions;
- auto const native_entry = cranelift_entry_acquire(ci);
- if (native_entry != 0) {
- // If we have native code for this block, jump into it.
- // The code is set up such that the target checkpoint is recovered from short_ip and nothing else needs to be passed as the stack is empty and all live state is in the shared locals.
- auto const handler = bit_cast<Outcome (*)(HANDLER_PARAMS(DECOMPOSE_PARAMS_TYPE_ONLY))>(native_entry);
- return handler(interpreter, configuration, cc[short_ip.current_ip_value].instruction, short_ip, cc, addresses_ptr);
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_call_00)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_00(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_01)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_01(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_10)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_10(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_11)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_11(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_20)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_20(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_21)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_21(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_30)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_30(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_31)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "[{}] call_31(#{} -> {})", short_ip.current_ip_value, index.value(), address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingRegisters)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(unreachable)
-{
- LOG_INSN;
- interpreter.set_trap("Unreachable"sv);
- return Outcome::Return;
-}
-
-HANDLE_INSTRUCTION(nop)
-{
- LOG_INSN;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(local_set)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- configuration.local(instruction->local_index()) = configuration.take_source<source_address_mix>(0, addresses.sources);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_argument_set)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- configuration.local(instruction->local_index()) = configuration.take_source<source_address_mix>(0, addresses.sources);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-#define HANDLE_SPECIALIZED_LOCAL_SET(N) \
- HANDLE_INSTRUCTION(synthetic_local_set_##N) \
- { \
- LOG_INSN; \
- LOAD_ADDRESSES(); \
- configuration.local(N) = configuration.take_source<source_address_mix>(0, addresses.sources); \
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY)); \
- }
-
-HANDLE_SPECIALIZED_LOCAL_SET(0)
-HANDLE_SPECIALIZED_LOCAL_SET(1)
-HANDLE_SPECIALIZED_LOCAL_SET(2)
-HANDLE_SPECIALIZED_LOCAL_SET(3)
-HANDLE_SPECIALIZED_LOCAL_SET(4)
-HANDLE_SPECIALIZED_LOCAL_SET(5)
-HANDLE_SPECIALIZED_LOCAL_SET(6)
-HANDLE_SPECIALIZED_LOCAL_SET(7)
-
-HANDLE_INSTRUCTION(synthetic_local_copy)
-{
- LOG_INSN;
- // local.get a; local.set b -> copy local a to local b directly
- configuration.local(instruction->arguments().get<LocalIndex>()) = configuration.local(instruction->local_index());
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_const)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(instruction->arguments().unsafe_get<i64>()), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_const)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(instruction->arguments().unsafe_get<float>()), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_const)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- configuration.push_to_destination<source_address_mix>(Value(instruction->arguments().unsafe_get<double>()), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(block)
-{
- LOG_INSN;
- auto& args = instruction->arguments().unsafe_get<Instruction::StructuredInstructionArgs>();
- auto& meta = args.meta;
- auto label = Label(meta.arity, args.end_ip, configuration.value_stack().size() - meta.parameter_count);
- configuration.label_stack().unchecked_append(move(label));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(loop)
-{
- LOG_INSN;
- auto& args = instruction->arguments().get<Instruction::StructuredInstructionArgs>();
- size_t params = args.meta.parameter_count;
- configuration.label_stack().unchecked_append(Label(params, short_ip.current_ip_value + 1, configuration.value_stack().size() - params));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(if_)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().unsafe_get<Instruction::StructuredInstructionArgs>();
- auto& meta = args.meta;
-
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources).template to<i32>();
- auto end_label = Label(meta.arity, args.end_ip.value(), configuration.value_stack().size() - meta.parameter_count);
- if (value == 0) {
- if (args.else_ip().has_value()) {
- short_ip.current_ip_value = args.else_ip()->value() - 1;
- configuration.label_stack().unchecked_append(end_label);
- } else {
- short_ip.current_ip_value = args.end_ip.value();
- }
- } else {
- configuration.label_stack().unchecked_append(end_label);
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(structured_end)
-{
- LOG_INSN;
- configuration.label_stack().take_last();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(structured_else)
-{
- LOG_INSN;
- auto label = configuration.label_stack().take_last();
- // Jump to the end label
- short_ip.current_ip_value = label.continuation().value() - 1;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(return_)
-{
- LOG_INSN;
- configuration.label_stack().shrink(configuration.frame().label_index() + 1, true);
- // Clear intermediate working values from the value stack, keeping only the top .arity() (the return values) above
- // the function-level label's recorded stack_height. Without this, residual values pushed before the return are
- // leaked to the caller’s value stack — and accumulate across nested calls until heap-buffer-overflow.
- auto const& label = configuration.label_stack().unsafe_last();
- auto& vs = configuration.value_stack();
- if (vs.size() > label.stack_height() + label.arity())
- vs.remove(label.stack_height(), vs.size() - label.stack_height() - label.arity());
- return Outcome::Return;
-}
-
-HANDLE_INSTRUCTION(br)
-{
- LOG_INSN;
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, instruction->arguments().unsafe_get<Instruction::BranchArgs>().label, short_ip.current_ip_value).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_br_nostack)
-{
- LOG_INSN;
- auto& branch_args = instruction->arguments().unsafe_get<Instruction::BranchArgs>();
- auto label_idx = branch_args.label.value();
- auto& label_stack = configuration.label_stack();
- auto label_pos = label_stack.size() - 1 - label_idx;
- auto& label = label_stack.data()[label_pos];
- auto expected = label.stack_height() + label.arity();
- auto current = configuration.value_stack().size();
- if (current != expected) [[unlikely]]
- TAILCALL return InstructionHandler<Instructions::br.value()>::operator()<HasDynamicInsnLimit, Continue, source_address_mix>(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- label_stack.unsafe_shrink(label_pos + 1);
- short_ip.current_ip_value = label.continuation().value() - 1;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(br_if)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto cond = configuration.take_source<source_address_mix>(0, addresses.sources).template to<i32>();
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, instruction->arguments().unsafe_get<Instruction::BranchArgs>().label, short_ip.current_ip_value, cond != 0).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-NEVER_INLINE static Outcome synthetic_br_if_nostack_not_taken(HANDLER_PARAMS(DECOMPOSE_PARAMS))
-{
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, instruction->arguments().unsafe_get<Instruction::BranchArgs>().label, short_ip.current_ip_value).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_br_if_nostack)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto cond = configuration.take_source<source_address_mix>(0, addresses.sources).template to<i32>();
- if (cond == 0) {
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
- auto& branch_args = instruction->arguments().unsafe_get<Instruction::BranchArgs>();
- auto label_idx = branch_args.label.value();
- auto& label_stack = configuration.label_stack();
- auto label_pos = label_stack.size() - 1 - label_idx;
- auto& label = label_stack.data()[label_pos];
- auto expected = label.stack_height() + label.arity();
- auto current = configuration.value_stack().size();
- if (current != expected) [[unlikely]]
- return synthetic_br_if_nostack_not_taken(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- label_stack.unsafe_shrink(label_pos + 1);
- short_ip.current_ip_value = label.continuation().value() - 1;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(br_table)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::TableBranchArgs>();
- auto i = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
-
- if (i >= args.labels.size()) {
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, args.default_, short_ip.current_ip_value).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, args.labels[i], short_ip.current_ip_value).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(call)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "call({})", address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_with_record_0)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "call.with_record.0({})", address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingCallRecord)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(synthetic_call_with_record_1)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "call.with_record.1({})", address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectCall, BytecodeInterpreter::CallType::UsingCallRecord)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(return_call)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>();
- auto address = configuration.frame().module().functions()[index.value()];
- configuration.label_stack().shrink(configuration.frame().label_index(), true);
- dbgln_if(WASM_TRACE_DEBUG, "tail call({})", address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::DirectTailCall)) {
- default:
- // Some IP we have to continue from.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- addresses = { .sources_and_destination = default_sources_and_destination };
- cc = configuration.frame().expression().compiled_instructions.dispatches.data();
- addresses_ptr = configuration.frame().expression().compiled_instructions.src_dst_mappings.data();
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- case Outcome::Return:
- return Outcome::Return;
- }
-}
-
-HANDLE_INSTRUCTION(call_indirect)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::IndirectCallArgs>();
- auto table_address = configuration.frame().module().tables()[args.table.value()];
- auto table_instance = configuration.store().get(table_address);
- // bounds checked by verifier.
- auto src_value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto index = src_value.template to<i32>();
- TRAP_IN_LOOP_IF_NOT(index >= 0);
- TRAP_IN_LOOP_IF_NOT(static_cast<size_t>(index) < table_instance->elements().size());
- auto& element = table_instance->elements()[index];
- TRAP_IN_LOOP_IF_NOT(element.ref().template has<Reference::Func>());
- auto address = element.ref().template get<Reference::Func>().address;
- // https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-call-indirect-x-y
- auto const* type_actual = configuration.store().get(address)->visit([](auto& f) { return f.defined_type(); });
- auto const* type_expected = configuration.frame().module().canonical_types()[args.type.value()];
- TRAP_IN_LOOP_IF_NOT(type_actual && matches_defined_type(*type_actual, *type_expected));
-
- dbgln_if(WASM_TRACE_DEBUG, "call_indirect({} -> {})", index, address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::IndirectCall)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(return_call_indirect)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::IndirectCallArgs>();
- auto table_address = configuration.frame().module().tables()[args.table.value()];
- auto table_instance = configuration.store().get(table_address);
- // bounds checked by verifier.
- auto index = configuration.take_source<source_address_mix>(0, addresses.sources).template to<i32>();
- TRAP_IN_LOOP_IF_NOT(index >= 0);
- TRAP_IN_LOOP_IF_NOT(static_cast<size_t>(index) < table_instance->elements().size());
- auto& element = table_instance->elements()[index];
- TRAP_IN_LOOP_IF_NOT(element.ref().template has<Reference::Func>());
- auto address = element.ref().template get<Reference::Func>().address;
- // https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-call-indirect-x-y
- auto const* type_actual = configuration.store().get(address)->visit([](auto& f) { return f.defined_type(); });
- auto const* type_expected = configuration.frame().module().canonical_types()[args.type.value()];
- TRAP_IN_LOOP_IF_NOT(type_actual && matches_defined_type(*type_actual, *type_expected));
-
- configuration.label_stack().shrink(configuration.frame().label_index(), true);
- dbgln_if(WASM_TRACE_DEBUG, "tail call_indirect({} -> {})", index, address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::IndirectTailCall)) {
- default:
- // Some IP we have to continue from.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- addresses = { .sources_and_destination = default_sources_and_destination };
- cc = configuration.frame().expression().compiled_instructions.dispatches.data();
- addresses_ptr = configuration.frame().expression().compiled_instructions.src_dst_mappings.data();
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- case Outcome::Return:
- return Outcome::Return;
- }
-}
-
-HANDLE_INSTRUCTION(call_ref)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto type_index = instruction->arguments().get<TypeIndex>();
- FunctionAddress address;
- {
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto reference = value.template to<Reference>();
- TRAP_IN_LOOP_IF_NOT(!reference.ref().template has<Reference::Null>());
- address = reference.ref().template get<Reference::Func>().address;
- }
- // https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-call-ref-x
- auto const* type_actual = configuration.store().get(address)->visit([](auto& f) { return f.defined_type(); });
- auto const* type_expected = configuration.frame().module().canonical_types()[type_index.value()];
- TRAP_IN_LOOP_IF_NOT(type_actual && matches_defined_type(*type_actual, *type_expected));
-
- dbgln_if(WASM_TRACE_DEBUG, "call_ref({})", address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::IndirectCall)) {
- case Outcome::Return:
- return Outcome::Return;
- default:
- // A callee's thrown exception was caught by a try_table in this frame; continue at the catch's branch target.
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
-}
-
-HANDLE_INSTRUCTION(return_call_ref)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto type_index = instruction->arguments().get<TypeIndex>();
- FunctionAddress address;
- {
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto reference = value.template to<Reference>();
- TRAP_IN_LOOP_IF_NOT(!reference.ref().template has<Reference::Null>());
- address = reference.ref().template get<Reference::Func>().address;
- }
- auto const* type_actual = configuration.store().get(address)->visit([](auto& f) { return f.defined_type(); });
- auto const* type_expected = configuration.frame().module().canonical_types()[type_index.value()];
- TRAP_IN_LOOP_IF_NOT(type_actual && matches_defined_type(*type_actual, *type_expected));
-
- configuration.label_stack().shrink(configuration.frame().label_index(), true);
- dbgln_if(WASM_TRACE_DEBUG, "tail call_ref({})", address.value());
- switch (auto const outcome = interpreter.call_address(configuration, address, addresses, BytecodeInterpreter::CallAddressSource::IndirectTailCall)) {
- default:
- short_ip.current_ip_value = to_underlying(outcome) - 1;
- addresses = { .sources_and_destination = default_sources_and_destination };
- cc = configuration.frame().expression().compiled_instructions.dispatches.data();
- addresses_ptr = configuration.frame().expression().compiled_instructions.src_dst_mappings.data();
- [[fallthrough]];
- case Outcome::Continue:
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- case Outcome::Return:
- return Outcome::Return;
- }
-}
-
-HANDLE_INSTRUCTION(i32_load)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<i32, i32, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_load)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<i64, i64, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_load)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<float, float, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_load)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<double, double, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_load8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<i8, i32, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_load8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<u8, i32, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_load16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<i16, i32, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_load16_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<u16, i32, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_load8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<i8, i64, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_load8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<u8, i64, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_load16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<i16, i64, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_load16_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<u16, i64, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_load32_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<i32, i64, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_load32_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push<u32, i64, source_address_mix>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_store)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<i32, i32>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_store)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<i64, i64>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_store)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<float, float>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_store)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<double, double>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_store8)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<i32, i8>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_store16)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<i32, i16>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_store8)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<i64, i8>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_store16)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<i64, i16>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_store32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store<i64, i32>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(local_tee)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto value = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- auto local_index = instruction->local_index();
- dbgln_if(WASM_TRACE_DEBUG, "stack:peek -> locals({})", local_index.value());
- configuration.local(local_index) = value;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(synthetic_argument_tee)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto value = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- auto local_index = instruction->local_index();
- dbgln_if(WASM_TRACE_DEBUG, "stack:peek -> locals({})", local_index.value());
- configuration.local(local_index) = value;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(global_get)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto global_index = instruction->arguments().get<GlobalIndex>();
- // This check here is for const expressions. In non-const expressions,
- // a validation error would have been thrown.
- TRAP_IN_LOOP_IF_NOT(global_index < configuration.frame().module().globals().size());
- auto address = configuration.frame().module().globals()[global_index.value()];
- dbgln_if(WASM_TRACE_DEBUG, "global({}) -> stack", address.value());
- auto global = configuration.store().get(address);
- configuration.push_to_destination<source_address_mix>(global->value(), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(global_set)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto global_index = instruction->arguments().get<GlobalIndex>();
- auto address = configuration.frame().module().globals()[global_index.value()];
- // bounds checked by verifier.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- dbgln_if(WASM_TRACE_DEBUG, "stack -> global({})", address.value());
- auto global = configuration.store().get(address);
- global->set_value(value);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(memory_size)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().unsafe_get<Instruction::MemoryIndexArgument>();
- auto address = configuration.frame().module().memories().data()[args.memory_index.value()];
- auto instance = configuration.store().get(address);
- auto pages = instance->size() / Constants::page_size;
- dbgln_if(WASM_TRACE_DEBUG, "memory.size -> stack({})", pages);
- auto result = instance->type().limits().address_type() == AddressType::I32
- ? Value(static_cast<i32>(pages))
- : Value(static_cast<i64>(pages));
- configuration.push_to_destination<source_address_mix>(result, addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(memory_grow)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().unsafe_get<Instruction::MemoryIndexArgument>();
- auto address = configuration.frame().module().memories().data()[args.memory_index.value()];
- auto instance = configuration.store().get(address);
- u64 old_pages = instance->size() / Constants::page_size;
- auto& entry = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- bool const is_address32 = instance->type().limits().address_type() == AddressType::I32;
- auto new_pages = entry.template to<u64>();
- if (is_address32)
- new_pages = static_cast<u32>(new_pages);
- dbgln_if(WASM_TRACE_DEBUG, "memory.grow({}), previously {} pages...", new_pages, old_pages);
- Checked<u64> size_to_grow { new_pages };
- size_to_grow *= Constants::page_size;
- if (!size_to_grow.has_overflow() && instance->grow(size_to_grow.value()))
- entry = is_address32 ? Value(static_cast<i32>(old_pages)) : Value(static_cast<i64>(old_pages));
- else
- entry = is_address32 ? Value(static_cast<i32>(-1)) : Value(static_cast<i64>(-1));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// Proposal "threads"
-struct AtomicAccess {
- MemoryInstance* memory;
- u64 address;
-};
-
-static ALWAYS_INLINE Optional<AtomicAccess> resolve_atomic_access(BytecodeInterpreter& interpreter, Configuration& configuration, Instruction::MemoryArgument const& arg, Value const& base_value, size_t access_size)
-{
- auto const& memory_address = configuration.frame().module().memories().data()[arg.memory_index.value()];
- auto* memory = configuration.store().unsafe_get(memory_address);
- Checked<u64> address { memory_base_address(*memory, base_value) };
- address += arg.offset;
- Checked<u64> end_address { address };
- end_address += access_size;
- if (end_address.has_overflow() || end_address.value() > memory->size()) [[unlikely]] {
- interpreter.set_trap("Memory access out of bounds"sv);
- return {};
- }
- if (address.value() % access_size != 0) [[unlikely]] {
- interpreter.set_trap("Unaligned atomic memory access"sv);
- return {};
- }
- return AtomicAccess { memory, address.value() };
-}
-
-template<typename Callback>
-static ALWAYS_INLINE bool dispatch_atomic_width(Instruction::AtomicMemoryArgument::Width width, Callback&& callback)
-{
- using Width = Instruction::AtomicMemoryArgument::Width;
- switch (width) {
- case Width::I32:
- return callback.template operator()<u32, u32>();
- case Width::I64:
- return callback.template operator()<u64, u64>();
- case Width::I8As32:
- return callback.template operator()<u8, u32>();
- case Width::I16As32:
- return callback.template operator()<u16, u32>();
- case Width::I8As64:
- return callback.template operator()<u8, u64>();
- case Width::I16As64:
- return callback.template operator()<u16, u64>();
- case Width::I32As64:
- return callback.template operator()<u32, u64>();
- }
- VERIFY_NOT_REACHED();
-}
-
-HANDLE_INSTRUCTION(atomic_load)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& arg = instruction->arguments().unsafe_get<Instruction::AtomicMemoryArgument>();
- auto& entry = configuration.source_value<SourceAddressMix::Any>(0, addresses.sources); // bounds checked by verifier.
- auto trapped = dispatch_atomic_width(arg.width, [&]<typename MemoryType, typename StackType>() {
- auto access = resolve_atomic_access(interpreter, configuration, arg.memory, entry, sizeof(MemoryType));
- if (!access.has_value())
- return true;
- auto value = interpreter.read_value<MemoryType>({ access->memory->data().offset_pointer(access->address), sizeof(MemoryType) });
- entry = Value(static_cast<StackType>(value));
- return false;
- });
- if (trapped)
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(atomic_store)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& arg = instruction->arguments().unsafe_get<Instruction::AtomicMemoryArgument>();
- auto value = configuration.take_source<SourceAddressMix::Any>(0, addresses.sources); // bounds checked by verifier.
- auto base = configuration.take_source<SourceAddressMix::Any>(1, addresses.sources); // bounds checked by verifier.
- auto trapped = dispatch_atomic_width(arg.width, [&]<typename MemoryType, typename StackType>() {
- auto access = resolve_atomic_access(interpreter, configuration, arg.memory, base, sizeof(MemoryType));
- if (!access.has_value())
- return true;
- auto stored_value = static_cast<MemoryType>(value.to<StackType>());
- access->memory->data().overwrite(access->address, &stored_value, sizeof(MemoryType));
- return false;
- });
- if (trapped)
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(atomic_rmw)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- using Op = Instruction::AtomicMemoryArgument::Op;
- auto const& arg = instruction->arguments().unsafe_get<Instruction::AtomicMemoryArgument>();
- auto operand = configuration.take_source<SourceAddressMix::Any>(0, addresses.sources); // bounds checked by verifier.
- auto& entry = configuration.source_value<SourceAddressMix::Any>(1, addresses.sources); // bounds checked by verifier.
- auto trapped = dispatch_atomic_width(arg.width, [&]<typename MemoryType, typename StackType>() {
- auto access = resolve_atomic_access(interpreter, configuration, arg.memory, entry, sizeof(MemoryType));
- if (!access.has_value())
- return true;
- auto old_value = interpreter.read_value<MemoryType>({ access->memory->data().offset_pointer(access->address), sizeof(MemoryType) });
- auto rhs = static_cast<MemoryType>(operand.to<StackType>());
- MemoryType new_value;
- switch (arg.op) {
- case Op::Add:
- new_value = old_value + rhs;
- break;
- case Op::Sub:
- new_value = old_value - rhs;
- break;
- case Op::And:
- new_value = old_value & rhs;
- break;
- case Op::Or:
- new_value = old_value | rhs;
- break;
- case Op::Xor:
- new_value = old_value ^ rhs;
- break;
- case Op::Xchg:
- new_value = rhs;
- break;
- case Op::None:
- VERIFY_NOT_REACHED();
- }
- access->memory->data().overwrite(access->address, &new_value, sizeof(MemoryType));
- entry = Value(static_cast<StackType>(old_value));
- return false;
- });
- if (trapped)
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(atomic_rmw_cmpxchg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& arg = instruction->arguments().unsafe_get<Instruction::AtomicMemoryArgument>();
- auto replacement = configuration.take_source<SourceAddressMix::Any>(0, addresses.sources); // bounds checked by verifier.
- auto expected = configuration.take_source<SourceAddressMix::Any>(1, addresses.sources); // bounds checked by verifier.
- auto& entry = configuration.source_value<SourceAddressMix::Any>(2, addresses.sources); // bounds checked by verifier.
- auto trapped = dispatch_atomic_width(arg.width, [&]<typename MemoryType, typename StackType>() {
- auto access = resolve_atomic_access(interpreter, configuration, arg.memory, entry, sizeof(MemoryType));
- if (!access.has_value())
- return true;
- auto old_value = interpreter.read_value<MemoryType>({ access->memory->data().offset_pointer(access->address), sizeof(MemoryType) });
- // The comparison is done at the width of the memory access, so the expected value is wrapped.
- if (old_value == static_cast<MemoryType>(expected.to<StackType>())) {
- auto new_value = static_cast<MemoryType>(replacement.to<StackType>());
- access->memory->data().overwrite(access->address, &new_value, sizeof(MemoryType));
- }
- entry = Value(static_cast<StackType>(old_value));
- return false;
- });
- if (trapped)
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(memory_atomic_notify)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& arg = instruction->arguments().unsafe_get<Instruction::MemoryArgument>();
- (void)configuration.take_source<SourceAddressMix::Any>(0, addresses.sources); // count, bounds checked by verifier.
- auto& entry = configuration.source_value<SourceAddressMix::Any>(1, addresses.sources); // bounds checked by verifier.
- auto access = resolve_atomic_access(interpreter, configuration, arg, entry, sizeof(i32));
- if (!access.has_value())
- return Outcome::Return;
- // Nothing can be waiting on a non-shared memory, so there is never anything to wake up.
- entry = Value(static_cast<i32>(0));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(memory_atomic_wait32)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& arg = instruction->arguments().unsafe_get<Instruction::MemoryArgument>();
- (void)configuration.take_source<SourceAddressMix::Any>(0, addresses.sources); // timeout, bounds checked by verifier.
- (void)configuration.take_source<SourceAddressMix::Any>(1, addresses.sources); // expected, bounds checked by verifier.
- auto& entry = configuration.source_value<SourceAddressMix::Any>(2, addresses.sources); // bounds checked by verifier.
- auto access = resolve_atomic_access(interpreter, configuration, arg, entry, sizeof(i32));
- if (!access.has_value())
- return Outcome::Return;
- // Waiting on a non-shared memory always traps.
- interpreter.set_trap("Expected shared memory"sv);
- return Outcome::Return;
-}
-
-HANDLE_INSTRUCTION(memory_atomic_wait64)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& arg = instruction->arguments().unsafe_get<Instruction::MemoryArgument>();
- (void)configuration.take_source<SourceAddressMix::Any>(0, addresses.sources); // timeout, bounds checked by verifier.
- (void)configuration.take_source<SourceAddressMix::Any>(1, addresses.sources); // expected, bounds checked by verifier.
- auto& entry = configuration.source_value<SourceAddressMix::Any>(2, addresses.sources); // bounds checked by verifier.
- auto access = resolve_atomic_access(interpreter, configuration, arg, entry, sizeof(i64));
- if (!access.has_value())
- return Outcome::Return;
- // Waiting on a non-shared memory always traps.
- interpreter.set_trap("Expected shared memory"sv);
- return Outcome::Return;
-}
-
-HANDLE_INSTRUCTION(atomic_fence)
-{
- LOG_INSN;
- // There is nothing to synchronize with in a single-threaded store.
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(memory_fill)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto& args = instruction->arguments().unsafe_get<Instruction::MemoryIndexArgument>();
- auto address = configuration.frame().module().memories().data()[args.memory_index.value()];
- auto instance = configuration.store().get(address);
- // bounds checked by verifier.
- auto const count = memory_base_address(*instance, configuration.take_source<source_address_mix>(0, addresses.sources));
- auto const value = static_cast<u8>(configuration.take_source<source_address_mix>(1, addresses.sources).template to<u32>());
- auto const destination_offset = memory_base_address(*instance, configuration.take_source<source_address_mix>(2, addresses.sources));
-
- Checked<u64> checked_end = destination_offset;
- checked_end += count;
- TRAP_IN_LOOP_IF_NOT(!checked_end.has_overflow() && static_cast<size_t>(checked_end.value()) <= instance->data().size());
-
- if (count == 0)
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-
- instance->data().fill(destination_offset, value, count);
- }
-
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(memory_copy)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().unsafe_get<Instruction::MemoryCopyArgs>();
- auto source_address = configuration.frame().module().memories().data()[args.src_index.value()];
- auto destination_address = configuration.frame().module().memories().data()[args.dst_index.value()];
- auto source_instance = configuration.store().get(source_address);
- auto destination_instance = configuration.store().get(destination_address);
-
- auto const& count_memory = source_instance->type().limits().address_type() == AddressType::I32 ? *source_instance : *destination_instance;
- auto count = memory_base_address(count_memory, configuration.take_source<source_address_mix>(0, addresses.sources));
- auto source_offset = memory_base_address(*source_instance, configuration.take_source<source_address_mix>(1, addresses.sources));
- auto destination_offset = memory_base_address(*destination_instance, configuration.take_source<source_address_mix>(2, addresses.sources));
-
- auto source_position = saturating_add<u64>(source_offset, count);
- auto destination_position = saturating_add<u64>(destination_offset, count);
- TRAP_IN_LOOP_IF_NOT(source_position <= source_instance->data().size());
- TRAP_IN_LOOP_IF_NOT(destination_position <= destination_instance->data().size());
-
- if (count == 0)
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-
- destination_instance->data().copy_from(source_instance->data(), source_offset, destination_offset, count);
-
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(memory_init)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().unsafe_get<Instruction::MemoryInitArgs>();
- auto& data_address = configuration.frame().module().datas()[args.data_index.value()];
- auto& data = *configuration.store().get(data_address);
- auto memory_address = configuration.frame().module().memories().data()[args.memory_index.value()];
- auto memory = configuration.store().unsafe_get(memory_address);
- // bounds checked by verifier.
- // The count and source offset are always i32; the destination is typed as the memory's address type.
- auto count = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto source_offset = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u32>();
- auto destination_offset = memory_base_address(*memory, configuration.take_source<source_address_mix>(2, addresses.sources));
-
- auto source_position = saturating_add<u64>(source_offset, count);
- auto destination_position = saturating_add<u64>(destination_offset, count);
- TRAP_IN_LOOP_IF_NOT(source_position <= data.data().size());
- TRAP_IN_LOOP_IF_NOT(destination_position <= memory->data().size());
-
- if (count == 0)
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-
- memory->data().overwrite(destination_offset, data.data().data() + source_offset, count);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(data_drop)
-{
- LOG_INSN;
- auto data_index = instruction->arguments().get<DataIndex>();
- auto data_address = configuration.frame().module().datas()[data_index.value()];
- *configuration.store().get(data_address) = DataInstance({});
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(elem_drop)
-{
- LOG_INSN;
- auto elem_index = instruction->arguments().get<ElementIndex>();
- auto address = configuration.frame().module().elements()[elem_index.value()];
- auto elem = configuration.store().get(address);
- *configuration.store().get(address) = ElementInstance(elem->type(), {});
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(table_init)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::TableElementArgs>();
- auto table_address = configuration.frame().module().tables()[args.table_index.value()];
- auto table = configuration.store().get(table_address);
- auto element_address = configuration.frame().module().elements()[args.element_index.value()];
- auto element = configuration.store().get(element_address);
- // bounds checked by verifier.
- auto count = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto source_offset = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u32>();
- auto destination_offset = configuration.take_source<source_address_mix>(2, addresses.sources).template to<u32>();
-
- Checked<u32> checked_source_offset = source_offset;
- Checked<u32> checked_destination_offset = destination_offset;
- checked_source_offset += count;
- checked_destination_offset += count;
- TRAP_IN_LOOP_IF_NOT(!checked_source_offset.has_overflow() && checked_source_offset <= (u32)element->references().size());
- TRAP_IN_LOOP_IF_NOT(!checked_destination_offset.has_overflow() && checked_destination_offset <= (u32)table->elements().size());
-
- for (u32 i = 0; i < count; ++i) {
- auto const& ref = element->references()[source_offset + i];
- RefPtr<ModuleInstance const> anchor;
- if (auto const* func = ref.ref().template get_pointer<Reference::Func>())
- anchor = configuration.store().get_module_instance_for(func->address);
- table->set_element(destination_offset + i, ref, move(anchor));
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(table_copy)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::TableTableArgs>();
- auto source_address = configuration.frame().module().tables()[args.rhs.value()];
- auto destination_address = configuration.frame().module().tables()[args.lhs.value()];
- auto source_instance = configuration.store().get(source_address);
- auto destination_instance = configuration.store().get(destination_address);
-
- // bounds checked by verifier.
- auto count = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto source_offset = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u32>();
- auto destination_offset = configuration.take_source<source_address_mix>(2, addresses.sources).template to<u32>();
-
- auto source_position = saturating_add(static_cast<size_t>(source_offset), static_cast<size_t>(count));
- auto destination_position = saturating_add(static_cast<size_t>(destination_offset), static_cast<size_t>(count));
- TRAP_IN_LOOP_IF_NOT(source_position <= source_instance->elements().size());
- TRAP_IN_LOOP_IF_NOT(destination_position <= destination_instance->elements().size());
-
- if (count == 0)
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-
- if (destination_offset <= source_offset) {
- for (u32 i = 0; i < count; ++i) {
- destination_instance->set_element(destination_offset + i,
- source_instance->elements()[source_offset + i],
- source_instance->module_anchor_at(source_offset + i));
- }
- } else {
- for (u32 i = count - 1; i != NumericLimits<u32>::max(); --i) {
- destination_instance->set_element(destination_offset + i,
- source_instance->elements()[source_offset + i],
- source_instance->module_anchor_at(source_offset + i));
- }
- }
-
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(table_fill)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto table_index = instruction->arguments().get<TableIndex>();
- auto address = configuration.frame().module().tables()[table_index.value()];
- auto table = configuration.store().get(address);
- // bounds checked by verifier.
- auto count = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto value = configuration.take_source<source_address_mix>(1, addresses.sources);
- auto start = configuration.take_source<source_address_mix>(2, addresses.sources).template to<u32>();
-
- Checked<u32> checked_offset = start;
- checked_offset += count;
- TRAP_IN_LOOP_IF_NOT(!checked_offset.has_overflow() && checked_offset <= (u32)table->elements().size());
-
- // Don't leak the RefPtr to the sibling call.
- {
- auto ref = value.template to<Reference>();
- RefPtr<ModuleInstance const> anchor;
- if (auto const* func = ref.ref().template get_pointer<Reference::Func>())
- anchor = configuration.store().get_module_instance_for(func->address);
- for (u32 i = 0; i < count; ++i)
- table->set_element(start + i, ref, anchor);
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(table_set)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto ref = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto index = static_cast<size_t>(configuration.take_source<source_address_mix>(1, addresses.sources).template to<u32>());
- auto table_index = instruction->arguments().get<TableIndex>();
- auto address = configuration.frame().module().tables()[table_index.value()];
- auto table = configuration.store().get(address);
- TRAP_IN_LOOP_IF_NOT(index < table->elements().size());
- {
- auto reference = ref.template to<Reference>();
- RefPtr<ModuleInstance const> anchor;
- if (auto const* func = reference.ref().template get_pointer<Reference::Func>())
- anchor = configuration.store().get_module_instance_for(func->address);
- table->set_element(index, reference, move(anchor));
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(table_get)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto& index_value = configuration.source_value<source_address_mix>(0, addresses.sources);
- auto index = static_cast<size_t>(index_value.template to<u32>());
- auto table_index = instruction->arguments().get<TableIndex>();
- auto address = configuration.frame().module().tables()[table_index.value()];
- auto table = configuration.store().get(address);
- TRAP_IN_LOOP_IF_NOT(index < table->elements().size());
- index_value = Value(table->elements()[index]);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(table_grow)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto size = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto fill_value = configuration.take_source<source_address_mix>(1, addresses.sources);
- auto table_index = instruction->arguments().get<TableIndex>();
- auto address = configuration.frame().module().tables()[table_index.value()];
- auto table = configuration.store().get(address);
- auto previous_size = table->elements().size();
- auto did_grow = table->grow(size, fill_value.template to<Reference>());
- if (!did_grow) {
- configuration.push_to_destination<source_address_mix>(Value(-1), addresses.destination);
- } else {
- configuration.push_to_destination<source_address_mix>(Value(static_cast<i32>(previous_size)), addresses.destination);
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(table_size)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto table_index = instruction->arguments().get<TableIndex>();
- auto address = configuration.frame().module().tables()[table_index.value()];
- auto table = configuration.store().get(address);
- configuration.push_to_destination<source_address_mix>(Value(static_cast<i32>(table->elements().size())), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(ref_null)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto type = instruction->arguments().get<ValueType>();
- configuration.push_to_destination<source_address_mix>(Value(Reference(Reference::Null { type })), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(ref_func)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto index = instruction->arguments().get<FunctionIndex>().value();
- auto& functions = configuration.frame().module().functions();
- auto address = functions[index];
- configuration.push_to_destination<source_address_mix>(Value(Reference { Reference::Func { address, configuration.store().get_module_for(address) } }), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(ref_is_null)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto ref = configuration.take_source<source_address_mix>(0, addresses.sources);
- configuration.push_to_destination<source_address_mix>(
- Value(static_cast<i32>(ref.template to<Reference>().ref().template has<Reference::Null>() ? 1 : 0)),
- addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(drop)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- configuration.take_source<source_address_mix>(0, addresses.sources);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(select)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // Note: The type seems to only be used for validation.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources).template to<i32>(); // bounds checked by verifier.
- dbgln_if(WASM_TRACE_DEBUG, "select({})", value);
- auto rhs = configuration.take_source<source_address_mix>(1, addresses.sources);
- auto& lhs = configuration.source_value<source_address_mix>(2, addresses.sources); // bounds checked by verifier.
- lhs = value != 0 ? lhs : rhs;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(select_typed)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // Note: The type seems to only be used for validation.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources).template to<i32>(); // bounds checked by verifier.
- dbgln_if(WASM_TRACE_DEBUG, "select_typed({})", value);
- auto rhs = configuration.take_source<source_address_mix>(1, addresses.sources);
- auto& lhs = configuration.source_value<source_address_mix>(2, addresses.sources); // bounds checked by verifier.
- lhs = value != 0 ? lhs : rhs;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_eqz)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i32, i32, Operators::EqualsZero, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::Equals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::NotEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_lts)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::LessThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_ltu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::LessThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_gts)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::GreaterThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_gtu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::GreaterThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_les)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::LessThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_leu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::LessThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_ges)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i32, i32, Operators::GreaterThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32_geu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u32, i32, Operators::GreaterThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_eqz)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<i64, i32, Operators::EqualsZero, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i32, Operators::Equals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i32, Operators::NotEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_lts)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i32, Operators::LessThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_ltu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i32, Operators::LessThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_gts)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i32, Operators::GreaterThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_gtu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i32, Operators::GreaterThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_les)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i32, Operators::LessThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_leu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i32, Operators::LessThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_ges)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<i64, i32, Operators::GreaterThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64_geu)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u64, i32, Operators::GreaterThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, i32, Operators::Equals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, i32, Operators::NotEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_lt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, i32, Operators::LessThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_gt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, i32, Operators::GreaterThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_le)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, i32, Operators::LessThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32_ge)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<float, i32, Operators::GreaterThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, i32, Operators::Equals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, i32, Operators::NotEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_lt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, i32, Operators::LessThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_gt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, i32, Operators::GreaterThan, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64_le)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<double, i32, Operators::LessThanOrEquals, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extmul_high_i16x8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<4, Operators::Multiply, Operators::VectorExt::High, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extmul_low_i16x8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<4, Operators::Multiply, Operators::VectorExt::Low, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<2, Operators::Equals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<2, Operators::NotEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_lt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<2, Operators::LessThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_gt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<2, Operators::GreaterThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_le_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<2, Operators::LessThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_ge_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<2, Operators::GreaterThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<2, Operators::Absolute>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<2, Operators::Negate, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_all_true)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorAllTrue<2>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<2, Operators::Add, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<2, Operators::Subtract, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<2, Operators::Multiply, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extend_low_i32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<2, Operators::VectorExt::Low, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extend_high_i32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<2, Operators::VectorExt::High, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extend_low_i32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<2, Operators::VectorExt::Low, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extend_high_i32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<2, Operators::VectorExt::High, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extmul_low_i32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<2, Operators::Multiply, Operators::VectorExt::Low, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extmul_high_i32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<2, Operators::Multiply, Operators::VectorExt::High, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extmul_low_i32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<2, Operators::Multiply, Operators::VectorExt::Low, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extmul_high_i32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<2, Operators::Multiply, Operators::VectorExt::High, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<4, Operators::Equals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<4, Operators::NotEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_lt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<4, Operators::LessThan>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_gt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<4, Operators::GreaterThan>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_le)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<4, Operators::LessThanOrEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_ge)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<4, Operators::GreaterThanOrEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_min)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::Minimum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_max)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::Maximum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<2, Operators::Equals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<2, Operators::NotEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_lt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<2, Operators::LessThan>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_gt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<2, Operators::GreaterThan>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_le)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<2, Operators::LessThanOrEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_ge)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatCmpOp<2, Operators::GreaterThanOrEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_min)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::Minimum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_max)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::Maximum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_div)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::Divide>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::Multiply>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::Subtract>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::Add>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_pmin)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::PseudoMinimum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_pmax)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<4, Operators::PseudoMaximum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_div)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::Divide>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::Multiply>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::Subtract>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::Add>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_pmin)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::PseudoMinimum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_pmax)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorFloatBinaryOp<2, Operators::PseudoMaximum>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_ceil)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<4, Operators::Ceil>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_floor)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<4, Operators::Floor>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_trunc)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<4, Operators::Truncate>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_nearest)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<4, Operators::NearbyIntegral>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_sqrt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<4, Operators::SquareRoot>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<4, Operators::Negate>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<4, Operators::Absolute>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_ceil)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<2, Operators::Ceil>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_floor)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<2, Operators::Floor>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_trunc)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<2, Operators::Truncate>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_nearest)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<2, Operators::NearbyIntegral>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_sqrt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<2, Operators::SquareRoot>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<2, Operators::Negate>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorFloatUnaryOp<2, Operators::Absolute>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_and)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::BitAnd, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_or)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::BitOr, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_xor)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::BitXor, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_not)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::BitNot, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_andnot)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::BitAndNot, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_bitselect)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto mask = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u128>();
- auto false_vector = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u128>();
- auto true_vector = configuration.take_source<source_address_mix>(2, addresses.sources).template to<u128>();
- u128 result = (true_vector & mask) | (false_vector & ~mask);
- configuration.push_to_destination<source_address_mix>(Value(result), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_any_true)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto vector = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u128>(); // bounds checked by verifier.
- configuration.push_to_destination<source_address_mix>(Value(static_cast<i32>(vector != 0)), addresses.destination);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load8_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_lane_n<8>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load16_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_lane_n<16>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load32_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_lane_n<32>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load64_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_lane_n<64>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load32_zero)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_zero_n<32>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_load64_zero)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.load_and_push_zero_n<64>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_store8_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store_lane_n<8>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_store16_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store_lane_n<16>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_store32_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store_lane_n<32>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(v128_store64_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.pop_and_store_lane_n<64>(configuration, *instruction, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_trunc_sat_f32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<4, 4, u32, f32, Operators::SaturatingTruncate<i32>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_trunc_sat_f32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<4, 4, u32, f32, Operators::SaturatingTruncate<u32>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_bitmask)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorBitmask<16>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_bitmask)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorBitmask<8>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_bitmask)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorBitmask<4>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_bitmask)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorBitmask<2>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_dot_i16x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorDotProduct<4>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_narrow_i16x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorNarrow<16, i8>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_narrow_i16x8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorNarrow<16, u8>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_narrow_i32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorNarrow<8, i16>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_narrow_i32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorNarrow<8, u16>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_q15mulr_sat_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::SaturatingOp<i16, Operators::Q15Mul>, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_convert_i32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<4, 4, u32, i32, Operators::Convert<f32>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_convert_i32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<4, 4, u32, u32, Operators::Convert<f32>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_convert_low_i32x4_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<2, 4, u64, i32, Operators::Convert<f64>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_convert_low_i32x4_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<2, 4, u64, u32, Operators::Convert<f64>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_demote_f64x2_zero)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<4, 2, u32, f64, Operators::Convert<f32>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_promote_low_f32x4)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<2, 4, u64, f32, Operators::Convert<f64>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_trunc_sat_f64x2_s_zero)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<4, 2, u32, f64, Operators::SaturatingTruncate<i32>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_trunc_sat_f64x2_u_zero)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorConvertOp<4, 2, u32, f64, Operators::SaturatingTruncate<u32>>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-HANDLE_INSTRUCTION(i8x16_shl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<16>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_shr_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<16, MakeUnsigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_shr_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<16, MakeSigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_shl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<8>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_shr_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<8, MakeUnsigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_shr_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<8, MakeSigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_shl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<4>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_shr_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<4, MakeUnsigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_shr_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<4, MakeSigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_shl)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<2>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_shr_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<2, MakeUnsigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_shr_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorShiftRight<2, MakeSigned>, source_address_mix, i32>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_swizzle)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorSwizzle, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_extract_lane_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i8, Operators::VectorExtractLane<16, MakeSigned>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_extract_lane_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u8, Operators::VectorExtractLane<16, MakeUnsigned>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extract_lane_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i16, Operators::VectorExtractLane<8, MakeSigned>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extract_lane_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u16, Operators::VectorExtractLane<8, MakeUnsigned>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extract_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorExtractLane<4, MakeSigned>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_extract_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i64, Operators::VectorExtractLane<2, MakeSigned>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_extract_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, float, Operators::VectorExtractLaneFloat<4>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_extract_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, double, Operators::VectorExtractLaneFloat<2>, source_address_mix>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_replace_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorReplaceLane<16, i32>, source_address_mix, i32>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_replace_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorReplaceLane<8, i32>, source_address_mix, i32>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_replace_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorReplaceLane<4>, source_address_mix, i32>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i64x2_replace_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorReplaceLane<2>, source_address_mix, i64>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_replace_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorReplaceLane<4, float>, source_address_mix, float>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_replace_lane)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorReplaceLane<2, double>, source_address_mix, double>(configuration, addresses, instruction->arguments().get<Instruction::LaneIndex>().lane))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::Equals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::NotEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_lt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::LessThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_lt_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::LessThan, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_gt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::GreaterThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_gt_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::GreaterThan, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_le_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::LessThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_le_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::LessThanOrEquals, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_ge_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::GreaterThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_ge_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<16, Operators::GreaterThanOrEquals, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<16, Operators::Absolute>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<16, Operators::Negate>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_all_true)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorAllTrue<16>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_popcnt)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<16, Operators::PopCount>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::Add>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::Subtract>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_avgr_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::Average, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_add_sat_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::SaturatingOp<i8, Operators::Add>, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_add_sat_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::SaturatingOp<u8, Operators::Add>, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_sub_sat_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::SaturatingOp<i8, Operators::Subtract>, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_sub_sat_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::SaturatingOp<u8, Operators::Subtract>, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_min_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::Minimum, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_min_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::Minimum, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_max_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::Maximum, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i8x16_max_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<16, Operators::Maximum, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::Equals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::NotEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_lt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::LessThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_lt_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::LessThan, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_gt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::GreaterThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_gt_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::GreaterThan, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_le_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::LessThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_le_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::LessThanOrEquals, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_ge_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::GreaterThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_ge_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<8, Operators::GreaterThanOrEquals, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<8, Operators::Absolute>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<8, Operators::Negate>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_all_true)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorAllTrue<8>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Add>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Subtract>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Multiply>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_avgr_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Average, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_add_sat_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::SaturatingOp<i16, Operators::Add>, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_add_sat_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::SaturatingOp<u16, Operators::Add>, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_sub_sat_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::SaturatingOp<i16, Operators::Subtract>, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_sub_sat_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::SaturatingOp<u16, Operators::Subtract>, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_min_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Minimum, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_min_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Minimum, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_max_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Maximum, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_max_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<8, Operators::Maximum, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extend_low_i8x16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<8, Operators::VectorExt::Low, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extend_high_i8x16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<8, Operators::VectorExt::High, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extend_low_i8x16_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<8, Operators::VectorExt::Low, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extend_high_i8x16_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<8, Operators::VectorExt::High, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extadd_pairwise_i8x16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExtOpPairwise<8, Operators::Add, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extadd_pairwise_i8x16_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExtOpPairwise<8, Operators::Add, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extmul_low_i8x16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<8, Operators::Multiply, Operators::VectorExt::Low, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extmul_high_i8x16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<8, Operators::Multiply, Operators::VectorExt::High, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extmul_low_i8x16_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<8, Operators::Multiply, Operators::VectorExt::Low, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i16x8_extmul_high_i8x16_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<8, Operators::Multiply, Operators::VectorExt::High, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::Equals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_ne)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::NotEquals>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_lt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::LessThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_lt_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::LessThan, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_gt_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::GreaterThan, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_gt_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::GreaterThan, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_le_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::LessThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_le_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::LessThanOrEquals, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_ge_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::GreaterThanOrEquals, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_ge_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorCmpOp<4, Operators::GreaterThanOrEquals, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_abs)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<4, Operators::Absolute>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_neg)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerUnaryOp<4, Operators::Negate, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_all_true)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, i32, Operators::VectorAllTrue<4>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_add)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<4, Operators::Add, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_sub)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<4, Operators::Subtract, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_mul)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<4, Operators::Multiply, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_min_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<4, Operators::Minimum, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_min_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<4, Operators::Minimum, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_max_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<4, Operators::Maximum, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_max_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerBinaryOp<4, Operators::Maximum, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extend_low_i16x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<4, Operators::VectorExt::Low, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extend_high_i16x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<4, Operators::VectorExt::High, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extend_low_i16x8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<4, Operators::VectorExt::Low, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extend_high_i16x8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExt<4, Operators::VectorExt::High, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extadd_pairwise_i16x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExtOpPairwise<4, Operators::Add, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extadd_pairwise_i16x8_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.unary_operation<u128, u128, Operators::VectorIntegerExtOpPairwise<4, Operators::Add, MakeUnsigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extmul_low_i16x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<4, Operators::Multiply, Operators::VectorExt::Low, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_extmul_high_i16x8_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorIntegerExtOp<4, Operators::Multiply, Operators::VectorExt::High, MakeSigned>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-ALIAS_INSTRUCTION(i8x16_relaxed_swizzle, i8x16_swizzle)
-ALIAS_INSTRUCTION(i32x4_relaxed_trunc_f32x4_s, i32x4_trunc_sat_f32x4_s)
-ALIAS_INSTRUCTION(i32x4_relaxed_trunc_f32x4_u, i32x4_trunc_sat_f32x4_u)
-ALIAS_INSTRUCTION(i32x4_relaxed_trunc_f64x2_s_zero, i32x4_trunc_sat_f64x2_s_zero)
-ALIAS_INSTRUCTION(i32x4_relaxed_trunc_f64x2_u_zero, i32x4_trunc_sat_f64x2_u_zero)
-
-HANDLE_INSTRUCTION(f32x4_relaxed_madd)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto c = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u128>();
- auto a = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u128>();
- auto& b_slot = configuration.source_value<source_address_mix>(2, addresses.sources);
- auto b = b_slot.template to<u128>();
- b_slot = Value { Operators::VectorMultiplyAdd<4> {}(a, b, c) };
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f32x4_relaxed_nmadd)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto c = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u128>();
- auto a = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u128>();
- auto& b_slot = configuration.source_value<source_address_mix>(2, addresses.sources);
- auto b = b_slot.template to<u128>();
- b_slot = Value { Operators::VectorMultiplySub<4> {}(a, b, c) };
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_relaxed_madd)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto c = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u128>();
- auto a = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u128>();
- auto& b_slot = configuration.source_value<source_address_mix>(2, addresses.sources);
- auto b = b_slot.template to<u128>();
- b_slot = Value { Operators::VectorMultiplyAdd<2> {}(a, b, c) };
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(f64x2_relaxed_nmadd)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto c = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u128>();
- auto a = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u128>();
- auto& b_slot = configuration.source_value<source_address_mix>(2, addresses.sources);
- auto b = b_slot.template to<u128>();
- b_slot = Value { Operators::VectorMultiplySub<2> {}(a, b, c) };
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-ALIAS_INSTRUCTION(i8x16_relaxed_laneselect, v128_bitselect)
-ALIAS_INSTRUCTION(i16x8_relaxed_laneselect, v128_bitselect)
-ALIAS_INSTRUCTION(i32x4_relaxed_laneselect, v128_bitselect)
-ALIAS_INSTRUCTION(i64x2_relaxed_laneselect, v128_bitselect)
-ALIAS_INSTRUCTION(f32x4_relaxed_min, f32x4_min)
-ALIAS_INSTRUCTION(f32x4_relaxed_max, f32x4_max)
-ALIAS_INSTRUCTION(f64x2_relaxed_min, f64x2_min)
-ALIAS_INSTRUCTION(f64x2_relaxed_max, f64x2_max)
-ALIAS_INSTRUCTION(i16x8_relaxed_q15mulr_s, i16x8_q15mulr_sat_s)
-
-HANDLE_INSTRUCTION(i16x8_relaxed_dot_i8x16_i7x16_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (interpreter.binary_numeric_operation<u128, u128, Operators::VectorDotProduct<8>, source_address_mix>(configuration, addresses))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i32x4_relaxed_dot_i8x16_i7x16_add_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto acc = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u128>();
- auto rhs = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u128>(); // bounds checked by verifier.
- auto& lhs_slot = configuration.source_value<source_address_mix>(2, addresses.sources);
- lhs_slot = Value { Operators::VectorRelaxedDotI8I7AddS {}(lhs_slot.template to<u128>(), rhs, acc) };
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-throw-ref
-HANDLE_INSTRUCTION(throw_ref)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const value = configuration.take_source<source_address_mix>(0, addresses.sources);
- // 4. If val' is ref.null, then trap. (See the encoding table in Value(Reference const&): 4 is a null exnref.)
- if (value.value().high() == 4) [[unlikely]] {
- interpreter.set_trap("null exception reference"sv);
- return Outcome::Return;
- }
- auto const exception_address = bit_cast<ExceptionAddress>(value.value().low());
- if (auto continuation = interpreter.unwind_to_throw_handler(configuration, exception_address); continuation.has_value()) {
- short_ip.current_ip_value = continuation->value() - 1;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
- }
- // 5.5.2. "...the first non-value entry of the stack is not a handler: Throw the exception val' as a result."
- interpreter.set_trap(Trap { UncaughtException { exception_address } });
- return Outcome::Return;
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-throw-x
-HANDLE_INSTRUCTION(throw_)
-{
- LOG_INSN;
- {
- auto tag_address = configuration.frame().module().tags()[instruction->arguments().get<TagIndex>().value()];
- auto& tag_instance = *configuration.store().get(tag_address);
- auto& type = tag_instance.type();
- auto values = Vector<Value>(configuration.value_stack().span().slice_from_end(type.parameters().size()));
- configuration.value_stack().shrink(configuration.value_stack().size() - type.parameters().size());
- auto exception_address = configuration.store().allocate(tag_address, move(values));
- if (!exception_address.has_value()) {
- interpreter.set_trap("Out of memory"sv);
- return Outcome::Return;
- }
- configuration.value_stack().append(Value(Reference { Reference::Exception { *exception_address } }));
- }
- TAILCALL return InstructionHandler<Instructions::throw_ref.value()>::operator()<HasDynamicInsnLimit, Continue, SourceAddressMix::Any>(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-try-table-xref-syntax-instructions-syntax-blocktype-mathit-blocktype-xref-syntax-instructions-syntax-catch-mathit-catch-ast-xref-syntax-instructions-syntax-instr-mathit-instr-ast
-HANDLE_INSTRUCTION(try_table)
-{
- LOG_INSN;
- auto& args = instruction->arguments().unsafe_get<Instruction::TryTableArgs>();
- auto& meta = args.meta;
- auto label = Label(meta.arity, args.end_ip, configuration.value_stack().size() - meta.parameter_count, instruction);
- configuration.label_stack().unchecked_append(move(label));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// Proposal "gc".
-
-#define GC_TRAP_IF(condition, message) \
- do { \
- if (condition) [[unlikely]] { \
- interpreter.set_trap(message##sv); \
- return Outcome::Return; \
- } \
- } while (false)
-
-static ALWAYS_INLINE bool is_null_gc_reference(Value const& value)
-{
- auto const tag = value.value().high();
- return tag == 2 || tag == 3 || tag == 4 || tag == 8;
-}
-
-// https://webassembly.github.io/spec/core/exec/runtime.html#aggregate-instances
-static Value pack_into_field(ValueType const& storage_type, Value const& value)
-{
- switch (storage_type.kind()) {
- case ValueType::I8:
- return Value(static_cast<u32>(value.to<u32>() & 0xff));
- case ValueType::I16:
- return Value(static_cast<u32>(value.to<u32>() & 0xffff));
- default:
- return value;
- }
-}
-
-// https://webassembly.github.io/spec/core/exec/runtime.html#aggregate-instances
-// unpack^sx?_zt(val) = val if zt is a valtype
-// = extend^sx_|zt|,32(val) if zt is a packtype
-static Value unpack_from_field(ValueType const& storage_type, Value const& value, bool sign_extend)
-{
- switch (storage_type.kind()) {
- case ValueType::I8:
- return sign_extend
- ? Value(static_cast<i32>(static_cast<i8>(value.to<u32>() & 0xff)))
- : Value(static_cast<u32>(value.to<u32>() & 0xff));
- case ValueType::I16:
- return sign_extend
- ? Value(static_cast<i32>(static_cast<i16>(value.to<u32>() & 0xffff)))
- : Value(static_cast<u32>(value.to<u32>() & 0xffff));
- default:
- return value;
- }
-}
-
-static size_t storage_type_byte_width(ValueType const& storage_type)
-{
- switch (storage_type.kind()) {
- case ValueType::I8:
- return 1;
- case ValueType::I16:
- return 2;
- case ValueType::I32:
- case ValueType::F32:
- return 4;
- case ValueType::I64:
- case ValueType::F64:
- return 8;
- case ValueType::V128:
- return 16;
- default:
- // References cannot be read out of a data segment (checked by the validator).
- VERIFY_NOT_REACHED();
- }
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-static Value value_from_segment_bytes(ValueType const& storage_type, ReadonlyBytes bytes)
-{
- auto read_le = []<typename T>(ReadonlyBytes data) {
- T value {};
- __builtin_memcpy(&value, data.data(), sizeof(T));
- return AK::convert_between_host_and_little_endian(value);
- };
- switch (storage_type.kind()) {
- case ValueType::I8:
- // Packed fields are stored pre-truncated; reads sign- or zero-extend, see unpack_from_field() above.
- return Value(static_cast<u32>(bytes[0]));
- case ValueType::I16:
- return Value(static_cast<u32>(read_le.operator()<u16>(bytes)));
- case ValueType::I32:
- return Value(static_cast<i32>(read_le.operator()<u32>(bytes)));
- case ValueType::I64:
- return Value(static_cast<i64>(read_le.operator()<u64>(bytes)));
- case ValueType::F32:
- return Value(bit_cast<f32>(read_le.operator()<u32>(bytes)));
- case ValueType::F64:
- return Value(bit_cast<f64>(read_le.operator()<u64>(bytes)));
- case ValueType::V128: {
- u128 value {};
- __builtin_memcpy(&value, bytes.data(), sizeof(u128));
- return Value(value);
- }
- default:
- VERIFY_NOT_REACHED();
- }
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-static bool reference_matches_type(Value const& value, ValueType const& target, Configuration& configuration)
-{
- // See the encoding table in Value(Reference const&).
- switch (value.value().high()) {
- case 2: // null funcref / nofuncref
- case 3: // null externref / noexternref
- case 4: // null exnref / noexnref
- case 8: // null in the any hierarchy
- // "ref.null matches (ref null ht)": null only matches nullable targets. Validation
- // keeps the hierarchies apart, so the target heap type always agrees with the null;
- // in particular this is the only way to match the bottom (none/nofunc/...) types.
- return target.is_nullable();
- case 1: // a host externref
- // Matches extern; also any, for an internalized host reference (tag 10) that lost its
- // wrapper crossing a Reference boundary (e.g. an anyref table), see Value::to<Reference>().
- return target.kind() == ValueType::ExternReference || target.kind() == ValueType::AnyReference;
- case 5: // an exception
- return target.kind() == ValueType::ExceptionReference;
- case 6: { // a struct or array instance
- auto& cell = *bit_cast<GC::Cell*>(value.value().low());
- switch (target.kind()) {
- case ValueType::AnyReference:
- case ValueType::EqReference:
- return true;
- case ValueType::ExternReference:
- // An externalized aggregate (tag 9) that lost its wrapper crossing a Reference boundary (e.g. an externref table); it is still in the extern hierarchy.
- return true;
- case ValueType::StructReference:
- return is<StructInstance>(cell);
- case ValueType::ArrayReference:
- return is<ArrayInstance>(cell);
- case ValueType::TypeUseReference: {
- DefinedType const* actual = nullptr;
- if (auto* struct_instance = as_if<StructInstance>(cell))
- actual = &struct_instance->type();
- else if (auto* array_instance = as_if<ArrayInstance>(cell))
- actual = &array_instance->type();
- return actual && matches_defined_type(*actual, *configuration.frame().module().canonical_types()[target.unsafe_typeindex().value()]);
- }
- default:
- return false;
- }
- }
- case 7: // an i31
- // ExternReference covers an externalized i31 (tag 9) that lost its wrapper crossing a Reference boundary, as for tag 6 above.
- return first_is_one_of(target.kind(), ValueType::I31Reference, ValueType::EqReference, ValueType::AnyReference, ValueType::ExternReference);
- case 9 | (6 << 8): // an externalized struct or array instance
- case 9 | (7 << 8): // an externalized i31
- return target.kind() == ValueType::ExternReference;
- case 10: // a host externref internalized into the any hierarchy
- return target.kind() == ValueType::AnyReference;
- default: { // a funcref; high is the defining Module* (null for host functions)
- if (target.kind() == ValueType::FunctionReference)
- return true;
- if (target.kind() != ValueType::TypeUseReference)
- return false;
- auto* function = configuration.store().get(FunctionAddress { value.value().low() });
- auto const* actual = function ? function->visit([](auto& f) { return f.defined_type(); }) : nullptr;
- return actual && matches_defined_type(*actual, *configuration.frame().module().canonical_types()[target.unsafe_typeindex().value()]);
- }
- }
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(ref_eq)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto rhs = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto& lhs_slot = configuration.source_value<source_address_mix>(1, addresses.sources);
- // Both operands are in the eq hierarchy: nulls are uniformly tag 8, i31s carry their payload and aggregates their cell pointer, so reference equality is bit equality.
- auto const equal = lhs_slot.value() == rhs.value();
- lhs_slot = Value(static_cast<i32>(equal ? 1 : 0));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(ref_as_non_null)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- GC_TRAP_IF(is_null_gc_reference(slot), "null reference");
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#control-instructions
-HANDLE_INSTRUCTION(br_on_null)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto const is_null = is_null_gc_reference(value);
- // The branched-to label's arity does not include the reference; it is only put back when falling through.
- if (!is_null)
- configuration.value_stack().append(value);
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, instruction->arguments().unsafe_get<Instruction::BranchArgs>().label, short_ip.current_ip_value, is_null).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#control-instructions
-HANDLE_INSTRUCTION(br_on_non_null)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto const is_null = is_null_gc_reference(value);
- if (!is_null)
- configuration.value_stack().append(value);
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, instruction->arguments().unsafe_get<Instruction::BranchArgs>().label, short_ip.current_ip_value, !is_null).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(struct_new)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto const& type = *configuration.frame().module().canonical_types()[instruction->arguments().get<TypeIndex>().value()];
- auto const& field_types = type.expansion().get<StructType>().fields();
- auto const field_count = field_types.size();
- auto operands = configuration.value_stack().span().slice_from_end(field_count);
- Vector<Value> fields;
- fields.ensure_capacity(field_count);
- for (size_t i = 0; i < field_count; ++i)
- fields.unchecked_append(pack_into_field(field_types[i].type(), operands[i]));
- auto instance = configuration.store().heap().allocate<StructInstance>(type, move(fields));
- configuration.value_stack().shrink(configuration.value_stack().size() - field_count);
- configuration.push_to_destination<source_address_mix>(Value(Reference { Reference::GcObject { instance.ptr() } }), addresses.destination);
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(struct_new_default)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto const& type = *configuration.frame().module().canonical_types()[instruction->arguments().get<TypeIndex>().value()];
- auto const& field_types = type.expansion().get<StructType>().fields();
- Vector<Value> fields;
- fields.ensure_capacity(field_types.size());
- for (auto const& field_type : field_types)
- fields.unchecked_append(Value(field_type.type().unpacked()));
- auto instance = configuration.store().heap().allocate<StructInstance>(type, move(fields));
- configuration.push_to_destination<source_address_mix>(Value(Reference { Reference::GcObject { instance.ptr() } }), addresses.destination);
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-template<SourceAddressMix mix>
-static bool struct_get_impl(BytecodeInterpreter& interpreter, Configuration& configuration, Instruction const* instruction, SourcesAndDestination const& addresses, bool sign_extend)
-{
- auto& args = instruction->arguments().get<Instruction::StructFieldArgs>();
- auto& slot = configuration.source_value<mix>(0, addresses.sources); // bounds checked by verifier.
- if (is_null_gc_reference(slot)) [[unlikely]]
- return interpreter.set_trap("null structure reference"sv);
- auto& instance = *static_cast<StructInstance*>(bit_cast<GC::Cell*>(slot.value().low()));
- auto const& field_types = configuration.frame().module().canonical_types()[args.type_index.value()]->expansion().get<StructType>().fields();
- slot = unpack_from_field(field_types[args.field_index].type(), instance.fields()[args.field_index], sign_extend);
- return false;
-}
-
-HANDLE_INSTRUCTION(struct_get)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (struct_get_impl<source_address_mix>(interpreter, configuration, instruction, addresses, false))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(struct_get_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (struct_get_impl<source_address_mix>(interpreter, configuration, instruction, addresses, true))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(struct_get_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (struct_get_impl<source_address_mix>(interpreter, configuration, instruction, addresses, false))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(struct_set)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::StructFieldArgs>();
- // bounds checked by verifier.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto reference = configuration.take_source<source_address_mix>(1, addresses.sources);
- GC_TRAP_IF(is_null_gc_reference(reference), "null structure reference");
- auto& instance = *static_cast<StructInstance*>(bit_cast<GC::Cell*>(reference.value().low()));
- auto const& field_types = configuration.frame().module().canonical_types()[args.type_index.value()]->expansion().get<StructType>().fields();
- instance.fields()[args.field_index] = pack_into_field(field_types[args.field_index].type(), value);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_new)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto const& type = *configuration.frame().module().canonical_types()[instruction->arguments().get<TypeIndex>().value()];
- auto const& field_type = type.expansion().get<ArrayType>().type();
- // bounds checked by verifier.
- auto count = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto& slot = configuration.source_value<source_address_mix>(1, addresses.sources);
- Vector<Value> elements;
- GC_TRAP_IF(elements.try_ensure_capacity(count).is_error(), "Out of memory");
- // The initializer stays live in `slot` (a scanned location) if the allocation below triggers a collection.
- auto const element = pack_into_field(field_type.type(), slot);
- for (u32 i = 0; i < count; ++i)
- elements.unchecked_append(element);
- auto instance = configuration.store().heap().allocate<ArrayInstance>(type, move(elements));
- slot = Value(Reference { Reference::GcObject { instance.ptr() } });
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_new_default)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto const& type = *configuration.frame().module().canonical_types()[instruction->arguments().get<TypeIndex>().value()];
- auto const& field_type = type.expansion().get<ArrayType>().type();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- auto count = slot.template to<u32>();
- Vector<Value> elements;
- GC_TRAP_IF(elements.try_ensure_capacity(count).is_error(), "Out of memory");
- auto const element = Value(field_type.type().unpacked());
- for (u32 i = 0; i < count; ++i)
- elements.unchecked_append(element);
- auto instance = configuration.store().heap().allocate<ArrayInstance>(type, move(elements));
- slot = Value(Reference { Reference::GcObject { instance.ptr() } });
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_new_fixed)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto& args = instruction->arguments().get<Instruction::ArrayNewFixedArgs>();
- auto const& type = *configuration.frame().module().canonical_types()[args.type_index.value()];
- auto const& field_type = type.expansion().get<ArrayType>().type();
- auto operands = configuration.value_stack().span().slice_from_end(args.count);
- Vector<Value> elements;
- elements.ensure_capacity(args.count);
- for (auto const& operand : operands)
- elements.unchecked_append(pack_into_field(field_type.type(), operand));
- auto instance = configuration.store().heap().allocate<ArrayInstance>(type, move(elements));
- configuration.value_stack().shrink(configuration.value_stack().size() - args.count);
- configuration.push_to_destination<source_address_mix>(Value(Reference { Reference::GcObject { instance.ptr() } }), addresses.destination);
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_new_data)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto& args = instruction->arguments().get<Instruction::ArrayDataArgs>();
- auto const& type = *configuration.frame().module().canonical_types()[args.type_index.value()];
- auto const& field_type = type.expansion().get<ArrayType>().type();
- auto const element_size = storage_type_byte_width(field_type.type());
- // bounds checked by verifier.
- auto count = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto& slot = configuration.source_value<source_address_mix>(1, addresses.sources);
- auto offset = slot.template to<u32>();
- auto const& data = *configuration.store().get(configuration.frame().module().datas()[args.data_index.value()]);
- GC_TRAP_IF(static_cast<u64>(offset) + static_cast<u64>(count) * element_size > data.size(), "out of bounds memory access");
- Vector<Value> elements;
- GC_TRAP_IF(elements.try_ensure_capacity(count).is_error(), "Out of memory");
- auto bytes = data.data().span();
- for (u32 i = 0; i < count; ++i)
- elements.unchecked_append(value_from_segment_bytes(field_type.type(), bytes.slice(offset + static_cast<size_t>(i) * element_size, element_size)));
- auto instance = configuration.store().heap().allocate<ArrayInstance>(type, move(elements));
- slot = Value(Reference { Reference::GcObject { instance.ptr() } });
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_new_elem)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- {
- auto& args = instruction->arguments().get<Instruction::ArrayElemArgs>();
- auto const& type = *configuration.frame().module().canonical_types()[args.type_index.value()];
- // bounds checked by verifier.
- auto count = configuration.take_source<source_address_mix>(0, addresses.sources).template to<u32>();
- auto& slot = configuration.source_value<source_address_mix>(1, addresses.sources);
- auto offset = slot.template to<u32>();
- auto const& references = configuration.store().get(configuration.frame().module().elements()[args.element_index.value()])->references();
- GC_TRAP_IF(static_cast<u64>(offset) + count > references.size(), "out of bounds table access");
- Vector<Value> elements;
- GC_TRAP_IF(elements.try_ensure_capacity(count).is_error(), "Out of memory");
- for (u32 i = 0; i < count; ++i)
- elements.unchecked_append(Value(references[offset + i]));
- auto instance = configuration.store().heap().allocate<ArrayInstance>(type, move(elements));
- slot = Value(Reference { Reference::GcObject { instance.ptr() } });
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-template<SourceAddressMix mix>
-static bool array_get_impl(BytecodeInterpreter& interpreter, Configuration& configuration, Instruction const* instruction, SourcesAndDestination const& addresses, bool sign_extend)
-{
- // bounds checked by verifier.
- auto index = configuration.take_source<mix>(0, addresses.sources).template to<u32>();
- auto& slot = configuration.source_value<mix>(1, addresses.sources);
- if (is_null_gc_reference(slot)) [[unlikely]]
- return interpreter.set_trap("null array reference"sv);
- auto& instance = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(slot.value().low()));
- if (index >= instance.elements().size()) [[unlikely]]
- return interpreter.set_trap("out of bounds array access"sv);
- auto const& field_type = configuration.frame().module().canonical_types()[instruction->arguments().get<TypeIndex>().value()]->expansion().get<ArrayType>().type();
- slot = unpack_from_field(field_type.type(), instance.elements()[index], sign_extend);
- return false;
-}
-
-HANDLE_INSTRUCTION(array_get)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (array_get_impl<source_address_mix>(interpreter, configuration, instruction, addresses, false))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(array_get_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (array_get_impl<source_address_mix>(interpreter, configuration, instruction, addresses, true))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(array_get_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- if (array_get_impl<source_address_mix>(interpreter, configuration, instruction, addresses, false))
- return Outcome::Return;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_set)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- // bounds checked by verifier.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto index = configuration.take_source<source_address_mix>(1, addresses.sources).template to<u32>();
- auto reference = configuration.take_source<source_address_mix>(2, addresses.sources);
- GC_TRAP_IF(is_null_gc_reference(reference), "null array reference");
- auto& instance = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(reference.value().low()));
- GC_TRAP_IF(index >= instance.elements().size(), "out of bounds array access");
- auto const& field_type = configuration.frame().module().canonical_types()[instruction->arguments().get<TypeIndex>().value()]->expansion().get<ArrayType>().type();
- instance.elements()[index] = pack_into_field(field_type.type(), value);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_len)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- GC_TRAP_IF(is_null_gc_reference(slot), "null array reference");
- auto& instance = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(slot.value().low()));
- slot = Value(static_cast<i32>(instance.elements().size()));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_fill)
-{
- LOG_INSN;
- auto& value_stack = configuration.value_stack();
- auto count = value_stack.take_last().to<u32>();
- auto value = value_stack.take_last();
- auto offset = value_stack.take_last().to<u32>();
- auto reference = value_stack.take_last();
- GC_TRAP_IF(is_null_gc_reference(reference), "null array reference");
- auto& instance = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(reference.value().low()));
- GC_TRAP_IF(static_cast<u64>(offset) + count > instance.elements().size(), "out of bounds array access");
- auto const& field_type = configuration.frame().module().canonical_types()[instruction->arguments().get<TypeIndex>().value()]->expansion().get<ArrayType>().type();
- auto const element = pack_into_field(field_type.type(), value);
- for (u32 i = 0; i < count; ++i)
- instance.elements()[offset + i] = element;
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_copy)
-{
- LOG_INSN;
- auto& value_stack = configuration.value_stack();
- auto count = value_stack.take_last().to<u32>();
- auto source_offset = value_stack.take_last().to<u32>();
- auto source_reference = value_stack.take_last();
- auto destination_offset = value_stack.take_last().to<u32>();
- auto destination_reference = value_stack.take_last();
- GC_TRAP_IF(is_null_gc_reference(destination_reference), "null array reference");
- GC_TRAP_IF(is_null_gc_reference(source_reference), "null array reference");
- auto& destination = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(destination_reference.value().low()));
- auto& source = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(source_reference.value().low()));
- GC_TRAP_IF(static_cast<u64>(destination_offset) + count > destination.elements().size(), "out of bounds array access");
- GC_TRAP_IF(static_cast<u64>(source_offset) + count > source.elements().size(), "out of bounds array access");
- if (destination_offset <= source_offset) {
- for (u32 i = 0; i < count; ++i)
- destination.elements()[destination_offset + i] = source.elements()[source_offset + i];
- } else {
- for (u32 i = count; i > 0; --i)
- destination.elements()[destination_offset + i - 1] = source.elements()[source_offset + i - 1];
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_init_data)
-{
- LOG_INSN;
- auto& args = instruction->arguments().get<Instruction::ArrayDataArgs>();
- auto& value_stack = configuration.value_stack();
- auto count = value_stack.take_last().to<u32>();
- auto source_offset = value_stack.take_last().to<u32>();
- auto destination_offset = value_stack.take_last().to<u32>();
- auto reference = value_stack.take_last();
- GC_TRAP_IF(is_null_gc_reference(reference), "null array reference");
- auto& instance = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(reference.value().low()));
- GC_TRAP_IF(static_cast<u64>(destination_offset) + count > instance.elements().size(), "out of bounds array access");
- auto const& field_type = configuration.frame().module().canonical_types()[args.type_index.value()]->expansion().get<ArrayType>().type();
- auto const element_size = storage_type_byte_width(field_type.type());
- auto const& data = *configuration.store().get(configuration.frame().module().datas()[args.data_index.value()]);
- GC_TRAP_IF(static_cast<u64>(source_offset) + static_cast<u64>(count) * element_size > data.size(), "out of bounds memory access");
- auto bytes = data.data().span();
- for (u32 i = 0; i < count; ++i)
- instance.elements()[destination_offset + i] = value_from_segment_bytes(field_type.type(), bytes.slice(source_offset + static_cast<size_t>(i) * element_size, element_size));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(array_init_elem)
-{
- LOG_INSN;
- auto& args = instruction->arguments().get<Instruction::ArrayElemArgs>();
- auto& value_stack = configuration.value_stack();
- auto count = value_stack.take_last().to<u32>();
- auto source_offset = value_stack.take_last().to<u32>();
- auto destination_offset = value_stack.take_last().to<u32>();
- auto reference = value_stack.take_last();
- GC_TRAP_IF(is_null_gc_reference(reference), "null array reference");
- auto& instance = *static_cast<ArrayInstance*>(bit_cast<GC::Cell*>(reference.value().low()));
- GC_TRAP_IF(static_cast<u64>(destination_offset) + count > instance.elements().size(), "out of bounds array access");
- auto const& references = configuration.store().get(configuration.frame().module().elements()[args.element_index.value()])->references();
- GC_TRAP_IF(static_cast<u64>(source_offset) + count > references.size(), "out of bounds table access");
- for (u32 i = 0; i < count; ++i)
- instance.elements()[destination_offset + i] = Value(references[source_offset + i]);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(ref_test)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- slot = Value(static_cast<i32>(reference_matches_type(slot, instruction->arguments().get<ValueType>(), configuration) ? 1 : 0));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-ALIAS_INSTRUCTION(ref_test_null, ref_test)
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(ref_cast)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto const& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- GC_TRAP_IF(!reference_matches_type(slot, instruction->arguments().get<ValueType>(), configuration), "cast failure");
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-ALIAS_INSTRUCTION(ref_cast_null, ref_cast)
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#control-instructions
-HANDLE_INSTRUCTION(br_on_cast)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::BranchOnCastArgs>();
- // bounds checked by verifier.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto const matches = reference_matches_type(value, args.target_type, configuration);
- configuration.value_stack().append(value);
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, args.branch.label, short_ip.current_ip_value, matches).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#control-instructions
-HANDLE_INSTRUCTION(br_on_cast_fail)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& args = instruction->arguments().get<Instruction::BranchOnCastArgs>();
- // bounds checked by verifier.
- auto value = configuration.take_source<source_address_mix>(0, addresses.sources);
- auto const matches = reference_matches_type(value, args.target_type, configuration);
- configuration.value_stack().append(value);
- short_ip.current_ip_value = interpreter.branch_to_label<true>(configuration, args.branch.label, short_ip.current_ip_value, !matches).value();
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(any_convert_extern)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- auto const low = slot.value().low();
- switch (slot.value().high()) {
- case 3:
- slot = Value(u128(0, 8));
- break;
- case 1:
- slot = Value(u128(low, 10));
- break;
- case 9 | (6 << 8):
- slot = Value(u128(low, 6));
- break;
- case 9 | (7 << 8):
- slot = Value(u128(low, 7));
- break;
- default:
- break;
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(extern_convert_any)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- auto const low = slot.value().low();
- switch (slot.value().high()) {
- case 8:
- slot = Value(u128(0, 3));
- break;
- case 6:
- slot = Value(u128(low, 9 | (6 << 8)));
- break;
- case 7:
- slot = Value(u128(low, 9 | (7 << 8)));
- break;
- case 10:
- slot = Value(u128(low, 1));
- break;
- default:
- break;
- }
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(ref_i31)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- slot = Value(u128(static_cast<u64>(slot.template to<u32>() & 0x7fffffff), 7));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#reference-instructions
-HANDLE_INSTRUCTION(i31_get_s)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- GC_TRAP_IF(is_null_gc_reference(slot), "null i31 reference");
- auto const payload = static_cast<u32>(slot.value().low() & 0x7fffffff);
- slot = Value(static_cast<i32>(payload << 1) >> 1);
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-HANDLE_INSTRUCTION(i31_get_u)
-{
- LOG_INSN;
- LOAD_ADDRESSES();
- auto& slot = configuration.source_value<source_address_mix>(0, addresses.sources); // bounds checked by verifier.
- GC_TRAP_IF(is_null_gc_reference(slot), "null i31 reference");
- slot = Value(static_cast<u32>(slot.value().low() & 0x7fffffff));
- TAILCALL return continue_(HANDLER_PARAMS(DECOMPOSE_PARAMS_NAME_ONLY));
-}
-
-#undef GC_TRAP_IF
-
-bool BytecodeInterpreter::trap_if_insufficient_native_stack_space(size_t minimum_native_stack_space_to_keep_free)
-{
- return trap_if_not(m_stack_info.size_free() >= minimum_native_stack_space_to_keep_free, Constants::stack_exhaustion_message);
-}
-
-template<u64 opcode, bool HasDynamicInsnLimit, typename Continue, SourceAddressMix mix, typename... Args>
-constexpr static auto handle_instruction(Args&&... a)
-{
- return InstructionHandler<opcode>::template operator()<HasDynamicInsnLimit, Continue, mix>(forward<Args>(a)...);
-}
-
-template<bool HasCompiledList, bool HasDynamicInsnLimit, bool HaveDirectThreadingInfo>
-FLATTEN void BytecodeInterpreter::interpret_impl(Configuration& configuration, Expression const& expression)
-{
- auto& instructions = expression.instructions();
- u64 executed_instructions = 0;
- ShortenedIP short_ip { .current_ip_value = static_cast<u32>(configuration.ip()) };
-
- auto cc = expression.compiled_instructions.dispatches.data();
- auto addresses_ptr = expression.compiled_instructions.src_dst_mappings.data();
-
- if constexpr (HaveDirectThreadingInfo) {
- static_assert(HasCompiledList, "Direct threading requires a compiled instruction list");
- auto const instruction = cc[short_ip.current_ip_value].instruction;
- auto const handler = bit_cast<Outcome (*)(HANDLER_PARAMS(DECOMPOSE_PARAMS_TYPE_ONLY))>(cc[short_ip.current_ip_value].handler_ptr);
- handler(*this, configuration, instruction, short_ip, cc, addresses_ptr);
- return;
- }
-
- while (true) {
- if constexpr (HasDynamicInsnLimit) {
- if (executed_instructions++ >= Constants::max_allowed_executed_instructions_per_call) [[unlikely]] {
- m_trap = Trap::from_string("Exceeded maximum allowed number of instructions");
- return;
- }
- }
- // bounds checked by loop condition.
- auto const instruction = HasCompiledList
- ? cc[short_ip.current_ip_value].instruction
- : &instructions.data()[short_ip.current_ip_value];
- auto const opcode = (HasCompiledList && !HaveDirectThreadingInfo
- ? cc[short_ip.current_ip_value].instruction_opcode
- : instruction->opcode())
- .value();
-
-#define RUN_NEXT_INSTRUCTION() \
- { \
- ++short_ip.current_ip_value; \
- break; \
- }
-
-#define HANDLE_INSTRUCTION_NEW(name, ...) \
- case Instructions::name.value(): { \
- auto outcome = handle_instruction<Instructions::name.value(), HasDynamicInsnLimit, Skip, SourceAddressMix::Any>(*this, configuration, instruction, short_ip, cc, addresses_ptr); \
- if (outcome == Outcome::Return) \
- return; \
- short_ip.current_ip_value = to_underlying(outcome); \
- if constexpr (first_is_one_of(Instructions::name, Instructions::return_call, Instructions::return_call_indirect, Instructions::return_call_ref)) { \
- cc = configuration.frame().expression().compiled_instructions.dispatches.data(); \
- addresses_ptr = configuration.frame().expression().compiled_instructions.src_dst_mappings.data(); \
- } \
- RUN_NEXT_INSTRUCTION(); \
- }
-
- dbgln_if(WASM_TRACE_DEBUG, "Executing instruction {} at current_ip_value {}", instruction_name(instruction->opcode()), short_ip.current_ip_value);
- if ((opcode & Instructions::SyntheticInstructionBase.value()) != Instructions::SyntheticInstructionBase.value())
- __builtin_prefetch(&instruction->arguments(), /* read */ 0, /* low temporal locality */ 1);
-
- switch (opcode) {
- ENUMERATE_WASM_OPCODES(HANDLE_INSTRUCTION_NEW)
- default:
- dbgln("Bad opcode {} in insn {} (ip {})", opcode, instruction_name(instruction->opcode()), short_ip.current_ip_value);
- VERIFY_NOT_REACHED();
- }
- }
-}
-
-template<bool NeedsStackAdjustment>
-InstructionPointer BytecodeInterpreter::branch_to_label(Configuration& configuration, LabelIndex index, InstructionPointer current_ip, bool actually_branching)
-{
- dbgln_if(WASM_TRACE_DEBUG, "Branch to label with index {}...", index.value());
- auto& label_stack = configuration.label_stack();
- label_stack.unsafe_shrink(actually_branching ? label_stack.size() - index.value() : label_stack.size());
- auto const& label = configuration.label_stack().unsafe_last();
- dbgln_if(WASM_TRACE_DEBUG, "...which is actually IP {}, and has {} result(s)", label.continuation().value(), label.arity());
-
- if constexpr (NeedsStackAdjustment) {
- if (actually_branching)
- configuration.value_stack().remove(label.stack_height(), configuration.value_stack().size() - label.stack_height() - label.arity());
- }
- return actually_branching ? label.continuation().value() - 1 : current_ip;
-}
-
-// https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-throw-ref
-Optional<InstructionPointer> BytecodeInterpreter::unwind_to_throw_handler(Configuration& configuration, ExceptionAddress exception_address)
-{
- auto& exception = *configuration.store().get(exception_address);
- auto& label_stack = configuration.label_stack();
- auto& frame = configuration.frame();
- auto const frame_label_index = frame.label_index();
- for (size_t label_index = label_stack.size(); label_index > frame_label_index + 1;) {
- --label_index;
- auto const& label = label_stack.data()[label_index];
- auto const* try_table_instruction = label.try_table_instruction();
- if (!try_table_instruction)
- continue;
- auto& args = try_table_instruction->arguments().unsafe_get<Instruction::TryTableArgs>();
- for (auto& catch_ : args.catches()) {
- // catch x l / catch_ref x l match if exns[a].tag = z.module.tags[x];
- // catch_all l / catch_all_ref l match any exception.
- if (auto tag_index = catch_.matching_tag_index(); tag_index.has_value()) {
- if (frame.module().tags()[tag_index->value()] != exception.tag())
- continue;
- }
- // Matched: the handler and its label should be removed, and the exception's fields (plus the exnref for the _ref forms) replace them...
- auto& value_stack = configuration.value_stack();
- value_stack.shrink(label.stack_height(), true);
- if (catch_.matching_tag_index().has_value()) {
- value_stack.ensure_capacity(value_stack.size() + exception.params().size());
- for (auto& field : exception.params())
- value_stack.unchecked_append(field);
- }
- if (catch_.is_ref())
- value_stack.append(Value(Reference { Reference::Exception { exception_address } }));
- label_stack.unsafe_shrink(label_index);
- // ...followed by (br l), with l relative to the context outside the try_table.
- label_stack.unsafe_shrink(label_stack.size() - catch_.target_label().value());
- auto const& target = label_stack.unsafe_last();
- value_stack.remove(target.stack_height(), value_stack.size() - target.stack_height() - target.arity());
- return target.continuation();
- }
- }
- // No handler in this frame matched; drop its labels (the frame is being unwound) so that a re-dispatch in the calling frame only ever sees that frame's own (still active) handlers.
- label_stack.shrink(frame_label_index, true);
- return {};
-}
-
-template<typename ReadType, typename PushType, SourceAddressMix mix>
-bool BytecodeInterpreter::load_and_push(Configuration& configuration, Instruction const& instruction, SourcesAndDestination const& addresses)
-{
- auto& arg = instruction.arguments().unsafe_get<Instruction::MemoryArgument>();
- auto& address = configuration.frame().module().memories().data()[arg.memory_index.value()];
- auto memory = configuration.store().unsafe_get(address);
- auto& entry = configuration.source_value<mix>(0, addresses.sources); // bounds checked by verifier.
- auto base = memory_base_address(*memory, entry);
- Checked<u64> end_address { base };
- end_address += arg.offset;
- end_address += sizeof(ReadType);
- u64 instance_address = base + arg.offset;
- dbgln_if(WASM_TRACE_DEBUG, "load({} : {}) -> stack", instance_address, sizeof(ReadType));
- if (end_address.has_overflow() || end_address.value() > memory->size()) {
- m_trap = Trap::from_string("Memory access out of bounds");
- dbgln_if(WASM_TRACE_DEBUG, "LibWasm: load_and_push - Memory access out of bounds (expected {} to be less than or equal to {})", instance_address + sizeof(ReadType), memory->size());
- return true;
- }
- entry = Value(static_cast<PushType>(read_value<ReadType>({ memory->data().offset_pointer(instance_address), sizeof(ReadType) })));
- dbgln_if(WASM_TRACE_DEBUG, " loaded value: {}", entry.value());
- return false;
-}
-
-template<typename TDst, typename TSrc>
-ALWAYS_INLINE static TDst convert_vector(TSrc v)
-{
- return __builtin_convertvector(v, TDst);
-}
-
-template<size_t M, size_t N, template<typename> typename SetSign>
-bool BytecodeInterpreter::load_and_push_mxn(Configuration& configuration, Instruction const& instruction, SourcesAndDestination const& addresses)
-{
- auto& arg = instruction.arguments().unsafe_get<Instruction::MemoryArgument>();
- auto& address = configuration.frame().module().memories().data()[arg.memory_index.value()];
- auto memory = configuration.store().unsafe_get(address);
- auto& entry = configuration.source_value<SourceAddressMix::Any>(0, addresses.sources); // bounds checked by verifier.
- auto base = memory_base_address(*memory, entry);
- Checked<u64> end_address { base };
- end_address += arg.offset;
- end_address += M * N / 8;
- u64 instance_address = base + arg.offset;
- dbgln_if(WASM_TRACE_DEBUG, "vec-load({} : {}) -> stack", instance_address, M * N / 8);
- if (end_address.has_overflow() || end_address.value() > memory->size()) {
- m_trap = Trap::from_string("Memory access out of bounds");
- return true;
- }
- auto const* data = memory->data().offset_pointer(instance_address);
- using V64 = NativeVectorType<M, N, SetSign>;
- using V128 = NativeVectorType<M * 2, N, SetSign>;
-
- V64 bytes { 0 };
- if (bit_cast<FlatPtr>(data) % sizeof(V64) == 0)
- bytes = *bit_cast<V64 const*>(data);
- else
- ByteReader::load(data, bytes);
-
- entry = Value(bit_cast<u128>(convert_vector<V128>(bytes)));
- dbgln_if(WASM_TRACE_DEBUG, " loaded value: {}", entry.value());
- return false;
-}
-
-template<size_t N>
-bool BytecodeInterpreter::load_and_push_lane_n(Configuration& configuration, Instruction const& instruction, SourcesAndDestination const& addresses)
-{
- auto memarg_and_lane = instruction.arguments().unsafe_get<Instruction::MemoryAndLaneArgument>();
- auto& address = configuration.frame().module().memories().data()[memarg_and_lane.memory.memory_index.value()];
- auto memory = configuration.store().unsafe_get(address);
- // bounds checked by verifier.
- auto vector = configuration.take_source<SourceAddressMix::Any>(0, addresses.sources).template to<u128>();
- auto base = memory_base_address(*memory, configuration.take_source<SourceAddressMix::Any>(1, addresses.sources));
- Checked<u64> end_address { base };
- end_address += memarg_and_lane.memory.offset;
- end_address += N / 8;
- u64 instance_address = base + memarg_and_lane.memory.offset;
- dbgln_if(WASM_TRACE_DEBUG, "load-lane({} : {}, lane {}) -> stack", instance_address, N / 8, memarg_and_lane.lane);
- if (end_address.has_overflow() || end_address.value() > memory->size()) {
- m_trap = Trap::from_string("Memory access out of bounds");
- return true;
- }
- auto dst = bit_cast<u8*>(&vector) + memarg_and_lane.lane * N / 8;
- memory->data().copy_to(instance_address, { dst, N / 8 });
- dbgln_if(WASM_TRACE_DEBUG, " loaded value: {}", vector);
- configuration.push_to_destination<SourceAddressMix::Any>(Value(vector), addresses.destination);
- return false;
-}
-
-template<size_t N>
-bool BytecodeInterpreter::load_and_push_zero_n(Configuration& configuration, Instruction const& instruction, SourcesAndDestination const& addresses)
-{
- auto memarg_and_lane = instruction.arguments().unsafe_get<Instruction::MemoryArgument>();
- auto& address = configuration.frame().module().memories().data()[memarg_and_lane.memory_index.value()];
- auto memory = configuration.store().unsafe_get(address);
- // bounds checked by verifier.
- auto base = memory_base_address(*memory, configuration.take_source<SourceAddressMix::Any>(0, addresses.sources));
- Checked<u64> end_address { base };
- end_address += memarg_and_lane.offset;
- end_address += N / 8;
- u64 instance_address = base + memarg_and_lane.offset;
- dbgln_if(WASM_TRACE_DEBUG, "load-zero({} : {}) -> stack", instance_address, N / 8);
- if (end_address.has_overflow() || end_address.value() > memory->size()) {
- m_trap = Trap::from_string("Memory access out of bounds");
- return true;
- }
- u128 vector = 0;
- memory->data().copy_to(instance_address, { bit_cast<u8*>(&vector), N / 8 });
- dbgln_if(WASM_TRACE_DEBUG, " loaded value: {}", vector);
- configuration.push_to_destination<SourceAddressMix::Any>(Value(vector), addresses.destination);
- return false;
-}
-
-template<size_t M>
-bool BytecodeInterpreter::load_and_push_m_splat(Configuration& configuration, Instruction const& instruction, SourcesAndDestination const& addresses)
-{
- auto& arg = instruction.arguments().unsafe_get<Instruction::MemoryArgument>();
- auto& address = configuration.frame().module().memories().data()[arg.memory_index.value()];
- auto memory = configuration.store().unsafe_get(address);
- auto& entry = configuration.source_value<SourceAddressMix::Any>(0, addresses.sources); // bounds checked by verifier.
- auto base = memory_base_address(*memory, entry);
- Checked<u64> end_address { base };
- end_address += arg.offset;
- end_address += M / 8;
- u64 instance_address = base + arg.offset;
- dbgln_if(WASM_TRACE_DEBUG, "vec-splat({} : {}) -> stack", instance_address, M / 8);
- if (end_address.has_overflow() || end_address.value() > memory->size()) {
- m_trap = Trap::from_string("Memory access out of bounds");
- return true;
- }
- auto value = read_value<NativeIntegralType<M>>({ memory->data().offset_pointer(instance_address), M / 8 });
- dbgln_if(WASM_TRACE_DEBUG, " loaded value: {}", value);
- set_top_m_splat<M, NativeIntegralType>(configuration, value, addresses);
- return false;
-}
-
-template<size_t M, template<size_t> typename NativeType>
-void BytecodeInterpreter::set_top_m_splat(Wasm::Configuration& configuration, NativeType<M> value, SourcesAndDestination const& addresses)
-{
- auto push = [&](auto result) {
- configuration.source_value<SourceAddressMix::Any>(0, addresses.sources) = Value(bit_cast<u128>(result));
- };
-
- if constexpr (IsFloatingPoint<NativeType<32>>) {
- if constexpr (M == 32) // 32 -> 32x4
- push(expand4(value));
- else if constexpr (M == 64) // 64 -> 64x2
- push(f64x2 { value, value });
- else
- static_assert(DependentFalse<NativeType<M>>, "Invalid vector size");
- } else {
- if constexpr (M == 8) // 8 -> 8x4 -> 32x4
- push(expand4(bit_cast<u32>(u8x4 { value, value, value, value })));
- else if constexpr (M == 16) // 16 -> 16x2 -> 32x4
- push(expand4(bit_cast<u32>(u16x2 { value, value })));
- else if constexpr (M == 32) // 32 -> 32x4
- push(expand4(value));
- else if constexpr (M == 64) // 64 -> 64x2
- push(u64x2 { value, value });
- else
- static_assert(DependentFalse<NativeType<M>>, "Invalid vector size");
- }
-}
-
-template<size_t M, template<size_t> typename NativeType>
-void BytecodeInterpreter::pop_and_push_m_splat(Wasm::Configuration& configuration, Instruction const&, SourcesAndDestination const& addresses)
-{
- using PopT = Conditional<M <= 32, NativeType<32>, NativeType<64>>;
- using ReadT = NativeType<M>;
- auto entry = configuration.source_value<SourceAddressMix::Any>(0, addresses.sources);
- auto value = static_cast<ReadT>(entry.template to<PopT>());
- dbgln_if(WASM_TRACE_DEBUG, "stack({}) -> splat({})", value, M);
- set_top_m_splat<M, NativeType>(configuration, value, addresses);
-}
-
-template<typename M, template<typename> typename SetSign, typename VectorType>
-VectorType BytecodeInterpreter::pop_vector(Configuration& configuration, size_t source, SourcesAndDestination const& addresses)
-{
- // bounds checked by verifier.
- return bit_cast<VectorType>(configuration.take_source<SourceAddressMix::Any>(source, addresses.sources).template to<u128>());
-}
-
-Outcome BytecodeInterpreter::call_address(Configuration& configuration, FunctionAddress address, SourcesAndDestination const& addresses, CallAddressSource source, CallType call_type)
-{
- TRAP_IF_NOT(m_stack_info.size_free() >= Constants::minimum_stack_space_to_keep_free, "{}: {}", Constants::stack_exhaustion_message);
- Result result { Trap::from_string("") };
- Outcome final_outcome = Outcome::Continue;
- {
- Optional<ScopedValueRollback<decltype(configuration.regs)>> regs_rollback;
-
- if (call_type == CallType::UsingRegisters || call_type == CallType::UsingCallRecord)
- regs_rollback = ScopedValueRollback { configuration.regs };
-
- auto instance = configuration.store().get(address);
- FunctionType const* type { nullptr };
- instance->visit([&](auto const& function) { type = &function.type(); });
- if (source == CallAddressSource::IndirectCall || source == CallAddressSource::IndirectTailCall) {
- TRAP_IF_NOT(type->parameters().size() <= configuration.value_stack().size());
- }
- Vector<Value, ArgumentsStaticSize> args;
-
- if (call_type == CallType::UsingCallRecord) {
- auto param_count = type->parameters().size();
- configuration.get_arguments_allocation_if_possible(args, param_count);
- args.ensure_capacity(param_count);
- for (size_t i = 0; i < param_count; ++i)
- args.unchecked_append(configuration.call_record_entry(i));
- } else {
- configuration.get_arguments_allocation_if_possible(args, type->parameters().size());
-
- {
- auto param_count = type->parameters().size();
- if (param_count) {
- args.ensure_capacity(param_count);
- if (call_type == CallType::UsingRegisters) {
- args.resize_and_keep_capacity(param_count);
- for (size_t i = 0; i < param_count; ++i)
- args[param_count - i - 1] = configuration.take_source<SourceAddressMix::Any>(i, addresses.sources);
- } else {
- auto span = configuration.value_stack().span().slice_from_end(param_count);
- for (auto& value : span)
- args.unchecked_append(value);
-
- configuration.value_stack().remove(configuration.value_stack().size() - span.size(), span.size());
- }
- }
- }
- }
-
- if (source == CallAddressSource::DirectTailCall || source == CallAddressSource::IndirectTailCall) {
- auto prep_outcome = configuration.prepare_call(address, args, true);
- if (prep_outcome.is_error()) {
- m_trap = prep_outcome.release_error();
- return Outcome::Return;
- }
-
- final_outcome = Outcome::Return; // At this point we can only ever return (unless we succeed in tail-calling).
- if (prep_outcome.value().has_value()) {
- result = prep_outcome.value()->function()(configuration, args);
- configuration.release_arguments_allocation(args);
- } else {
- configuration.ip() = 0;
- return static_cast<Outcome>(0); // Continue from IP 0 in the new frame.
- }
- } else {
- if (instance->has<WasmFunction>()) {
- CallFrameHandle handle { *this, configuration };
- result = configuration.call(*this, address, args);
- } else {
- result = configuration.call(*this, address, args);
- configuration.release_arguments_allocation(args);
- }
- }
-
- if (result.is_trap()) {
- // https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-throw-ref
- if (auto const* uncaught_exception = result.trap().data.get_pointer<UncaughtException>(); uncaught_exception && final_outcome == Outcome::Continue) {
- if (auto continuation = unwind_to_throw_handler(configuration, uncaught_exception->address); continuation.has_value()) {
- // The callee's interpret() left the exception in m_trap; it's handled now.
- m_trap = Empty {};
- return static_cast<Outcome>(continuation->value());
- }
- }
- m_trap = move(result.trap());
- return Outcome::Return;
- }
- }
-
- if (!result.values().is_empty()) {
- if (call_type == CallType::UsingRegisters || call_type == CallType::UsingCallRecord || result.values().size() == 1) {
- configuration.push_to_destination<SourceAddressMix::Any>(result.values().take_first(), addresses.destination);
- } else {
- configuration.value_stack().ensure_capacity(configuration.value_stack().size() + result.values().size());
- for (auto& entry : result.values().in_reverse())
- configuration.value_stack().unchecked_append(entry);
- }
- }
-
- return final_outcome;
-}
-
-template<typename PopTypeLHS, typename PushType, typename Operator, SourceAddressMix mix, typename PopTypeRHS, typename... Args>
-bool BytecodeInterpreter::binary_numeric_operation(Configuration& configuration, SourcesAndDestination const& addresses, Args&&... args)
-{
- // bounds checked by Nor.
- auto rhs = configuration.take_source<mix>(0, addresses.sources).template to<PopTypeRHS>();
- auto& lhs_slot = configuration.source_value<mix>(1, addresses.sources); // bounds checked by verifier.
- auto lhs = lhs_slot.template to<PopTypeLHS>();
- PushType result;
- auto call_result = Operator { forward<Args>(args)... }(lhs, rhs);
- if constexpr (IsSpecializationOf<decltype(call_result), AK::ErrorOr>) {
- if (call_result.is_error())
- return trap_if_not(false, call_result.error());
- result = call_result.release_value();
- } else {
- result = call_result;
- }
- dbgln_if(WASM_TRACE_DEBUG, "{} {} {} = {}", lhs, Operator::name(), rhs, result);
- lhs_slot = Value(result);
- return false;
-}
-
-template<typename PopType, typename PushType, typename Operator, SourceAddressMix mix, size_t input_arg, typename... Args>
-bool BytecodeInterpreter::unary_operation(Configuration& configuration, SourcesAndDestination const& addresses, Args&&... args)
-{
- auto& entry = configuration.source_value<mix>(input_arg, addresses.sources); // bounds checked by verifier.
- auto value = entry.template to<PopType>();
- auto call_result = Operator { forward<Args>(args)... }(value);
- PushType result;
- if constexpr (IsSpecializationOf<decltype(call_result), AK::ErrorOr>) {
- if (call_result.is_error())
- return trap_if_not(false, call_result.error());
- result = call_result.release_value();
- } else {
- result = call_result;
- }
- dbgln_if(WASM_TRACE_DEBUG, "map({}) {} = {}", Operator::name(), value, result);
- entry = Value(result);
- return false;
-}
-
-template<typename PopT, typename StoreT>
-bool BytecodeInterpreter::pop_and_store(Configuration& configuration, Instruction const& instruction, SourcesAndDestination const& addresses)
-{
- // bounds checked by verifier.
- auto entry = configuration.take_source<SourceAddressMix::Any>(0, addresses.sources);
- auto value = ConvertToRaw<StoreT> {}(entry.template to<PopT>());
- return store_value(configuration, instruction, value, 1, addresses);
-}
-
-template<typename StoreT>
-bool BytecodeInterpreter::store_value(Configuration& configuration, Instruction const& instruction, StoreT value, size_t address_source, SourcesAndDestination const& addresses)
-{
- auto& memarg = instruction.arguments().unsafe_get<Instruction::MemoryArgument>();
- dbgln_if(WASM_TRACE_DEBUG, "stack({}) -> temporary({}b)", value, sizeof(StoreT));
- auto base = configuration.take_source<SourceAddressMix::Any>(address_source, addresses.sources);
- return store_to_memory(configuration, memarg, { &value, sizeof(StoreT) }, base);
-}
-
-template<size_t N>
-bool BytecodeInterpreter::pop_and_store_lane_n(Configuration& configuration, Instruction const& instruction, SourcesAndDestination const& addresses)
-{
- auto& memarg_and_lane = instruction.arguments().unsafe_get<Instruction::MemoryAndLaneArgument>();
- // bounds checked by verifier.
- auto vector = configuration.take_source<SourceAddressMix::Any>(0, addresses.sources).template to<u128>();
- auto src = bit_cast<u8*>(&vector) + memarg_and_lane.lane * N / 8;
- auto base = configuration.take_source<SourceAddressMix::Any>(1, addresses.sources);
- return store_to_memory(configuration, memarg_and_lane.memory, { src, N / 8 }, base);
-}
-
-bool BytecodeInterpreter::store_to_memory(Configuration& configuration, Instruction::MemoryArgument const& arg, ReadonlyBytes data, Value const& base_value)
-{
- auto const& address = configuration.frame().module().memories().data()[arg.memory_index.value()];
- auto memory = configuration.store().unsafe_get(address);
- Checked<u64> instance_address { memory_base_address(*memory, base_value) };
- instance_address += arg.offset;
- if (instance_address.has_overflow()) [[unlikely]] {
- m_trap = Trap::from_string("Memory access out of bounds");
- return true;
- }
- return store_to_memory(*memory, instance_address.value(), data);
-}
-
-template<typename T>
-bool BytecodeInterpreter::store_to_memory(MemoryInstance& memory, u64 address, T value)
-{
- Checked addition { address };
- size_t data_size;
- if constexpr (IsSame<ReadonlyBytes, T>)
- data_size = value.size();
- else
- data_size = sizeof(T);
-
- addition += data_size;
- if (addition.has_overflow() || addition.value() > memory.size()) [[unlikely]] {
- m_trap = Trap::from_string("Memory access out of bounds");
- return true;
- }
-
- dbgln_if(WASM_TRACE_DEBUG, "temporary({}b) -> store({})", data_size, address);
- if constexpr (IsSame<ReadonlyBytes, T>)
- memory.data().overwrite(address, value.data(), data_size);
- else
- memory.data().overwrite(address, &value, data_size);
- return false;
-}
-
-template<typename T>
-T BytecodeInterpreter::read_value(ReadonlyBytes data)
-{
- VERIFY(sizeof(T) <= data.size());
- if (bit_cast<FlatPtr>(data.data()) % alignof(T)) {
- alignas(T) u8 buf[sizeof(T)];
- memcpy(buf, data.data(), sizeof(T));
- return bit_cast<LittleEndian<T>>(buf);
- }
- return *bit_cast<LittleEndian<T> const*>(data.data());
-}
-
-template<>
-float BytecodeInterpreter::read_value<float>(ReadonlyBytes data)
-{
- return bit_cast<float>(read_value<u32>(data));
-}
-
-template<>
-double BytecodeInterpreter::read_value<double>(ReadonlyBytes data)
-{
- return bit_cast<double>(read_value<u64>(data));
-}
-
-void InstructionStorage::add_chunk()
-{
- static constexpr size_t initial_chunk_capacity = 8;
- static constexpr size_t max_chunk_capacity = 512;
- auto chunk_capacity = clamp(m_capacity, initial_chunk_capacity, max_chunk_capacity);
- m_chunks.append(Chunk::must_create_but_fixme_should_propagate_errors(chunk_capacity));
- m_capacity += chunk_capacity;
- m_next_index_in_last_chunk = 0;
-}
-
-Instruction& InstructionStorage::append(Instruction instruction)
-{
- if (m_chunks.is_empty() || m_next_index_in_last_chunk == m_chunks.unsafe_last().size())
- add_chunk();
-
- auto& slot = m_chunks.unsafe_last()[m_next_index_in_last_chunk++];
- slot = move(instruction);
- ++m_size;
- return slot.value();
-}
-
-CompiledInstructions try_compile_instructions(Expression const& expression, Span<FunctionType const> functions, Span<CodeSection::Func const* const> callee_bodies, size_t current_function_index, size_t caller_local_count, size_t imported_function_count)
-{
- CompiledInstructions result;
-
- auto instruction_count = expression.instructions().size();
- result.dispatches.ensure_capacity(instruction_count);
- result.src_dst_mappings.ensure_capacity(instruction_count);
-
- i32 i32_const_value { 0 };
- i64 i64_const_value { 0 };
- LocalIndex local_index_0 { 0 };
- LocalIndex local_index_1 { 0 };
- enum class InsnPatternState {
- Nothing,
- GetLocal,
- GetLocalI32Const,
- GetLocalI64Const,
- GetLocalx2,
- I32Const,
- I32ConstGetLocal,
- I64Const,
- I64ConstGetLocal,
- } pattern_state { InsnPatternState::Nothing };
- static auto& nop = *new Instruction { Instructions::nop };
-
- size_t calls_in_expression = 0;
-
- auto append_extra_instruction = [&result](auto&&... args) -> Instruction& {
- return result.extra_instruction_storage.append(Instruction(forward<decltype(args)>(args)...));
- };
-
- auto const set_default_dispatch = [&result](Instruction const& instruction, size_t index = NumericLimits<size_t>::max()) {
- if (index < result.dispatches.size()) {
- result.dispatches[index] = { { .instruction_opcode = instruction.opcode() }, &instruction };
- result.src_dst_mappings[index] = { .sources = { Dispatch::Stack, Dispatch::Stack, Dispatch::Stack }, .destination = Dispatch::Stack };
- } else {
- result.dispatches.append({ { .instruction_opcode = instruction.opcode() }, &instruction });
- result.src_dst_mappings.append({ .sources = { Dispatch::Stack, Dispatch::Stack, Dispatch::Stack }, .destination = Dispatch::Stack });
- }
- };
-
- auto callee_if_inlineable = [&](size_t func_index) -> CodeSection::Func const* {
- if (func_index >= callee_bodies.size() || func_index >= current_function_index)
- return nullptr; // import, forward reference, or self (cannot inline)
-
- auto const* callee = callee_bodies[func_index];
- if (!callee)
- return nullptr;
-
- auto const& ci = callee->body().compiled_instructions;
- if (!ci.cranelift_eligible)
- return nullptr;
-
- if (callee->body().instructions().size() > 96) // Value arbitrarily chosen based on vibes.
- return nullptr;
-
- if (functions[func_index].results().size() > 1 || functions[func_index].parameters().size() > 8)
- return nullptr;
-
- for (auto const& local : callee->locals()) {
- // Wasm semantics want locals to be zeroed on entry, but we're reusing locals across multiple inlined sites;
- // we can't zero reference-typed locals without potentially dropping a live reference, so reject those callees.
- if (local.type().is_reference())
- return nullptr;
- }
- for (auto& gi : callee->body().instructions()) {
- if (first_is_one_of(gi.opcode(),
- Instructions::call, Instructions::call_indirect,
- Instructions::return_call, Instructions::return_call_indirect,
- Instructions::call_ref, Instructions::return_call_ref))
- return nullptr;
- }
- return callee;
- };
-
- size_t inlined_local_count = 0;
- auto did_inline = false;
- Vector<Instruction const*> expanded;
- expanded.ensure_capacity(instruction_count);
-
- Vector<size_t> wasm_ip_to_expanded;
- wasm_ip_to_expanded.resize(expression.instructions().size());
-
- Vector<size_t> caller_structured_positions;
- auto append_caller = [&](Instruction const& insn) {
- if (insn.arguments().has<Instruction::StructuredInstructionArgs>() || insn.arguments().has<Instruction::TryTableArgs>())
- caller_structured_positions.append(expanded.size());
- expanded.append(&insn);
- };
-
- auto is_local_op = [](OpCode op) { return first_is_one_of(op, Instructions::local_get, Instructions::local_set, Instructions::local_tee); };
-
- size_t wasm_ip = 0;
- for (auto& instruction : expression.instructions()) {
- wasm_ip_to_expanded[wasm_ip++] = expanded.size();
- if (instruction.opcode() == Instructions::call) {
- auto func_index = instruction.arguments().get<FunctionIndex>().value();
- if (auto const* callee = callee_if_inlineable(func_index)) {
- // Reuse a range above the caller's locals for the callee's locals, and remap all local accesses in the callee to that range,
- // Currently the locals are allocated on the stack for up to 64 locals, so avoid inlining if the callee's locals would exceed that limit (with some headroom for the parameters).
- size_t base = caller_local_count;
- size_t g_params = functions[func_index].parameters().size();
- size_t g_total = g_params + callee->total_local_count();
- if (base + g_total > 56) {
- append_caller(instruction);
- continue;
- }
- for (size_t p = g_params; p-- > 0;)
- expanded.append(&append_extra_instruction(Instruction(Instructions::local_set, LocalIndex { static_cast<u32>(base + p) })));
-
- // Zero-init all callee locals on "entry", note that we drop reference-typed locals above, so a normal zero-init is safe here.
- for (size_t l = 0; l < callee->total_local_count(); ++l)
- expanded.append(&append_extra_instruction(Instructions::synthetic_local_seti32_const, LocalIndex { static_cast<u32>(base + g_params + l) }, static_cast<i32>(0)));
-
- auto callee_cfg = false;
- for (auto& gi : callee->body().instructions()) {
- if (first_is_one_of(gi.opcode(),
- Instructions::block, Instructions::loop, Instructions::if_, Instructions::return_,
- Instructions::br, Instructions::br_if, Instructions::br_table)) {
- callee_cfg = true;
- break;
- }
- }
-
- if (!callee_cfg) {
- for (auto& gi : callee->body().instructions()) {
- if (gi.opcode() == Instructions::synthetic_end_expression)
- continue; // drop the trailing function-end marker
- if (is_local_op(gi.opcode()))
- expanded.append(&append_extra_instruction(Instruction(gi.opcode(), LocalIndex { static_cast<u32>(gi.local_index().value() + base) })));
- else
- expanded.append(&gi);
- }
- } else {
- // The function being inlined has some control flow, wrap it in a block and rewrite `return` to `br` out of the wrapper so that the inlined code can exit to the caller.
- auto block_type = functions[func_index].results().is_empty() ? BlockType {} : BlockType { functions[func_index].results()[0] };
- auto& wrapper = append_extra_instruction(Instruction(
- Instructions::block,
- Instruction::StructuredInstructionArgs {
- block_type,
- InstructionPointer { 0 },
- {},
- { static_cast<u32>(functions[func_index].results().size()), 0, false },
- }));
- expanded.append(&wrapper);
-
- Vector<size_t> g_ip_to_expanded;
- g_ip_to_expanded.resize(callee->body().instructions().size() + 1);
- Vector<size_t> g_structured_positions;
- int depth = 0;
- size_t g_idx = 0;
- for (auto& gi : callee->body().instructions()) {
- g_ip_to_expanded[g_idx++] = expanded.size();
- auto opc = gi.opcode();
- if (opc == Instructions::synthetic_end_expression)
- continue;
- if (opc == Instructions::return_) {
- expanded.append(&append_extra_instruction(Instruction(Instructions::br, Instruction::BranchArgs { LabelIndex { static_cast<u32>(depth) }, false })));
- } else if (first_is_one_of(opc, Instructions::block, Instructions::loop, Instructions::if_)) {
- ++depth;
- g_structured_positions.append(expanded.size());
- expanded.append(&gi);
- } else if (opc == Instructions::structured_end) {
- --depth;
- expanded.append(&gi);
- } else if (is_local_op(opc)) {
- expanded.append(&append_extra_instruction(Instruction(opc, LocalIndex { static_cast<u32>(gi.local_index().value() + base) })));
- } else {
- expanded.append(&gi);
- }
- }
- g_ip_to_expanded[g_idx] = expanded.size();
- auto& wrapper_end = append_extra_instruction(Instruction(Instructions::structured_end));
- auto wrapper_end_pos = expanded.size();
- expanded.append(&wrapper_end);
- wrapper.arguments() = Instruction::StructuredInstructionArgs {
- block_type,
- InstructionPointer { static_cast<u32>(wrapper_end_pos) },
- {},
- { static_cast<u32>(functions[func_index].results().size()), 0, false },
- };
-
- auto g_remap = [&](InstructionPointer ip) -> InstructionPointer {
- auto v = ip.value();
- return InstructionPointer { static_cast<u32>(v < g_ip_to_expanded.size() ? g_ip_to_expanded[v] : wrapper_end_pos) };
- };
- for (auto pos : g_structured_positions) {
- auto* sa = expanded[pos]->arguments().get_pointer<Instruction::StructuredInstructionArgs>();
- auto copy = *expanded[pos];
- auto new_else = sa->else_ip().map([&](InstructionPointer ip) { return g_remap(ip); });
- copy.arguments() = Instruction::StructuredInstructionArgs { sa->block_type, g_remap(sa->end_ip), new_else, sa->meta };
- expanded[pos] = &append_extra_instruction(move(copy));
- }
- }
- inlined_local_count = max(inlined_local_count, g_total);
- did_inline = true;
- continue;
- }
- }
- append_caller(instruction);
- }
- result.cranelift_inlined_locals = static_cast<u32>(inlined_local_count);
-
- // Regenerate all relative/IP-based structured instruction arguments to point into the new `expanded` vector.
- if (did_inline) {
- auto remap = [&](InstructionPointer ip) -> InstructionPointer {
- auto v = ip.value();
- return InstructionPointer { static_cast<u32>(v < wasm_ip_to_expanded.size() ? wasm_ip_to_expanded[v] : expanded.size()) };
- };
- for (auto i : caller_structured_positions) {
- auto const* insn = expanded[i];
- if (auto const* sa = insn->arguments().get_pointer<Instruction::StructuredInstructionArgs>()) {
- auto copy = *insn;
- auto new_else = sa->else_ip().map([&](InstructionPointer ip) { return remap(ip); });
- copy.arguments() = Instruction::StructuredInstructionArgs { sa->block_type, remap(sa->end_ip), new_else, sa->meta };
- expanded[i] = &append_extra_instruction(move(copy));
- } else if (auto const* tta = insn->arguments().get_pointer<Instruction::TryTableArgs>()) {
- auto copy = *insn;
- copy.arguments() = Instruction::TryTableArgs { tta->block_type, remap(tta->end_ip), tta->catches(), tta->meta };
- expanded[i] = &append_extra_instruction(move(copy));
- }
- }
- }
-
- {
- size_t depth = 0;
- size_t max_depth = 0;
- for (auto const* instruction_ptr : expanded) {
- auto op = instruction_ptr->opcode();
- if (first_is_one_of(op, Instructions::block, Instructions::loop, Instructions::if_, Instructions::try_table))
- max_depth = max(max_depth, ++depth);
- else if (op == Instructions::structured_end && depth > 0)
- --depth;
- }
- result.max_label_depth = static_cast<u32>(max_depth + 1);
- }
-
- for (auto const* instruction_ptr : expanded) {
- auto& instruction = *instruction_ptr;
- if (instruction.opcode() == Instructions::call) {
- auto const call_func_index = instruction.arguments().get<FunctionIndex>().value();
- auto& function = functions[call_func_index];
- // Host calls all gather their arguments into a buffer, so reg-calling them is a net perf loss for all of them; force whatever we can to the call record path.
- // Any remaining ones can still go through the regular call path, which is regardless faster than regcalling them.
- bool const is_extern = call_func_index < imported_function_count;
- if (!is_extern && function.results().size() <= 1 && function.parameters().size() < 4) {
- pattern_state = InsnPatternState::Nothing;
- OpCode op { static_cast<OpCode::Type>(Instructions::synthetic_call_00.value() + function.parameters().size() * 2 + function.results().size()) };
- auto& extra_instruction = append_extra_instruction(op, instruction.arguments());
- set_default_dispatch(extra_instruction);
- continue;
- }
-
- calls_in_expression++;
- }
-
- switch (pattern_state) {
- case InsnPatternState::Nothing:
- if (instruction.opcode() == Instructions::local_get) {
- local_index_0 = instruction.local_index();
- pattern_state = InsnPatternState::GetLocal;
- } else if (instruction.opcode() == Instructions::i32_const) {
- i32_const_value = instruction.arguments().get<i32>();
- pattern_state = InsnPatternState::I32Const;
- } else if (instruction.opcode() == Instructions::i64_const) {
- i64_const_value = instruction.arguments().get<i64>();
- pattern_state = InsnPatternState::I64Const;
- }
- break;
- case InsnPatternState::GetLocal:
- if (instruction.opcode() == Instructions::local_get) {
- local_index_1 = instruction.local_index();
- pattern_state = InsnPatternState::GetLocalx2;
- } else if (instruction.opcode() == Instructions::i32_const) {
- i32_const_value = instruction.arguments().get<i32>();
- pattern_state = InsnPatternState::GetLocalI32Const;
- } else if (instruction.opcode() == Instructions::i64_const) {
- i64_const_value = instruction.arguments().get<i64>();
- pattern_state = InsnPatternState::GetLocalI64Const;
- } else if (instruction.opcode() == Instructions::i32_store) {
- // `local.get a; i32.store m` -> `i32.storelocal a m`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i32_storelocal,
- local_index_0,
- instruction.arguments());
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else if (instruction.opcode() == Instructions::i64_store) {
- // `local.get a; i64.store m` -> `i64.storelocal a m`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i64_storelocal,
- local_index_0,
- instruction.arguments());
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else if (instruction.opcode() == Instructions::local_set) {
- // `local.get a; local.set b` -> `local_copy a b`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_local_copy,
- local_index_0,
- instruction.local_index());
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else {
- pattern_state = InsnPatternState::Nothing;
- }
- break;
- case InsnPatternState::GetLocalx2: {
- auto make_2local_synthetic = [&](OpCode synthetic_op) {
- set_default_dispatch(nop, result.dispatches.size() - 1);
- set_default_dispatch(nop, result.dispatches.size() - 2);
- auto& extra_instruction = append_extra_instruction(
- synthetic_op,
- local_index_0,
- local_index_1);
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- };
- if (instruction.opcode() == Instructions::i32_add) {
- // `local.get a; local.get b; i32.add` -> `i32.add_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_add2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_sub) {
- // `local.get a; local.get b; i32.sub` -> `i32.sub_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_sub2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_mul) {
- // `local.get a; local.get b; i32.mul` -> `i32.mul_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_mul2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_and) {
- // `local.get a; local.get b; i32.and` -> `i32.and_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_and2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_or) {
- // `local.get a; local.get b; i32.or` -> `i32.or_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_or2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_xor) {
- // `local.get a; local.get b; i32.xor` -> `i32.xor_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_xor2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_shl) {
- // `local.get a; local.get b; i32.shl` -> `i32.shl_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_shl2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_shru) {
- // `local.get a; local.get b; i32.shr_u` -> `i32.shru_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_shru2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_shrs) {
- // `local.get a; local.get b; i32.shr_s` -> `i32.shrs_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i32_shrs2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_add) {
- // `local.get a; local.get b; i64.add` -> `i64.add_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_add2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_sub) {
- // `local.get a; local.get b; i64.sub` -> `i64.sub_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_sub2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_mul) {
- // `local.get a; local.get b; i64.mul` -> `i64.mul_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_mul2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_and) {
- // `local.get a; local.get b; i64.and` -> `i64.and_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_and2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_or) {
- // `local.get a; local.get b; i64.or` -> `i64.or_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_or2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_xor) {
- // `local.get a; local.get b; i64.xor` -> `i64.xor_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_xor2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_shl) {
- // `local.get a; local.get b; i64.shl` -> `i64.shl_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_shl2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_shru) {
- // `local.get a; local.get b; i64.shr_u` -> `i64.shru_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_shru2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i64_shrs) {
- // `local.get a; local.get b; i64.shr_s` -> `i64.shrs_2local a b`.
- make_2local_synthetic(Instructions::synthetic_i64_shrs2local);
- continue;
- }
- if (instruction.opcode() == Instructions::i32_store) {
- // `local.get a; i32.store m` -> `i32.storelocal a m`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i32_storelocal,
- local_index_1,
- instruction.arguments());
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- }
- if (instruction.opcode() == Instructions::i64_store) {
- // `local.get a; i64.store m` -> `i64.storelocal a m`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i64_storelocal,
- local_index_1,
- instruction.arguments());
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- }
- if (instruction.opcode() == Instructions::i32_const) {
- swap(local_index_0, local_index_1);
- i32_const_value = instruction.arguments().get<i32>();
- pattern_state = InsnPatternState::GetLocalI32Const;
- } else if (instruction.opcode() == Instructions::i64_const) {
- swap(local_index_0, local_index_1);
- i64_const_value = instruction.arguments().get<i64>();
- pattern_state = InsnPatternState::GetLocalI64Const;
- } else {
- pattern_state = InsnPatternState::Nothing;
- }
- } break;
- case InsnPatternState::I32Const:
- if (instruction.opcode() == Instructions::local_get) {
- local_index_0 = instruction.local_index();
- pattern_state = InsnPatternState::I32ConstGetLocal;
- } else if (instruction.opcode() == Instructions::i32_const) {
- i32_const_value = instruction.arguments().get<i32>();
- } else if (instruction.opcode() == Instructions::local_set) {
- // `i32.const a; local.set b` -> `local.seti32_const b a`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_local_seti32_const,
- instruction.local_index(),
- i32_const_value);
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else {
- pattern_state = InsnPatternState::Nothing;
- }
- break;
- case InsnPatternState::GetLocalI32Const:
- if (instruction.opcode() == Instructions::local_set) {
- // `i32.const a; local.set b` -> `local.seti32_const b a`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_local_seti32_const,
- instruction.local_index(),
- i32_const_value);
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- }
- if (instruction.opcode() == Instructions::i32_const) {
- i32_const_value = instruction.arguments().get<i32>();
- pattern_state = InsnPatternState::I32Const;
- break;
- }
- if (instruction.opcode() == Instructions::local_get) {
- local_index_0 = instruction.local_index();
- pattern_state = InsnPatternState::I32ConstGetLocal;
- break;
- }
- [[fallthrough]];
- case InsnPatternState::I32ConstGetLocal:
- if (instruction.opcode() == Instructions::i32_const) {
- i32_const_value = instruction.arguments().get<i32>();
- pattern_state = InsnPatternState::GetLocalI32Const;
- } else if (instruction.opcode() == Instructions::local_get) {
- local_index_1 = instruction.local_index();
- pattern_state = InsnPatternState::GetLocalx2;
- } else if (instruction.opcode() == Instructions::i32_add) {
- // `i32.const a; local.get b; i32.add` -> `i32.add_constlocal b a`.
- // Replace the previous two ops with noops, and add i32.add_constlocal.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- set_default_dispatch(nop, result.dispatches.size() - 2);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i32_addconstlocal,
- local_index_0,
- i32_const_value);
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else if (instruction.opcode() == Instructions::i32_and) {
- // `i32.const a; local.get b; i32.and` -> `i32.and_constlocal b a`.
- // Replace the previous two ops with noops, and add i32.and_constlocal.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- set_default_dispatch(nop, result.dispatches.size() - 2);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i32_andconstlocal,
- local_index_0,
- i32_const_value);
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else {
- pattern_state = InsnPatternState::Nothing;
- }
- break;
- case InsnPatternState::I64Const:
- if (instruction.opcode() == Instructions::local_get) {
- local_index_0 = instruction.local_index();
- pattern_state = InsnPatternState::I64ConstGetLocal;
- } else if (instruction.opcode() == Instructions::i64_const) {
- i64_const_value = instruction.arguments().get<i64>();
- } else if (instruction.opcode() == Instructions::local_set) {
- // `i64.const a; local.set b` -> `local.seti64_const b a`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_local_seti64_const,
- instruction.local_index(),
- i64_const_value);
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else {
- pattern_state = InsnPatternState::Nothing;
- }
- break;
- case InsnPatternState::GetLocalI64Const:
- if (instruction.opcode() == Instructions::local_set) {
- // `i64.const a; local.set b` -> `local.seti64_const b a`.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_local_seti64_const,
- instruction.local_index(),
- i64_const_value);
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- }
- if (instruction.opcode() == Instructions::i64_const) {
- i64_const_value = instruction.arguments().get<i64>();
- pattern_state = InsnPatternState::I64Const;
- break;
- }
- if (instruction.opcode() == Instructions::local_get) {
- local_index_0 = instruction.local_index();
- pattern_state = InsnPatternState::I64ConstGetLocal;
- break;
- }
- [[fallthrough]];
- case InsnPatternState::I64ConstGetLocal:
- if (instruction.opcode() == Instructions::i64_const) {
- i64_const_value = instruction.arguments().get<i64>();
- pattern_state = InsnPatternState::GetLocalI64Const;
- } else if (instruction.opcode() == Instructions::local_get) {
- local_index_1 = instruction.local_index();
- pattern_state = InsnPatternState::GetLocalx2;
- } else if (instruction.opcode() == Instructions::i64_add) {
- // `i64.const a; local.get b; i64.add` -> `i64.add_constlocal b a`.
- // Replace the previous two ops with noops, and add i64.add_constlocal.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- set_default_dispatch(nop, result.dispatches.size() - 2);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i64_addconstlocal,
- local_index_0,
- i64_const_value);
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else if (instruction.opcode() == Instructions::i64_and) {
- // `i64.const a; local.get b; i64.and` -> `i64.and_constlocal b a`.
- // Replace the previous two ops with noops, and add i64.and_constlocal.
- set_default_dispatch(nop, result.dispatches.size() - 1);
- set_default_dispatch(nop, result.dispatches.size() - 2);
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_i64_andconstlocal,
- local_index_0,
- i64_const_value);
-
- set_default_dispatch(extra_instruction);
- pattern_state = InsnPatternState::Nothing;
- continue;
- } else {
- pattern_state = InsnPatternState::Nothing;
- }
- break;
- }
- set_default_dispatch(instruction);
- }
-
- // Remove all nops (that were either added by the above patterns or were already present in the original instructions),
- // and adjust jumps accordingly.
- RedBlackTree<size_t, Empty> nops_to_remove;
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- if (result.dispatches[i].instruction->opcode() == Instructions::nop)
- nops_to_remove.insert(i, {});
- }
-
- auto nops_to_remove_it = nops_to_remove.begin();
- size_t offset_accumulated = 0;
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- if (result.dispatches[i].instruction->opcode() == Instructions::nop) {
- offset_accumulated++;
- ++nops_to_remove_it;
- continue;
- }
-
- auto& args = result.dispatches[i].instruction->arguments();
- auto offset_to = [&](InstructionPointer ip) {
- size_t offset = 0;
- auto it = nops_to_remove_it;
- while (it != nops_to_remove.end() && it.key() < ip.value()) {
- ++offset;
- ++it;
- }
- return offset;
- };
- if (auto ptr = args.get_pointer<Instruction::StructuredInstructionArgs>()) {
- InstructionPointer end_ip = ptr->end_ip.value() - offset_accumulated - offset_to(ptr->end_ip - ptr->else_ip().has_value());
- auto else_ip = ptr->else_ip().map([&](InstructionPointer const& ip) -> InstructionPointer { return ip.value() - offset_accumulated - offset_to(ip - 1); });
- auto instruction = *result.dispatches[i].instruction;
- instruction.arguments() = Instruction::StructuredInstructionArgs { ptr->block_type, end_ip, else_ip, ptr->meta };
- auto& extra_instruction = append_extra_instruction(move(instruction));
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- } else if (auto try_table_ptr = args.get_pointer<Instruction::TryTableArgs>()) {
- InstructionPointer end_ip = try_table_ptr->end_ip.value() - offset_accumulated - offset_to(try_table_ptr->end_ip);
- auto instruction = *result.dispatches[i].instruction;
- instruction.arguments() = Instruction::TryTableArgs { try_table_ptr->block_type, end_ip, try_table_ptr->catches(), try_table_ptr->meta };
- auto& extra_instruction = append_extra_instruction(move(instruction));
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- }
- }
-
- result.dispatches.remove_all(nops_to_remove, [](auto const& it) { return it.key(); });
- result.src_dst_mappings.remove_all(nops_to_remove, [](auto const& it) { return it.key(); });
-
- // Every time we have a large-enough function, drop a synthetic_tier_up checkpoint right after each loop header that's eligible for tier-up (empty stack at the header, so the back-edge hits it every iteration).
- // This allows us to start running code immediately in the interpreter, and switch to native code on paths that matter (or eventually) once compiled code is ready and the tier-up check hits.
- constexpr size_t tier_up_instruction_threshold = 32;
- if (result.dispatches.size() >= tier_up_instruction_threshold) {
- Vector<size_t> loop_positions;
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- if (result.dispatches[i].instruction->opcode() != Instructions::loop)
- continue;
- auto& sa = result.dispatches[i].instruction->arguments().get<Instruction::StructuredInstructionArgs>();
- if (sa.meta.tier_up_eligible)
- loop_positions.append(i);
- }
-
- if (!loop_positions.is_empty()) {
- // Number of tier-up ops inserted strictly before a given old dispatch index. A tier-up
- // sits between its loop (at L) and L+1, so it precedes any old index > L.
- auto shift_before = [&](size_t old_index) {
- size_t shift = 0;
- for (auto position : loop_positions) {
- if (position < old_index)
- ++shift;
- else
- break;
- }
- return shift;
- };
-
- Vector<Dispatch> new_dispatches;
- Vector<SourcesAndDestination> new_src_dst;
- new_dispatches.ensure_capacity(result.dispatches.size() + loop_positions.size());
- new_src_dst.ensure_capacity(result.src_dst_mappings.size() + loop_positions.size());
-
- size_t next_loop = 0;
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- new_dispatches.append(result.dispatches[i]);
- new_src_dst.append(result.src_dst_mappings[i]);
- if (next_loop < loop_positions.size() && loop_positions[next_loop] == i) {
- auto& tier_up = append_extra_instruction(Instructions::synthetic_tier_up);
- new_dispatches.append({ { .instruction_opcode = tier_up.opcode() }, &tier_up });
- new_src_dst.append({ .sources = { Dispatch::Stack, Dispatch::Stack, Dispatch::Stack }, .destination = Dispatch::Stack });
- ++next_loop;
- }
- }
-
- // Re-point absolute IPs in structured args (end_ip / else_ip) past the inserted ops.
- for (size_t i = 0; i < new_dispatches.size(); ++i) {
- if (auto* sa = new_dispatches[i].instruction->arguments().get_pointer<Instruction::StructuredInstructionArgs>()) {
- InstructionPointer new_end_ip = sa->end_ip.value() + shift_before(sa->end_ip.value());
- auto new_else_ip = sa->else_ip().map([&](InstructionPointer ip) -> InstructionPointer { return ip.value() + shift_before(ip.value()); });
- auto rebuilt = *new_dispatches[i].instruction;
- rebuilt.arguments() = Instruction::StructuredInstructionArgs { sa->block_type, new_end_ip, new_else_ip, sa->meta };
- auto& extra_instruction = append_extra_instruction(move(rebuilt));
- new_dispatches[i].instruction = &extra_instruction;
- new_dispatches[i].instruction_opcode = extra_instruction.opcode();
- } else if (auto* tta = new_dispatches[i].instruction->arguments().get_pointer<Instruction::TryTableArgs>()) {
- InstructionPointer new_end_ip = tta->end_ip.value() + shift_before(tta->end_ip.value());
- auto rebuilt = *new_dispatches[i].instruction;
- rebuilt.arguments() = Instruction::TryTableArgs { tta->block_type, new_end_ip, tta->catches(), tta->meta };
- auto& extra_instruction = append_extra_instruction(move(rebuilt));
- new_dispatches[i].instruction = &extra_instruction;
- new_dispatches[i].instruction_opcode = extra_instruction.opcode();
- }
- }
-
- result.dispatches = move(new_dispatches);
- result.src_dst_mappings = move(new_src_dst);
- result.has_tier_up_checkpoints = true;
- }
- }
-
- // Rewrite local.* of arguments to argument.* to keep local.* for locals only.
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- if (dispatch.instruction->opcode() == Instructions::local_get) {
- auto local_index = dispatch.instruction->local_index();
- if (local_index.value() & LocalArgumentMarker) {
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_argument_get,
- local_index);
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- }
- } else if (dispatch.instruction->opcode() == Instructions::local_set) {
- auto local_index = dispatch.instruction->local_index();
- if (local_index.value() & LocalArgumentMarker) {
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_argument_set,
- local_index);
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- }
- } else if (dispatch.instruction->opcode() == Instructions::local_tee) {
- auto local_index = dispatch.instruction->local_index();
- if (local_index.value() & LocalArgumentMarker) {
- auto& extra_instruction = append_extra_instruction(
- Instructions::synthetic_argument_tee,
- local_index);
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- }
- }
- }
-
- // Allocate registers for instructions, meeting the following constraints:
- // - Any instruction that produces polymorphic stack, or requires its inputs on the stack must sink all active values to the stack.
- // - All instructions must have the same location for their last input and their destination value (if any).
- // - Any value left at the end of the expression must be on the stack.
-
- using ValueID = DistinctNumeric<size_t, struct ValueIDTag, AK::DistinctNumericFeature::Comparison, AK::DistinctNumericFeature::Arithmetic, AK::DistinctNumericFeature::Increment>;
- using IP = DistinctNumeric<size_t, struct IPTag, AK::DistinctNumericFeature::Comparison>;
-
- struct Value {
- ValueID id;
- IP definition_index;
- IP last_use = 0;
- bool was_created_as_a_result_of_polymorphic_stack = false;
- };
-
- struct ActiveReg {
- ValueID value_id;
- IP end;
- Dispatch::RegisterOrStack reg;
- };
-
- HashMap<ValueID, Value> values;
- Vector<ValueID> value_stack;
- ValueID next_value_id = 0;
- HashMap<IP, ValueID> instr_to_output_value;
- HashMap<IP, Vector<ValueID>> instr_to_input_values;
-
- instr_to_output_value.ensure_capacity(result.dispatches.size());
- instr_to_input_values.ensure_capacity(result.dispatches.size());
-
- Vector<ValueID> forced_stack_values;
-
- Vector<ValueID> parent; // parent[id] -> parent ValueID of id in the alias tree
- Vector<ValueID> rank; // rank[id] -> rank of the tree rooted at id
- Vector<ValueID> final_roots; // final_roots[id] -> the final root parent of id
-
- // OPTIMIZATION: Append alias entries so the tables grow geometrically as values are introduced.
- auto ensure_id_space = [&](ValueID id) {
- while (parent.size() <= id.value()) {
- parent.append(parent.size());
- rank.append(0);
- }
- };
-
- auto find_root = [&parent](this auto& self, ValueID x) -> ValueID {
- if (parent[x.value()] != x)
- parent[x.value()] = self(parent[x.value()]);
- return parent[x.value()];
- };
-
- auto union_alias = [&](ValueID a, ValueID b) {
- ensure_id_space(max(a, b));
-
- auto const root_a = find_root(a);
- auto const root_b = find_root(b);
-
- if (root_a == root_b)
- return;
-
- if (rank[root_a.value()] < rank[root_b.value()]) {
- parent[root_a.value()] = root_b;
- } else if (rank[root_a.value()] > rank[root_b.value()]) {
- parent[root_b.value()] = root_a;
- } else {
- parent[root_b.value()] = root_a;
- ++rank[root_a.value()];
- }
- };
-
- HashTable<ValueID> stack_forced_roots;
-
- // Track call record constraints
- HashMap<ValueID, u8> value_to_callrec_slot;
-
- struct CallInfo {
- size_t call_index;
- size_t param_count;
- size_t result_count;
- size_t earliest_arg_index;
- Vector<ValueID> arg_values;
- };
- Vector<CallInfo> eligible_calls;
-
- eligible_calls.ensure_capacity(calls_in_expression);
-
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- auto opcode = dispatch.instruction->opcode();
- size_t inputs = 0;
- size_t outputs = 0;
-
- bool variadic_or_unknown = false;
- bool requires_aliased_destination = true;
-
- switch (opcode.value()) {
-#define M(name, _, ins, outs) \
- case Instructions::name.value(): \
- if constexpr (ins == -1 || outs == -1) { \
- variadic_or_unknown = true; \
- } \
- inputs = max(ins, 0); \
- outputs = max(outs, 0); \
- break;
- ENUMERATE_WASM_OPCODES(M)
-#undef M
- }
-
- Vector<ValueID> input_ids;
-
- if (opcode == Instructions::call) {
- auto& type = functions[dispatch.instruction->arguments().get<FunctionIndex>().value()];
-
- if (type.parameters().size() <= (Dispatch::LastCallRecord - Dispatch::CallRecord + 1)
- && type.results().size() <= 1
- && type.parameters().size() <= value_stack.size()) {
-
- inputs = type.parameters().size();
- outputs = type.results().size();
- variadic_or_unknown = false;
- requires_aliased_destination = false;
-
- auto value_stack_copy = value_stack;
-
- for (size_t j = 0; j < inputs; ++j) {
- auto input_value = value_stack.take_last();
- auto& value = values.get(input_value).value();
-
- // if this value was created as a result of a polymorphic stack,
- // we can't actually go and force it to a call record again, so disqualify this call.
- if (value.was_created_as_a_result_of_polymorphic_stack) {
- inputs = 0;
- outputs = 0;
- variadic_or_unknown = true;
- value_stack = move(value_stack_copy);
- goto avoid_optimizing_this_call;
- }
-
- input_ids.append(input_value);
- value.last_use = max(value.last_use, i);
- forced_stack_values.append(input_value);
- }
- instr_to_input_values.set(i, input_ids);
-
- for (size_t j = 0; j < outputs; ++j) {
- auto id = next_value_id++;
- values.set(id, Value { id, i, i });
- value_stack.append(id);
- instr_to_output_value.set(i, id);
- ensure_id_space(id);
- }
-
- size_t earliest = i;
- ValueID earliest_arg_value = NumericLimits<size_t>::max();
- for (auto value_id : input_ids) {
- auto& value = values.get(value_id).value();
- if (earliest > value.definition_index.value()) {
- earliest = value.definition_index.value();
- earliest_arg_value = value_id;
- }
- }
-
- // Reverse the input_ids to match stack order
- Vector<ValueID> reversed_args;
- for (size_t j = 0; j < inputs; ++j) {
- reversed_args.append(input_ids[inputs - 1 - j]);
- }
-
- // Follow the alias root of the earliest arg value to find the first instruction that produced it.
- auto new_earliest = earliest;
- while (true) {
- auto maybe_inputs = instr_to_input_values.get(new_earliest);
- if (!maybe_inputs.has_value())
- break;
- bool found_earliest = false;
- for (auto val : maybe_inputs.value()) {
- auto root = find_root(val);
- if (root == find_root(earliest_arg_value)) {
- auto& value = values.get(val).value();
- if (value.definition_index.value() < new_earliest) {
- new_earliest = value.definition_index.value();
- found_earliest = true;
- break;
- }
- }
- }
- if (!found_earliest)
- break;
- }
-
- eligible_calls.append({ .call_index = i,
- .param_count = inputs,
- .result_count = outputs,
- .earliest_arg_index = new_earliest,
- .arg_values = reversed_args });
-
- continue;
- }
- }
- avoid_optimizing_this_call:;
-
- // Handle the inputs we actually know about.
- size_t j = 0;
- for (; j < inputs && !value_stack.is_empty(); ++j) {
- auto input_value = value_stack.take_last();
- input_ids.append(input_value);
- auto& value = values.get(input_value).value();
- value.last_use = max(value.last_use, i);
- }
-
- inputs -= j;
-
- if (variadic_or_unknown) {
- for (auto val : value_stack) {
- auto& value = values.get(val).value();
- value.last_use = max(value.last_use, i);
- forced_stack_values.append(val);
- }
- value_stack.clear_with_capacity();
- }
-
- if (value_stack.size() < inputs) {
- size_t j = 0;
- for (; j < inputs && !value_stack.is_empty(); ++j) {
- auto input_value = value_stack.take_last();
- input_ids.append(input_value);
- auto& value = values.get(input_value).value();
- value.last_use = max(value.last_use, i);
- }
-
- for (; j < inputs; ++j) {
- auto val_id = next_value_id++;
- values.set(val_id, Value { val_id, i, i, true });
- input_ids.append(val_id);
- forced_stack_values.append(val_id);
- ensure_id_space(val_id);
- }
-
- inputs = 0;
- }
-
- for (size_t j = 0; j < inputs; ++j) {
- auto input_value = value_stack.take_last();
- input_ids.append(input_value);
- auto& value = values.get(input_value).value();
- value.last_use = max(value.last_use, i);
- }
- instr_to_input_values.set(i, input_ids);
-
- ValueID output_id = NumericLimits<size_t>::max();
- for (size_t j = 0; j < outputs; ++j) {
- auto id = next_value_id++;
- values.set(id, Value { id, i, i });
- value_stack.append(id);
- instr_to_output_value.set(i, id);
- output_id = id;
- ensure_id_space(id);
- }
-
- // Alias the output with the last input, if one exists.
- if (outputs > 0 && requires_aliased_destination) {
- auto maybe_input_ids = instr_to_input_values.get(i);
- if (maybe_input_ids.has_value() && !maybe_input_ids->is_empty()) {
- auto last_input_id = maybe_input_ids->last();
- union_alias(output_id, last_input_id);
-
- auto alias_root = find_root(last_input_id);
-
- // If the last input was created as a result of polymorphic stack, propagate that to the output (as they're aliased).
- auto& output_value = values.get(output_id).value();
- auto const& input_value = values.get(last_input_id).value();
- if (input_value.was_created_as_a_result_of_polymorphic_stack)
- output_value.was_created_as_a_result_of_polymorphic_stack = true;
-
- // If any *other* input is forced to alias the output, we have no choice but to place all three on the stack.
- for (size_t j = 0; j < maybe_input_ids->size() - 1; ++j) {
- auto input_root = find_root((*maybe_input_ids)[j]);
- if (input_root == alias_root) {
- stack_forced_roots.set(alias_root);
- break;
- }
- }
- }
- }
- }
-
- forced_stack_values.extend(value_stack);
-
- // Build conflict graph and select maximum set of non-conflicting calls
- // Prefer calls with more arguments, and among those with equal args, prefer shorter spans
-
- struct CallScore {
- size_t index;
- size_t param_count;
- size_t span;
- };
-
- Vector<CallScore> scored_calls;
- for (size_t i = 0; i < eligible_calls.size(); ++i) {
- auto& call = eligible_calls[i];
- size_t span = call.call_index - call.earliest_arg_index;
- scored_calls.append({ i, call.param_count, span });
- }
-
- // Sort by: more params first, then shorter span
- quick_sort(scored_calls, [](auto const& a, auto const& b) {
- if (a.param_count != b.param_count)
- return a.param_count > b.param_count;
- return a.span < b.span;
- });
-
- // Greedily select non-conflicting calls in priority order
- Vector<CallInfo*> valid_calls;
- size_t max_call_record_size = 0;
-
- for (auto const& score : scored_calls) {
- auto& call_info = eligible_calls[score.index];
- size_t call_start = call_info.earliest_arg_index;
- size_t call_end = call_info.call_index;
-
- bool conflicts = false;
- for (auto* other_call : valid_calls) {
- size_t other_start = other_call->earliest_arg_index;
- size_t other_end = other_call->call_index;
-
- // Check if the ranges overlap
- // Two ranges [a,b] and [c,d] overlap if: NOT (b < c OR d < a)
- if (!(call_end < other_start || other_end < call_start)) {
- conflicts = true;
- break;
- }
- }
-
- if (!conflicts) {
- valid_calls.append(&call_info);
- max_call_record_size = max(max_call_record_size, call_info.param_count);
- }
- }
-
- // Only apply call record optimization to non-conflicting calls
- HashTable<size_t> calls_with_records;
- for (auto* call_info : valid_calls) {
- calls_with_records.set(call_info->call_index);
-
- // Mark values for call record slots
- for (size_t j = 0; j < call_info->param_count; ++j) {
- value_to_callrec_slot.set(call_info->arg_values[j], Dispatch::CallRecord + j);
- }
-
- auto new_call_opcode = call_info->result_count == 0
- ? Instructions::synthetic_call_with_record_0
- : Instructions::synthetic_call_with_record_1;
-
- auto new_call_insn = Instruction(
- new_call_opcode,
- result.dispatches[call_info->call_index].instruction->arguments());
-
- auto& extra_instruction = append_extra_instruction(move(new_call_insn));
- result.dispatches[call_info->call_index].instruction = &extra_instruction;
- result.dispatches[call_info->call_index].instruction_opcode = new_call_opcode;
- }
-
- result.max_call_rec_size = max_call_record_size;
-
- final_roots.resize(parent.size());
- for (size_t i = 0; i < final_roots.size(); ++i)
- final_roots[i] = find_root(i);
-
- HashMap<ValueID, u8> root_to_callrec_slot;
- for (auto const& [value_id, slot] : value_to_callrec_slot) {
- auto root = final_roots[value_id.value()];
- if (auto existing = root_to_callrec_slot.get(root); existing.has_value()) {
- VERIFY(*existing == slot);
- }
- root_to_callrec_slot.set(root, slot);
- }
-
- value_to_callrec_slot.clear_with_capacity();
- for (size_t i = 0; i < final_roots.size(); ++i) {
- auto root = final_roots[i];
- if (auto slot = root_to_callrec_slot.get(root); slot.has_value()) {
- value_to_callrec_slot.set(ValueID { i }, *slot);
- }
- }
-
- struct LiveInterval {
- ValueID value_id;
- IP start;
- IP end;
- bool forced_to_stack { false };
- };
-
- Vector<LiveInterval> intervals;
- intervals.ensure_capacity(values.size());
-
- for (auto const& [_, value] : values) {
- auto start = value.definition_index;
- auto end = max(start, value.last_use);
- intervals.append({ value.id, start, end });
- }
-
- for (auto id : forced_stack_values)
- stack_forced_roots.set(final_roots[id.value()]);
- for (auto& interval : intervals)
- interval.forced_to_stack = stack_forced_roots.contains(final_roots[interval.value_id.value()]);
-
- quick_sort(intervals, [](auto const& a, auto const& b) {
- return a.start < b.start;
- });
-
- HashMap<ValueID, Dispatch::RegisterOrStack> value_alloc;
- RedBlackTree<size_t, ActiveReg> active_by_end;
-
- auto expire_old_intervals = [&](IP current_start) {
- while (true) {
- auto it = active_by_end.find_smallest_not_below_iterator(current_start.value());
- if (it.is_end())
- break;
- active_by_end.remove(it.key());
- }
- };
-
- HashMap<ValueID, Vector<LiveInterval*>> alias_groups;
- for (auto& interval : intervals) {
- auto root = final_roots[interval.value_id.value()];
- alias_groups.ensure(root).append(&interval);
- }
-
- struct RegisterOccupancy {
- Bitmap occupied;
- Vector<ValueID> roots_at_position;
-
- bool can_place(IP start, IP end, ValueID root) const
- {
- for (size_t i = start.value(); i <= end.value(); ++i) {
- if (occupied.get(i)) {
- if (roots_at_position.size() > i && roots_at_position[i].value() != root.value())
- return false;
- }
- }
- return true;
- }
-
- void place(IP start, IP end, ValueID root)
- {
- if (roots_at_position.size() <= end.value())
- roots_at_position.resize_with_default_value(end.value() + 1, {});
-
- occupied.set_range<true>(start.value(), end.value() - start.value() + 1);
- for (size_t i = start.value(); i <= end.value(); ++i)
- roots_at_position[i] = root;
- }
- };
-
- Array<RegisterOccupancy, Dispatch::CountRegisters> reg_occupancy;
-
- for (u8 r = 0; r < Dispatch::CountRegisters; ++r) {
- auto bitmap_result = Bitmap::create(result.dispatches.size(), false);
- if (bitmap_result.is_error()) {
- dbgln("Failed to allocate register bitmap of size {} ({}), bailing on register allocation", result.dispatches.size(), bitmap_result.error());
- return {};
- }
- reg_occupancy[r].occupied = bitmap_result.release_value();
- }
-
- for (auto& [key, group] : alias_groups) {
- // Check if any value in this group needs a call record slot
- Dispatch::RegisterOrStack forced_slot = Dispatch::RegisterOrStack::Stack;
- bool has_callrec_constraint = false;
-
- for (auto* interval : group) {
- if (auto slot = value_to_callrec_slot.get(interval->value_id); slot.has_value()) {
- forced_slot = static_cast<Dispatch::RegisterOrStack>(*slot);
- has_callrec_constraint = true;
- break;
- }
- }
-
- if (has_callrec_constraint) {
- // Force all values in this alias group to use the call record slot
- for (auto* interval : group) {
- value_alloc.set(interval->value_id, forced_slot);
- }
- continue;
- }
-
- auto has_fixed_allocation = false;
- for (auto* interval : group) {
- if (value_alloc.contains(interval->value_id)) {
- has_fixed_allocation = true;
- break;
- }
- }
- if (has_fixed_allocation)
- continue;
-
- IP group_start = NumericLimits<size_t>::max();
- IP group_end = 0;
- auto group_forced_to_stack = false;
-
- for (auto* interval : group) {
- group_start = min(group_start, interval->start);
- group_end = max(group_end, interval->end);
- if (interval->forced_to_stack)
- group_forced_to_stack = true;
- }
-
- expire_old_intervals(group_start);
-
- Dispatch::RegisterOrStack reg = Dispatch::RegisterOrStack::Stack;
- if (!group_forced_to_stack) {
- Array<bool, Dispatch::CountRegisters> used_regs;
- used_regs.fill(false);
-
- for (auto const& active_entry : active_by_end) {
- if (active_entry.reg != Dispatch::RegisterOrStack::Stack)
- used_regs[to_underlying(active_entry.reg)] = true;
- }
-
- auto group_root = final_roots[key.value()];
-
- for (u8 r = 0; r < Dispatch::CountRegisters; ++r) {
- if (used_regs[r])
- continue;
-
- if (reg_occupancy[r].can_place(group_start, group_end, group_root)) {
- reg = static_cast<Dispatch::RegisterOrStack>(r);
- active_by_end.insert(group_end.value(), { key, group_end, reg });
- reg_occupancy[r].place(group_start, group_end, group_root);
- break;
- }
- }
- }
-
- for (auto* interval : group)
- value_alloc.set(interval->value_id, reg);
- }
-
- size_t max_call_arg_count = 0;
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- if (dispatch.instruction->opcode() == Instructions::call
- || dispatch.instruction->opcode() == Instructions::synthetic_call_00
- || dispatch.instruction->opcode() == Instructions::synthetic_call_10
- || dispatch.instruction->opcode() == Instructions::synthetic_call_11
- || dispatch.instruction->opcode() == Instructions::synthetic_call_20
- || dispatch.instruction->opcode() == Instructions::synthetic_call_21
- || dispatch.instruction->opcode() == Instructions::synthetic_call_30
- || dispatch.instruction->opcode() == Instructions::synthetic_call_31) {
-
- auto target = dispatch.instruction->arguments().get<FunctionIndex>();
- if (target.value() < functions.size()) {
- auto& function = functions[target.value()];
- max_call_arg_count = max(max_call_arg_count, function.parameters().size());
- }
- }
-
- auto& addr = result.src_dst_mappings[i];
- auto input_ids = instr_to_input_values.get(IP(i)).value_or({});
- if (input_ids.size() <= array_size(addr.sources)) {
- for (size_t j = 0; j < input_ids.size(); ++j) {
- auto reg = value_alloc.get(input_ids[j]).value_or(Dispatch::RegisterOrStack::Stack);
- addr.sources[j] = reg;
- }
- }
-
- if (auto output_id = instr_to_output_value.get(IP(i)); output_id.has_value())
- addr.destination = value_alloc.get(*output_id).value_or(Dispatch::RegisterOrStack::Stack);
- }
-
- result.max_call_arg_count = max_call_arg_count;
-
- // Swap out local.get (0..7) with local.get_[0..7] to avoid one extra load when possible
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- if (dispatch.instruction->opcode() == Instructions::local_get) {
- auto local_index = dispatch.instruction->local_index().value();
- if (local_index <= 7) {
- auto& extra_instruction = append_extra_instruction(
- static_cast<OpCode>(Instructions::synthetic_local_get_0.value() + local_index),
- dispatch.instruction->local_index());
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- }
- }
- }
-
- // Swap out local.set (0..7) with local.set_[0..7] to avoid one extra load when possible
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- if (dispatch.instruction->opcode() == Instructions::local_set) {
- auto local_index = dispatch.instruction->local_index().value();
- if (local_index <= 7) {
- auto& extra_instruction = append_extra_instruction(
- static_cast<OpCode>(Instructions::synthetic_local_set_0.value() + local_index),
- dispatch.instruction->local_index());
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- }
- }
- }
-
- // Swap out br(.if) with the runtime-checked nostack variant if no adjustment is needed.
- // We still have to check whether that's true in reality as we may have had a polymorphic stack coming in,
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- if ((dispatch.instruction->opcode() == Instructions::br || dispatch.instruction->opcode() == Instructions::br_if)
- && !dispatch.instruction->arguments().get<Instruction::BranchArgs>().has_stack_adjustment) {
- auto new_opcode = dispatch.instruction->opcode() == Instructions::br
- ? Instructions::synthetic_br_nostack
- : Instructions::synthetic_br_if_nostack;
- auto& extra_instruction = append_extra_instruction(
- new_opcode,
- dispatch.instruction->arguments());
- result.dispatches[i].instruction = &extra_instruction;
- result.dispatches[i].instruction_opcode = result.dispatches[i].instruction->opcode();
- }
- }
-
- if constexpr (should_try_to_use_direct_threading) {
- constexpr auto all_sources_are_registers = [](SourcesAndDestination const& addrs, ssize_t expected_source_count, ssize_t expected_dest_count) -> bool {
- if (expected_source_count < 0 || expected_dest_count > 1)
- return false;
- for (ssize_t i = 0; i < expected_source_count; ++i) {
- if (addrs.sources[i] >= Dispatch::Stack)
- return false;
- }
-
- if (expected_dest_count == 1 && addrs.destination >= Dispatch::Stack)
- return false;
-
- return true;
- };
- constexpr auto all_sources_are_callrec = [](SourcesAndDestination const& addrs, ssize_t expected_source_count, ssize_t expected_dest_count) -> bool {
- if (expected_source_count < 0 || expected_dest_count > 1)
- return false;
- for (ssize_t i = 0; i < expected_source_count; ++i) {
- if (addrs.sources[i] < Dispatch::CallRecord)
- return false;
- }
- if (expected_dest_count == 1 && addrs.destination < Dispatch::CallRecord)
- return false;
- return true;
- };
- constexpr auto all_sources_are_stack = [](SourcesAndDestination const& addrs, ssize_t expected_source_count, ssize_t expected_dest_count) -> bool {
- if (expected_source_count < 0 || expected_dest_count > 1)
- return false;
- for (ssize_t i = 0; i < expected_source_count; ++i) {
- if (addrs.sources[i] != Dispatch::Stack)
- return false;
- }
-
- if (expected_dest_count == 1 && addrs.destination != Dispatch::Stack)
- return false;
-
- return true;
- };
-
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- auto& addrs = result.src_dst_mappings[i];
-
-#define CASE(name, _, inputs, outputs) \
- case Instructions::name.value(): \
- if (all_sources_are_registers(addrs, inputs, outputs)) \
- dispatch.handler_ptr = bit_cast<FlatPtr>(&InstructionHandler<Instructions::name.value()>::template operator()<false, Continue, SourceAddressMix::AllRegisters>); \
- else if (all_sources_are_callrec(addrs, inputs, outputs)) \
- dispatch.handler_ptr = bit_cast<FlatPtr>(&InstructionHandler<Instructions::name.value()>::template operator()<false, Continue, SourceAddressMix::AllCallRecords>); \
- else if (all_sources_are_stack(addrs, inputs, outputs)) \
- dispatch.handler_ptr = bit_cast<FlatPtr>(&InstructionHandler<Instructions::name.value()>::template operator()<false, Continue, SourceAddressMix::AllStack>); \
- else \
- dispatch.handler_ptr = bit_cast<FlatPtr>(&InstructionHandler<Instructions::name.value()>::template operator()<false, Continue, SourceAddressMix::Any>); \
- break;
-
- switch (dispatch.instruction->opcode().value()) {
- ENUMERATE_WASM_OPCODES(CASE)
- default:
- dbgln("No handler for opcode {}", dispatch.instruction->opcode().value());
- VERIFY_NOT_REACHED();
- }
- }
- result.direct = true;
- }
-
- // Verify instruction stream.
- struct Mark {
- size_t ip;
- StringView label;
- };
-
- auto print_instructions_around = [&](size_t start_ish, size_t end_ish, auto... marks) {
- auto sterr = MUST(Core::File::standard_error());
- Printer p(*sterr);
- auto print_range = [&](size_t start_ip, size_t end_ip) {
- for (size_t k = start_ip; k < end_ip; ++k) {
- warn("[{:04}] ", k);
- auto instruction = result.dispatches[k].instruction;
- auto addresses = result.src_dst_mappings[k];
-
- p.print(*instruction);
-
- ([&] { if (k == marks.ip) warnln(" ^-- {}", marks.label); }(), ...);
-
- auto [in_count, out_count] = instruction_operand_counts(instruction->opcode());
- for (ssize_t i = 0; i < in_count; ++i) {
- warnln(" arg{} [{}]", i, regname(addresses.sources[i]));
- }
- if (out_count == 1) {
- auto dest = addresses.destination;
- warnln(" dest [{}]", regname(dest));
- } else if (out_count > 1) {
- warnln(" dest [multiple outputs]");
- } else if (first_is_one_of(instruction->opcode(), Instructions::call, Instructions::call_indirect, Instructions::call_ref)) {
- if (addresses.destination != Dispatch::Stack)
- warnln(" dest [{}]", regname(addresses.destination));
- }
- }
- };
-
- if (start_ish > end_ish)
- swap(start_ish, end_ish);
- auto start_ip = start_ish >= 40 ? start_ish - 40 : 0;
- auto end_ip = min(result.dispatches.size(), end_ish + 10);
- auto skip_start = Optional<size_t> {};
- for (auto ip = start_ip; ip < end_ip; ip += 5) {
- size_t chunk_end = min(end_ip, ip + 5);
- print_range(ip, chunk_end);
- continue;
- bool has_mark = false;
- for (auto const& mark : { marks... }) {
- if (mark.ip >= ip && mark.ip < chunk_end) {
- has_mark = true;
- break;
- }
- }
- if (has_mark || ip == start_ip || chunk_end == end_ip) {
- if (skip_start.has_value()) {
- warnln("... skipping instructions [{:04}..{:04}] ...", *skip_start, ip);
- skip_start = {};
- }
- print_range(ip, chunk_end);
- } else if (!skip_start.has_value()) {
- skip_start = ip;
- }
- }
- };
-
- bool used[256] = { false };
- for (size_t i = 0; i < result.dispatches.size(); ++i) {
- auto& dispatch = result.dispatches[i];
- if (dispatch.instruction->opcode() == Instructions::if_) {
- // if (else) (end), verify (else) - 1 points at a synthetic:else_, and (end)-1+(!has-else) points at a synthetic:end.
- auto args = dispatch.instruction->arguments().get<Instruction::StructuredInstructionArgs>();
- if (args.else_ip().has_value()) {
- size_t else_ip = args.else_ip()->value() - 1;
- if (result.dispatches[else_ip].instruction->opcode() != Instructions::structured_else) {
- dbgln("Invalid else_ip target at instruction {}: else_ip {}", i, else_ip);
- dbgln("Instructions around the invalid else_ip:");
- print_instructions_around(i, else_ip, Mark { i, "invalid if_"sv }, Mark { else_ip, "this should've been an else"sv }, Mark { else_ip - 1, "previous instruction"sv }, Mark { else_ip + 1, "next instruction"sv });
- VERIFY_NOT_REACHED();
- }
- }
- size_t end_ip = args.end_ip.value() - 1 + (args.else_ip().has_value() ? 0 : 1);
- if (result.dispatches[end_ip].instruction->opcode() != Instructions::structured_end) {
- dbgln("Invalid end_ip target at instruction {}: end_ip {}", i, end_ip);
- dbgln("Instructions around the invalid end_ip:");
- print_instructions_around(i, end_ip, Mark { i, "invalid if_"sv }, Mark { end_ip, "this should've been an end"sv }, Mark { end_ip - 1, "previous instruction"sv }, Mark { end_ip + 1, "next instruction"sv });
- VERIFY_NOT_REACHED();
- }
- }
- // If the instruction is a call with a callrec, clear used[] for the callrec registers.
- if (dispatch.instruction->opcode() == Instructions::synthetic_call_with_record_0 || dispatch.instruction->opcode() == Instructions::synthetic_call_with_record_1) {
- for (size_t j = to_underlying(Dispatch::CallRecord); j <= to_underlying(Dispatch::LastCallRecord); ++j)
- used[j] = false;
- }
-
- auto& addr = result.src_dst_mappings[i];
-
- // for each input, ensure it's not reading from a register that is not marked as used (unless stack).
- auto [in_count, out_count] = instruction_operand_counts(dispatch.instruction->opcode());
- for (ssize_t j = 0; j < in_count; ++j) {
- auto src = addr.sources[j];
- if (src == Dispatch::Stack)
- continue;
- if (!used[to_underlying(src)]) {
- dbgln("Instruction {} reads from register {} which is not populated", i, to_underlying(src));
- dbgln("Instructions around the invalid read:");
- print_instructions_around(i, i, Mark { i, "invalid read here"sv });
- VERIFY_NOT_REACHED();
- }
- used[to_underlying(src)] = false;
- }
- // if the instruction has an output, ensure it's not writing to a register that is marked used.
- if (out_count == 1 || first_is_one_of(dispatch.instruction->opcode(), Instructions::call, Instructions::call_indirect, Instructions::call_ref)) {
- auto dest = addr.destination;
- if (dest != Dispatch::Stack) {
- if (used[to_underlying(dest)]) {
- dbgln("Instruction {} writes to register {} which is already populated", i, to_underlying(dest));
- dbgln("Instructions around the invalid write:");
- print_instructions_around(i, i, Mark { i, "invalid write here"sv });
- VERIFY_NOT_REACHED();
- }
- used[to_underlying(dest)] = true;
- }
- }
- }
-
- return result;
-}
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.h b/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.h
deleted file mode 100644
index ee0a92f5a68..00000000000
--- a/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/StackInfo.h>
-#include <LibWasm/AbstractMachine/Configuration.h>
-#include <LibWasm/AbstractMachine/Interpreter.h>
-#include <LibWasm/Export.h>
-
-namespace Wasm {
-
-enum class Outcome : u64 {
- // 0..Constants::max_allowed_executed_instructions_per_call -> next IP.
- Continue = Constants::max_allowed_executed_instructions_per_call + 1,
- Return,
-};
-
-struct WASM_API BytecodeInterpreter final : public Interpreter {
- explicit BytecodeInterpreter(StackInfo const& stack_info)
- : m_stack_info(stack_info)
- {
- }
-
- virtual void interpret(Configuration&) final;
-
- virtual ~BytecodeInterpreter() override = default;
- virtual bool did_trap() const final { return !m_trap.has<Empty>(); }
- virtual Trap trap() const final
- {
- return m_trap.get<Trap>();
- }
- virtual void clear_trap() final
- {
- if (!m_trap.has<Empty>()) [[unlikely]]
- m_trap = Empty {};
- }
- virtual void visit_external_resources(HostVisitOps const& host) override
- {
- if (auto ptr = m_trap.get_pointer<Trap>())
- if (auto data = ptr->data.get_pointer<ExternallyManagedTrap>())
- host.visit_trap(*data);
- }
-
- struct CallFrameHandle {
- explicit CallFrameHandle(BytecodeInterpreter& interpreter, Configuration& configuration)
- : m_configuration_handle(configuration)
- , m_interpreter(interpreter)
- {
- }
-
- ~CallFrameHandle() = default;
-
- Configuration::CallFrameHandle m_configuration_handle;
- BytecodeInterpreter& m_interpreter;
- };
-
- enum class CallAddressSource {
- DirectCall,
- IndirectCall,
- DirectTailCall,
- IndirectTailCall,
- };
-
- enum class CallType {
- UsingRegisters,
- UsingCallRecord,
- UsingStack,
- };
-
- template<bool HasCompiledList, bool HasDynamicInsnLimit, bool HaveDirectThreadingInfo>
- void interpret_impl(Configuration&, Expression const&);
-
- template<bool NeedsStackAdjustment>
- InstructionPointer branch_to_label(Configuration&, LabelIndex, InstructionPointer current_ip, bool actually_branching = true);
- Optional<InstructionPointer> unwind_to_throw_handler(Configuration&, ExceptionAddress);
- template<typename ReadT, typename PushT, SourceAddressMix>
- bool load_and_push(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<typename PopT, typename StoreT>
- bool pop_and_store(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<typename StoreT>
- bool store_value(Configuration&, Instruction const&, StoreT, size_t address_source, SourcesAndDestination const&);
- template<size_t N>
- bool pop_and_store_lane_n(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<size_t M, size_t N, template<typename> typename SetSign>
- bool load_and_push_mxn(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<size_t N>
- bool load_and_push_lane_n(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<size_t N>
- bool load_and_push_zero_n(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<size_t M>
- bool load_and_push_m_splat(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<size_t M, template<size_t> typename NativeType>
- void set_top_m_splat(Configuration&, NativeType<M>, SourcesAndDestination const&);
- template<size_t M, template<size_t> typename NativeType>
- void pop_and_push_m_splat(Configuration&, Instruction const&, SourcesAndDestination const&);
- template<typename M, template<typename> typename SetSign, typename VectorType = Native128ByteVectorOf<M, SetSign>>
- VectorType pop_vector(Configuration&, size_t source, SourcesAndDestination const&);
- bool store_to_memory(Configuration&, Instruction::MemoryArgument const&, ReadonlyBytes data, Value const& base);
- Outcome call_address(Configuration&, FunctionAddress, SourcesAndDestination const&, CallAddressSource = CallAddressSource::DirectCall, CallType = CallType::UsingStack);
- Outcome run_compiled_function_direct(Configuration&);
- Outcome run_native_entry(Configuration&);
- bool trap_if_insufficient_native_stack_space(size_t minimum_native_stack_space_to_keep_free = 2 * MiB);
-
- template<typename T>
- bool store_to_memory(MemoryInstance&, u64 address, T value);
-
- template<typename PopTypeLHS, typename PushType, typename Operator, SourceAddressMix, typename PopTypeRHS = PopTypeLHS, typename... Args>
- bool binary_numeric_operation(Configuration&, SourcesAndDestination const&, Args&&...);
-
- template<typename PopType, typename PushType, typename Operator, SourceAddressMix, size_t input_arg = 0, typename... Args>
- bool unary_operation(Configuration&, SourcesAndDestination const&, Args&&...);
-
- ALWAYS_INLINE bool set_trap(StringView reason)
- {
- m_trap = Trap { ByteString(reason) };
- return true;
- }
-
- ALWAYS_INLINE bool set_trap(Trap trap)
- {
- m_trap = move(trap);
- return true;
- }
-
- template<typename T>
- T read_value(ReadonlyBytes data);
-
- ALWAYS_INLINE bool trap_if_not(bool value, StringView reason)
- {
- if (!value) [[unlikely]] {
- m_trap = Trap { ByteString(reason) };
- return true;
- }
- return false;
- }
-
- template<typename... Rest>
- ALWAYS_INLINE bool trap_if_not(bool value, StringView reason, CheckedFormatString<StringView, Rest...> format, Rest const&... args)
- {
- if (!value) [[unlikely]] {
- m_trap = Trap { ByteString::formatted(move(format), reason, args...) };
- return true;
- }
- return false;
- }
-
-protected:
- Variant<Trap, Empty> m_trap;
- StackInfo const& m_stack_info;
-};
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/Configuration.cpp b/Libraries/LibWasm/AbstractMachine/Configuration.cpp
deleted file mode 100644
index f0d1deb7caa..00000000000
--- a/Libraries/LibWasm/AbstractMachine/Configuration.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/MemoryStream.h>
-#include <LibWasm/AbstractMachine/Configuration.h>
-#include <LibWasm/AbstractMachine/Interpreter.h>
-#include <LibWasm/Printer/Printer.h>
-
-namespace Wasm {
-
-void Configuration::unwind_impl()
-{
- m_depth--;
-
- Optional<Vector<Value, ArgumentsStaticSize>> released_locals;
- auto const* popped_module = &m_frame_stack.last().module();
- if (m_frame_stack.last().owns_locals())
- released_locals = m_owned_locals_stack.take_last();
- m_frame_stack.remove(m_frame_stack.size() - 1);
-
- if (m_frame_stack.is_empty()) {
- m_locals_base = nullptr;
- m_memory_instances = nullptr;
- m_global_instances = nullptr;
- } else {
- auto& caller = m_frame_stack.last();
- m_locals_base = caller.owns_locals() ? m_owned_locals_stack.last().data() : caller.locals_data();
- if (&caller.module() != popped_module) {
- m_memory_instances = caller.module().resolved_memories(m_store);
- m_global_instances = caller.module().resolved_globals(m_store);
- }
- }
-
- if (released_locals.has_value())
- release_arguments_allocation(released_locals.value());
-}
-
-Result Configuration::call(Interpreter& interpreter, FunctionAddress address, Vector<Value, ArgumentsStaticSize>& arguments)
-{
- if (auto fn = TRY(prepare_call(address, arguments)); fn.has_value())
- return fn->function()(*this, arguments.span());
- m_ip = 0;
- return execute(interpreter);
-}
-
-ErrorOr<Optional<HostFunction&>, Trap> Configuration::prepare_call(FunctionAddress address, Vector<Value, ArgumentsStaticSize>& arguments, bool is_tailcall)
-{
- auto* function = m_store.get(address);
- if (!function)
- return Trap::from_string("Attempt to call nonexistent function by address");
-
- if (auto* wasm_function = function->get_pointer<WasmFunction>()) {
- TRY(prepare_wasm_call(*wasm_function, arguments, is_tailcall));
- return OptionalNone {};
- }
-
- return function->get<HostFunction>();
-}
-
-ErrorOr<void, Trap> Configuration::prepare_wasm_call(WasmFunction const& wasm_function, Vector<Value, ArgumentsStaticSize>& arguments, bool is_tailcall)
-{
- // Tier-0 by default: don't block the call waiting for native compilation. Non-Web embedders
- // compile synchronously at instantiate time (so the JIT is already live here); the Web path
- // compiles in the background and the interpreter picks up the native entry on a later call
- // once it's published. Either way, execution falls back to the interpreter until then.
- if (is_tailcall)
- unwind_impl();
-
- auto inlined_locals = wasm_function.code().func().body().compiled_instructions.cranelift_inlined_locals;
- arguments.ensure_capacity(arguments.size() + wasm_function.code().func().total_local_count() + inlined_locals);
- for (auto const& local : wasm_function.code().func().locals()) {
- for (size_t i = 0; i < local.n(); ++i)
- arguments.unchecked_append(Value(local.type()));
- }
- for (u32 i = 0; i < inlined_locals; ++i)
- arguments.unchecked_append(Value(ValueType { ValueType::I32 }));
-
- set_frame(
- is_tailcall ? IsTailcall::Yes : IsTailcall::No,
- wasm_function.module(),
- move(arguments),
- wasm_function.code().func().body(),
- wasm_function.type().results().size());
- return {};
-}
-
-Result Configuration::execute(Interpreter& interpreter)
-{
- interpreter.interpret(*this);
- if (interpreter.did_trap())
- return interpreter.trap();
-
- Vector<Value, ResultsStaticSize> results { value_stack().span().slice_from_end(frame().arity()) };
- value_stack().shrink(value_stack().size() - results.size(), true);
- results.reverse();
-
- // If we reached here from a tailcall -> return, we might not have a label to pop (because the return already popped it)
- if (label_stack().size() > frame().label_index())
- label_stack().shrink(frame().label_index(), true);
-
- return Result { move(results) };
-}
-
-ErrorOr<void, Trap> Configuration::execute_for_compiled_call(Interpreter& interpreter, Value* single_result)
-{
- interpreter.interpret(*this);
- if (interpreter.did_trap())
- return interpreter.trap();
-
- VERIFY(frame().arity() <= 1);
- if (frame().arity() == 1) {
- auto result = value_stack().unsafe_take_last();
- if (single_result)
- *single_result = result;
- }
-
- if (!label_stack().is_empty())
- label_stack().take_last();
-
- return {};
-}
-
-void Configuration::reset_after_invoke(Badge<AbstractMachine>)
-{
- m_value_stack.reset_and_clear();
- m_call_record_stack.reset_and_clear();
-
- m_label_stack.clear_with_capacity();
- m_frame_stack.clear_with_capacity();
- m_owned_locals_stack.clear_with_capacity();
- m_call_argument_freelist.clear_with_capacity();
- regs.fill(Value(0));
-
- m_depth = 0;
- m_ip = 0;
- m_locals_base = nullptr;
- m_call_record_base = nullptr;
- m_memory_instances = nullptr;
- m_global_instances = nullptr;
- m_compiled_call_result_scratch = Value(0);
-}
-
-void Configuration::dump_stack()
-{
- auto print_value = []<typename... Ts>(CheckedFormatString<Ts...> format, Ts... vs) {
- AllocatingMemoryStream memory_stream;
- Printer { memory_stream }.print(vs...);
- auto buffer = ByteBuffer::create_uninitialized(memory_stream.used_buffer_size()).release_value_but_fixme_should_propagate_errors();
- memory_stream.read_until_filled(buffer).release_value_but_fixme_should_propagate_errors();
- dbgln(format.view(), StringView(buffer).trim_whitespace());
- };
- for (auto const& value : value_stack()) {
- print_value(" {}", value);
- }
-}
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/Configuration.h b/Libraries/LibWasm/AbstractMachine/Configuration.h
deleted file mode 100644
index 81a0c0c6f91..00000000000
--- a/Libraries/LibWasm/AbstractMachine/Configuration.h
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/DoublyLinkedList.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/AbstractMachine/ValueStack.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-enum class SourceAddressMix {
- AllRegisters,
- AllCallRecords,
- AllStack,
- Any,
-};
-
-enum class IsTailcall {
- No,
- Yes,
-};
-
-class Configuration {
- AK_MAKE_NONCOPYABLE(Configuration);
- AK_MAKE_NONMOVABLE(Configuration);
-
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- explicit Configuration(Store& store)
- : m_store(store)
- {
- m_store.register_configuration({}, *this);
- }
-
- ~Configuration()
- {
- m_store.unregister_configuration({}, *this);
- }
-
- void set_frame(IsTailcall is_tailcall, ModuleInstance const& module, Vector<Value, ArgumentsStaticSize> locals, Expression const& expression, size_t arity)
- {
- m_owned_locals_stack.append(move(locals));
- auto* locals_ptr = m_owned_locals_stack.last().data();
- m_frame_stack.empend(module, locals_ptr, expression, arity, /* owns_locals = */ true);
-
- auto& frame = m_frame_stack.last();
- m_locals_base = locals_ptr;
- m_memory_instances = frame.module().resolved_memories(m_store);
- m_global_instances = frame.module().resolved_globals(m_store);
- frame.set_compiled_fn_table(&frame.module().compiled_fn_table(m_store));
-
- auto continuation = frame.expression().instructions().size() - 1;
- if (auto size = frame.expression().compiled_instructions.dispatches.size(); size > 0)
- continuation = size - 1;
- Label label(frame.arity(), continuation, m_value_stack.size());
- frame.label_index() = m_label_stack.size();
- if (auto hint = frame.expression().stack_usage_hint(); hint.has_value())
- m_value_stack.ensure_capacity(*hint + m_value_stack.size());
- if (auto depth = frame.expression().compiled_instructions.max_label_depth; depth > 0)
- m_label_stack.ensure_capacity(depth + m_label_stack.size());
- m_label_stack.append(label);
-
- // A tail call replaces the current frame, so release its record first; otherwise a
- // tail-call loop would grow the record region without bound.
- if (is_tailcall == IsTailcall::Yes && m_call_record_base)
- m_call_record_stack.release_to(m_call_record_base);
- auto max_call_rec_size = frame.expression().compiled_instructions.max_call_rec_size;
- if (max_call_rec_size > 0)
- m_call_record_base = m_call_record_stack.allocate(max_call_rec_size);
- else
- m_call_record_base = nullptr;
- }
- // Lightweight set_frame for direct Cranelift-to-Cranelift calls.
- void set_frame_lightweight(ModuleInstance const& module, Value* locals_ptr,
- Expression const& expression, size_t arity, size_t max_call_rec_size)
- {
- VERIFY(bit_cast<FlatPtr>(&module) != 0);
-
- // For the (common) same-module call case, we already have the compiled-fn-table pointer cached on the caller's frame, so reuse it instead of re-resolving through the store on every call.
- bool const same_module = !m_frame_stack.is_empty() && &m_frame_stack.last().module() == &module;
- auto const* table = same_module ? m_frame_stack.last().compiled_fn_table() : &module.compiled_fn_table(m_store);
- m_frame_stack.empend(module, locals_ptr, expression, arity);
- m_frame_stack.last().set_compiled_fn_table(table);
- m_locals_base = locals_ptr;
- if (!same_module) {
- m_memory_instances = module.resolved_memories(m_store);
- m_global_instances = module.resolved_globals(m_store);
- }
- // Compiled code pushes to the value stack without bounds checks, so verify here that the
- // frame's whole stack usage fits the reservation.
- if (auto hint = expression.stack_usage_hint(); hint.has_value())
- m_value_stack.ensure_capacity(m_value_stack.size() + *hint);
- // Compiled code writes call-record entries without null checks, so allocate eagerly
- // (heavy set_frame does the same).
- if (max_call_rec_size > 0)
- m_call_record_base = m_call_record_stack.allocate(max_call_rec_size);
- // Skip the label push (Cranelift uses its own structured control flow).
- }
-
- ALWAYS_INLINE auto& frame() const { return m_frame_stack.last(); }
- ALWAYS_INLINE auto& frame() { return m_frame_stack.last(); }
- ALWAYS_INLINE auto& ip() const { return m_ip; }
- ALWAYS_INLINE auto& ip() { return m_ip; }
- ALWAYS_INLINE auto& depth() const { return m_depth; }
- ALWAYS_INLINE auto& depth() { return m_depth; }
- ALWAYS_INLINE auto& value_stack() const { return m_value_stack; }
- ALWAYS_INLINE auto& value_stack() { return m_value_stack; }
- ALWAYS_INLINE auto& label_stack() const { return m_label_stack; }
- ALWAYS_INLINE auto& label_stack() { return m_label_stack; }
- ALWAYS_INLINE auto& store() const { return m_store; }
- ALWAYS_INLINE auto& store() { return m_store; }
- ALWAYS_INLINE MemoryInstance* memory_instance(size_t index) const { return m_memory_instances[index]; }
- ALWAYS_INLINE Value& compiled_call_result_scratch() { return m_compiled_call_result_scratch; }
- ALWAYS_INLINE Value const& compiled_call_result_scratch() const { return m_compiled_call_result_scratch; }
-
- ALWAYS_INLINE Value const& local(LocalIndex index) const { return m_locals_base[index.value()]; }
- ALWAYS_INLINE Value& local(LocalIndex index) { return m_locals_base[index.value()]; }
- ALWAYS_INLINE Value* locals_base() const { return m_locals_base; }
- ALWAYS_INLINE void set_locals_base(Value* base) { m_locals_base = base; }
-
- static constexpr size_t locals_base_offset() { return __builtin_offsetof(Configuration, m_locals_base); }
- static constexpr size_t memory_instances_offset() { return __builtin_offsetof(Configuration, m_memory_instances); }
- static constexpr size_t global_instances_offset() { return __builtin_offsetof(Configuration, m_global_instances); }
- static constexpr size_t compiled_call_result_scratch_offset() { return __builtin_offsetof(Configuration, m_compiled_call_result_scratch); }
- static constexpr size_t value_stack_base_offset() { return __builtin_offsetof(Configuration, m_value_stack) + ValueStack::base_offset(); }
- static constexpr size_t value_stack_top_offset() { return __builtin_offsetof(Configuration, m_value_stack) + ValueStack::top_offset(); }
- static constexpr size_t call_record_base_offset() { return __builtin_offsetof(Configuration, m_call_record_base); }
-
- ALWAYS_INLINE Value& call_record_entry(size_t index) { return m_call_record_base[index]; }
- ALWAYS_INLINE Value const& call_record_entry(size_t index) const { return m_call_record_base[index]; }
- ALWAYS_INLINE Value* call_record_base() const { return m_call_record_base; }
- ALWAYS_INLINE void set_call_record_base(Value* base) { m_call_record_base = base; }
- ALWAYS_INLINE void setup_call_record(size_t max_call_rec_size)
- {
- m_call_record_base = m_call_record_stack.allocate(max_call_rec_size);
- }
-
- struct CallFrameHandle {
- explicit CallFrameHandle(Configuration& configuration)
- : configuration(configuration)
- , saved_call_record_base(configuration.m_call_record_base)
- , saved_call_record_mark(configuration.m_call_record_stack.mark())
- {
- configuration.depth()++;
- configuration.m_call_record_base = nullptr;
- }
-
- ~CallFrameHandle()
- {
- configuration.m_call_record_stack.release_to(saved_call_record_mark);
- configuration.m_call_record_base = saved_call_record_base;
- configuration.unwind({}, *this);
- }
-
- Configuration& configuration;
- Value* saved_call_record_base;
- Value* saved_call_record_mark;
- };
-
- void unwind(Badge<CallFrameHandle>, CallFrameHandle const&) { unwind_impl(); }
- ErrorOr<Optional<HostFunction&>, Trap> prepare_call(FunctionAddress, Vector<Value, ArgumentsStaticSize>& arguments, bool is_tailcall = false);
- ErrorOr<void, Trap> prepare_wasm_call(WasmFunction const& wasm_function, Vector<Value, ArgumentsStaticSize>& arguments, bool is_tailcall = false);
- Result call(Interpreter&, FunctionAddress, Vector<Value, ArgumentsStaticSize>& arguments);
- Result execute(Interpreter&);
- ErrorOr<void, Trap> execute_for_compiled_call(Interpreter&, Value* single_result = nullptr);
-
- void enable_instruction_count_limit() { m_should_limit_instruction_count = true; }
- bool should_limit_instruction_count() const { return m_should_limit_instruction_count; }
-
- void reset_after_invoke(Badge<AbstractMachine>);
-
- void dump_stack();
-
- void get_arguments_allocation_if_possible(Vector<Value, ArgumentsStaticSize>& arguments, size_t max_size)
- {
- if (arguments.capacity() != ArgumentsStaticSize || max_size <= ArgumentsStaticSize)
- return; // Already heap allocated, or we just don't need to allocate anything.
-
- // _arguments_ is still in static storage, pull something from the freelist if it fits.
- if (auto index = m_call_argument_freelist.find_first_index_if([&](auto& entry) { return entry.capacity() >= max_size; }); index.has_value()) {
- arguments = m_call_argument_freelist.take(*index);
- return;
- }
-
- if (!m_call_argument_freelist.is_empty())
- arguments = m_call_argument_freelist.take_last();
-
- arguments.ensure_capacity(max(max_size, frame().module().cached_minimum_call_record_allocation_size));
- }
-
- void release_arguments_allocation(Vector<Value, ArgumentsStaticSize>& arguments)
- {
- arguments.clear_with_capacity(); // Clear to avoid copying, but keep capacity for reuse.
-
- if (arguments.capacity() != ArgumentsStaticSize) {
- if (m_call_argument_freelist.size() >= 16) {
- // Don't grow to heap.
- return;
- }
-
- m_call_argument_freelist.unchecked_append(move(arguments));
- }
- }
-
- template<SourceAddressMix mix>
- ALWAYS_INLINE FLATTEN void push_to_destination(Value value, Dispatch::RegisterOrStack destination)
- {
- if constexpr (mix == SourceAddressMix::AllRegisters) {
- regs.data()[to_underlying(destination)] = value;
- return;
- } else if constexpr (mix == SourceAddressMix::AllCallRecords) {
- m_call_record_base[to_underlying(destination) - Dispatch::RegisterOrStack::CallRecord] = value;
- return;
- } else if constexpr (mix == SourceAddressMix::AllStack) {
- value_stack().unchecked_append(value);
- return;
- } else if constexpr (mix == SourceAddressMix::Any) {
- if (!(destination & ~(Dispatch::Stack - 1))) [[likely]] {
- regs.data()[to_underlying(destination)] = value;
- return;
- }
- }
-
- if constexpr (mix == SourceAddressMix::Any) {
- if (destination == Dispatch::RegisterOrStack::Stack) [[unlikely]] {
- value_stack().unchecked_append(value);
- return;
- }
-
- m_call_record_base[to_underlying(destination) - Dispatch::RegisterOrStack::CallRecord] = value;
- return;
- }
-
- VERIFY_NOT_REACHED();
- }
-
- template<SourceAddressMix mix>
- ALWAYS_INLINE FLATTEN Value& source_value(u8 index, Dispatch::RegisterOrStack const* sources)
- {
- // Note: The last source in a dispatch *must* be equal to the destination for this to be valid.
- auto const source = sources[index];
-
- if constexpr (mix == SourceAddressMix::AllRegisters) {
- return regs.data()[to_underlying(source)];
- } else if constexpr (mix == SourceAddressMix::AllCallRecords) {
- return m_call_record_base[to_underlying(source) - Dispatch::RegisterOrStack::CallRecord];
- } else if constexpr (mix == SourceAddressMix::AllStack) {
- return value_stack().unsafe_last();
- } else if constexpr (mix == SourceAddressMix::Any) {
- if (!(source & ~(Dispatch::Stack - 1))) [[likely]]
- return regs.data()[to_underlying(source)];
- }
-
- if constexpr (mix == SourceAddressMix::Any) {
- if (source == Dispatch::RegisterOrStack::Stack) [[unlikely]]
- return value_stack().unsafe_last();
-
- return m_call_record_base[to_underlying(source) - Dispatch::RegisterOrStack::CallRecord];
- }
-
- VERIFY_NOT_REACHED();
- }
-
- template<SourceAddressMix mix>
- ALWAYS_INLINE FLATTEN Value take_source(u8 index, Dispatch::RegisterOrStack const* sources)
- {
- auto const source = sources[index];
- if constexpr (mix == SourceAddressMix::AllRegisters) {
- return regs.data()[to_underlying(source)];
- } else if constexpr (mix == SourceAddressMix::AllCallRecords) {
- return m_call_record_base[to_underlying(source) - Dispatch::RegisterOrStack::CallRecord];
- } else if constexpr (mix == SourceAddressMix::AllStack) {
- return value_stack().unsafe_take_last();
- } else if constexpr (mix == SourceAddressMix::Any) {
- if (!(source & ~(Dispatch::Stack - 1))) [[likely]]
- return regs.data()[to_underlying(source)];
- }
-
- if constexpr (mix == SourceAddressMix::Any) {
- if (source == Dispatch::RegisterOrStack::Stack) [[unlikely]]
- return value_stack().unsafe_take_last();
-
- return m_call_record_base[to_underlying(source) - Dispatch::RegisterOrStack::CallRecord];
- }
-
- VERIFY_NOT_REACHED();
- }
-
- Array<Value, Dispatch::RegisterOrStack::CountRegisters> regs = {
- Value(0),
- Value(0),
- Value(0),
- Value(0),
- Value(0),
- Value(0),
- Value(0),
- Value(0),
- };
-
- // Public for CraneliftBridge direct call pop_frame.
- void unwind_impl();
-
- Store& m_store;
- ValueStack m_value_stack;
- ValueStack m_call_record_stack;
- Vector<Label, 64, FastLastAccess::Yes> m_label_stack;
- Vector<Frame> m_frame_stack;
- Vector<Vector<Value, ArgumentsStaticSize>> m_owned_locals_stack;
- Vector<Vector<Value, ArgumentsStaticSize>, 16, FastLastAccess::Yes> m_call_argument_freelist;
- size_t m_depth { 0 };
- u64 m_ip { 0 };
- bool m_should_limit_instruction_count { false };
- Value* m_locals_base { nullptr };
- Value* m_call_record_base { nullptr };
- MemoryInstanceTable m_memory_instances { nullptr };
- GlobalInstanceTable m_global_instances { nullptr };
- Value m_compiled_call_result_scratch;
-};
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/Interpreter.h b/Libraries/LibWasm/AbstractMachine/Interpreter.h
deleted file mode 100644
index d9bb59ac4a0..00000000000
--- a/Libraries/LibWasm/AbstractMachine/Interpreter.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWasm/AbstractMachine/Configuration.h>
-
-namespace Wasm {
-
-struct Interpreter {
- AK_ALLOC_WITH_KMALLOC;
-
- virtual ~Interpreter() = default;
- virtual void interpret(Configuration&) = 0;
- virtual Trap trap() const = 0;
- virtual bool did_trap() const = 0;
- virtual void clear_trap() = 0;
- virtual void visit_external_resources(HostVisitOps const&) { }
-};
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/Operators.h b/Libraries/LibWasm/AbstractMachine/Operators.h
deleted file mode 100644
index d798e9eab94..00000000000
--- a/Libraries/LibWasm/AbstractMachine/Operators.h
+++ /dev/null
@@ -1,1222 +0,0 @@
-/*
- * Copyright (c) 2021-2023, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/BitCast.h>
-#include <AK/BuiltinWrappers.h>
-#include <AK/Math.h>
-#include <AK/Result.h>
-#include <AK/SIMD.h>
-#include <AK/SIMDExtras.h>
-#include <AK/StringView.h>
-#include <AK/Types.h>
-#include <LibWasm/Types.h>
-#include <limits.h>
-#include <math.h>
-
-namespace Wasm::Operators {
-
-using namespace AK::SIMD;
-
-#define DEFINE_BINARY_OPERATOR(Name, operation) \
- struct Name { \
- template<typename Lhs, typename Rhs> \
- auto operator()(Lhs lhs, Rhs rhs) const \
- { \
- return lhs operation rhs; \
- } \
- \
- static StringView name() \
- { \
- return #operation##sv; \
- } \
- }
-
-DEFINE_BINARY_OPERATOR(Equals, ==);
-DEFINE_BINARY_OPERATOR(NotEquals, !=);
-DEFINE_BINARY_OPERATOR(GreaterThan, >);
-DEFINE_BINARY_OPERATOR(LessThan, <);
-DEFINE_BINARY_OPERATOR(LessThanOrEquals, <=);
-DEFINE_BINARY_OPERATOR(GreaterThanOrEquals, >=);
-DEFINE_BINARY_OPERATOR(Add, +);
-DEFINE_BINARY_OPERATOR(Subtract, -);
-DEFINE_BINARY_OPERATOR(Multiply, *);
-DEFINE_BINARY_OPERATOR(BitAnd, &);
-DEFINE_BINARY_OPERATOR(BitOr, |);
-DEFINE_BINARY_OPERATOR(BitXor, ^);
-
-#undef DEFINE_BINARY_OPERATOR
-
-struct Identity {
- auto operator()(auto x) const { return x; }
-};
-
-struct Divide {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- if constexpr (IsFloatingPoint<Lhs>) {
- return lhs / rhs;
- } else {
- Checked value(lhs);
- value /= rhs;
- if (value.has_overflow())
- return AK::ErrorOr<Lhs, StringView>("Integer division overflow"sv);
- return AK::ErrorOr<Lhs, StringView>(value.value());
- }
- }
-
- static StringView name() { return "/"sv; }
-};
-
-struct Modulo {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- if (rhs == 0)
- return AK::ErrorOr<Lhs, StringView>("Integer division overflow"sv);
- if constexpr (IsSigned<Lhs>) {
- if (rhs == -1)
- return AK::ErrorOr<Lhs, StringView>(0); // Spec weirdness right here, signed division overflow is ignored.
- }
- return AK::ErrorOr<Lhs, StringView>(lhs % rhs);
- }
-
- static StringView name() { return "%"sv; }
-};
-
-struct Average {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- return static_cast<Lhs>((lhs + rhs + 1) / 2);
- }
-
- static StringView name() { return "avgr"sv; }
-};
-
-struct Q15Mul {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- return (lhs * rhs + 0x4000) >> 15;
- }
-
- static StringView name() { return "q15mul"sv; }
-};
-
-struct BitShiftLeft {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const { return lhs << (rhs % (sizeof(lhs) * 8)); }
-
- static StringView name() { return "<<"sv; }
-};
-
-struct BitShiftRight {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const { return lhs >> (rhs % (sizeof(lhs) * 8)); }
-
- static StringView name() { return ">>"sv; }
-};
-
-struct BitAndNot {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const { return lhs & ~rhs; }
-
- static StringView name() { return "andnot"sv; }
-};
-
-struct BitNot {
- template<typename Lhs>
- auto operator()(Lhs lhs) const { return ~lhs; }
-
- static StringView name() { return "~"sv; }
-};
-
-struct BitRotateLeft {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- // generates a single 'rol' instruction if shift is positive
- // otherwise generate a `ror`
- auto const mask = CHAR_BIT * sizeof(Lhs) - 1;
- rhs &= mask;
- return (lhs << rhs) | (lhs >> ((-rhs) & mask));
- }
-
- static StringView name() { return "rotate_left"sv; }
-};
-
-struct BitRotateRight {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- // generates a single 'ror' instruction if shift is positive
- // otherwise generate a `rol`
- auto const mask = CHAR_BIT * sizeof(Lhs) - 1;
- rhs &= mask;
- return (lhs >> rhs) | (lhs << ((-rhs) & mask));
- }
-
- static StringView name() { return "rotate_right"sv; }
-};
-
-template<size_t VectorSize, template<typename> typename SetSign = MakeSigned>
-struct VectorAllTrue {
- auto operator()(u128 c) const
- {
- using ElementType = NativeIntegralType<128 / VectorSize>;
-
- auto any_false = bit_cast<Native128ByteVectorOf<ElementType, SetSign>>(c) == 0;
- return bit_cast<u128>(any_false) == 0;
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16).all_true"sv;
- case 8:
- return "vec(16x8).all_true"sv;
- case 4:
- return "vec(32x4).all_true"sv;
- case 2:
- return "vec(64x2).all_true"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize>
-struct VectorShiftLeft {
- auto operator()(u128 lhs, i32 rhs) const
- {
- auto shift_value = rhs % (sizeof(lhs) * 8 / VectorSize);
- return bit_cast<u128>(bit_cast<Native128ByteVectorOf<NativeIntegralType<128 / VectorSize>, MakeUnsigned>>(lhs) << shift_value);
- }
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16)<<"sv;
- case 8:
- return "vec(16x8)<<"sv;
- case 4:
- return "vec(32x4)<<"sv;
- case 2:
- return "vec(64x2)<<"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, template<typename> typename SetSign>
-struct VectorShiftRight {
- auto operator()(u128 lhs, i32 rhs) const
- {
- auto shift_value = rhs % (sizeof(lhs) * 8 / VectorSize);
- return bit_cast<u128>(bit_cast<Native128ByteVectorOf<SetSign<NativeIntegralType<128 / VectorSize>>, SetSign>>(lhs) >> shift_value);
- }
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16)>>"sv;
- case 8:
- return "vec(16x8)>>"sv;
- case 4:
- return "vec(32x4)>>"sv;
- case 2:
- return "vec(64x2)>>"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-struct VectorSwizzle {
- auto operator()(u128 c1, u128 c2) const
- {
- // https://webassembly.github.io/spec/core/bikeshed/#-mathsfi8x16hrefsyntax-instr-vecmathsfswizzle%E2%91%A0
- auto i = bit_cast<Native128ByteVectorOf<i8, MakeSigned>>(c1);
- auto j = bit_cast<Native128ByteVectorOf<i8, MakeSigned>>(c2);
- auto result = shuffle_or_0(i, j);
- return bit_cast<u128>(result);
- }
- static StringView name() { return "vec(8x16).swizzle"sv; }
-};
-
-template<size_t VectorSize, template<typename> typename SetSign>
-struct VectorExtractLane {
- size_t lane;
-
- auto operator()(u128 c) const
- {
- auto result = bit_cast<Native128ByteVectorOf<NativeIntegralType<128 / VectorSize>, SetSign>>(c);
- return result[lane];
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16).extract_lane"sv;
- case 8:
- return "vec(16x8).extract_lane"sv;
- case 4:
- return "vec(32x4).extract_lane"sv;
- case 2:
- return "vec(64x2).extract_lane"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize>
-struct VectorExtractLaneFloat {
- size_t lane;
-
- auto operator()(u128 c) const
- {
- auto result = bit_cast<NativeFloatingVectorType<128 / VectorSize, VectorSize>>(c);
- return result[lane];
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16).extract_lane"sv;
- case 8:
- return "vec(16x8).extract_lane"sv;
- case 4:
- return "vec(32x4).extract_lane"sv;
- case 2:
- return "vec(64x2).extract_lane"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, typename TrueValueType = NativeIntegralType<128 / VectorSize>>
-struct VectorReplaceLane {
- size_t lane;
- using ValueType = Conditional<IsFloatingPoint<TrueValueType>, NativeFloatingType<128 / VectorSize>, NativeIntegralType<128 / VectorSize>>;
-
- auto operator()(u128 c, TrueValueType value) const
- {
- auto result = bit_cast<Native128ByteVectorOf<ValueType, MakeUnsigned>>(c);
- result[lane] = static_cast<ValueType>(value);
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16).replace_lane"sv;
- case 8:
- return "vec(16x8).replace_lane"sv;
- case 4:
- return "vec(32x4).replace_lane"sv;
- case 2:
- return "vec(64x2).replace_lane"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, typename Op, template<typename> typename SetSign = MakeSigned>
-struct VectorCmpOp {
- auto operator()(u128 c1, u128 c2) const
- {
- using ElementType = NativeIntegralType<128 / VectorSize>;
- auto result = bit_cast<Native128ByteVectorOf<ElementType, SetSign>>(c1);
- auto other = bit_cast<Native128ByteVectorOf<ElementType, SetSign>>(c2);
- Op op;
- for (size_t i = 0; i < VectorSize; ++i) {
- SetSign<ElementType> lhs = result[i];
- SetSign<ElementType> rhs = other[i];
- result[i] = op(lhs, rhs) ? static_cast<MakeUnsigned<ElementType>>(-1) : 0;
- }
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16).cmp"sv;
- case 8:
- return "vec(16x8).cmp"sv;
- case 4:
- return "vec(32x4).cmp"sv;
- case 2:
- return "vec(64x2).cmp"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, typename Op>
-struct VectorFloatCmpOp {
- auto operator()(u128 c1, u128 c2) const
- {
- auto first = bit_cast<NativeFloatingVectorType<128, VectorSize, NativeFloatingType<128 / VectorSize>>>(c1);
- auto other = bit_cast<NativeFloatingVectorType<128, VectorSize, NativeFloatingType<128 / VectorSize>>>(c2);
- using ElementType = NativeIntegralType<128 / VectorSize>;
- Native128ByteVectorOf<ElementType, MakeUnsigned> result;
- Op op;
- for (size_t i = 0; i < VectorSize; ++i)
- result[i] = op(first[i], other[i]) ? static_cast<ElementType>(-1) : 0;
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 4:
- return "vecf(32x4).cmp"sv;
- case 2:
- return "vecf(64x2).cmp"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-struct Minimum {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- if constexpr (IsFloatingPoint<Lhs> || IsFloatingPoint<Rhs>) {
- if (isnan(lhs) || isnan(rhs))
- return AK::NaN<Lhs>;
- if (lhs == 0 && rhs == 0)
- return signbit(lhs) ? lhs : rhs;
- }
- return min(lhs, rhs);
- }
-
- static StringView name() { return "minimum"sv; }
-};
-
-struct Maximum {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- if constexpr (IsFloatingPoint<Lhs> || IsFloatingPoint<Rhs>) {
- if (isnan(lhs) || isnan(rhs))
- return AK::NaN<Lhs>;
- if (lhs == 0 && rhs == 0)
- return signbit(lhs) ? rhs : lhs;
- }
- return max(lhs, rhs);
- }
-
- static StringView name() { return "maximum"sv; }
-};
-
-struct PseudoMinimum {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- return rhs < lhs ? rhs : lhs;
- }
-
- static StringView name() { return "pseudo_minimum"sv; }
-};
-
-struct PseudoMaximum {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- return lhs < rhs ? rhs : lhs;
- }
-
- static StringView name() { return "pseudo_maximum"sv; }
-};
-
-struct CopySign {
- template<typename Lhs, typename Rhs>
- auto operator()(Lhs lhs, Rhs rhs) const
- {
- if constexpr (IsSame<Lhs, float>)
- return copysignf(lhs, rhs);
- else if constexpr (IsSame<Lhs, double>)
- return copysign(lhs, rhs);
- else
- static_assert(DependentFalse<Lhs, Rhs>, "Invalid types to CopySign");
- }
-
- static StringView name() { return "copysign"sv; }
-};
-
-// Unary
-
-struct EqualsZero {
- template<typename Lhs>
- auto operator()(Lhs lhs) const { return lhs == 0; }
-
- static StringView name() { return "== 0"sv; }
-};
-
-struct CountLeadingZeros {
- template<typename Lhs>
- i32 operator()(Lhs lhs) const
- {
- if (lhs == 0)
- return sizeof(Lhs) * CHAR_BIT;
-
- if constexpr (sizeof(Lhs) == 4 || sizeof(Lhs) == 8)
- return count_leading_zeroes(MakeUnsigned<Lhs>(lhs));
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "clz"sv; }
-};
-
-struct CountTrailingZeros {
- template<typename Lhs>
- i32 operator()(Lhs lhs) const
- {
- if (lhs == 0)
- return sizeof(Lhs) * CHAR_BIT;
-
- if constexpr (sizeof(Lhs) == 4 || sizeof(Lhs) == 8)
- return count_trailing_zeroes(MakeUnsigned<Lhs>(lhs));
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "ctz"sv; }
-};
-
-struct PopCount {
- template<typename Lhs>
- auto operator()(Lhs lhs) const
- {
- if constexpr (sizeof(Lhs) == 1 || sizeof(Lhs) == 2 || sizeof(Lhs) == 4 || sizeof(Lhs) == 8)
- return popcount(MakeUnsigned<Lhs>(lhs));
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "popcnt"sv; }
-};
-
-struct Absolute {
- template<typename Lhs>
- Lhs operator()(Lhs lhs) const
- {
- if constexpr (IsFloatingPoint<Lhs>)
- return AK::abs(lhs);
-
- if constexpr (IsSigned<Lhs>) {
- if (lhs == NumericLimits<Lhs>::min())
- return NumericLimits<Lhs>::min(); // Return the negation of _i_ modulo 2^N: https://www.w3.org/TR/wasm-core-2/#-hrefop-iabsmathrmiabs_n-i step 3
- }
-
- return AK::abs(lhs);
- }
-
- static StringView name() { return "abs"sv; }
-};
-
-struct Negate {
- template<typename Lhs>
- Lhs operator()(Lhs lhs) const
- {
- if constexpr (IsFloatingPoint<Lhs>)
- return -lhs;
-
- if constexpr (IsSigned<Lhs>) {
- if (lhs == NumericLimits<Lhs>::min())
- return NumericLimits<Lhs>::min(); // Return the negation of _i_ modulo 2^N: https://www.w3.org/TR/wasm-core-2/#-hrefop-iabsmathrmiabs_n-i step 3
- }
-
- return -lhs;
- }
-
- static StringView name() { return "neg"sv; }
-};
-
-struct Ceil {
- template<typename Lhs>
- auto operator()(Lhs lhs) const
- {
- if (isnan(lhs))
- return AK::NaN<Lhs>;
-
- if constexpr (IsSame<Lhs, float>)
- return ceilf(lhs);
- else if constexpr (IsSame<Lhs, double>)
- return ceil(lhs);
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "ceil"sv; }
-};
-
-template<size_t VectorSize, typename Op, template<typename> typename SetSign = MakeSigned>
-struct VectorIntegerExtOpPairwise {
- auto operator()(u128 c) const
- {
- using VectorResult = NativeVectorType<128 / VectorSize, VectorSize, SetSign>;
- using VectorInput = NativeVectorType<128 / (VectorSize * 2), VectorSize * 2, SetSign>;
- auto vector = bit_cast<VectorInput>(c);
- VectorResult result;
- Op op;
-
- // FIXME: Find a way to not loop here
- for (size_t i = 0; i < VectorSize; ++i) {
- result[i] = op(vector[i * 2], vector[(i * 2) + 1]);
- }
-
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 8:
- return "vec(16x8).ext_op_pairwise(8x16)"sv;
- case 4:
- return "vec(32x4).ext_op_pairwise(16x8)"sv;
- case 2:
- return "vec(64x2).ext_op_pairwise(32x4)"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-enum class VectorExt {
- High,
- Low,
-};
-
-template<size_t VectorSize, VectorExt Mode, template<typename> typename SetSign = MakeSigned>
-struct VectorIntegerExt {
- auto operator()(u128 c) const
- {
- using VectorResult = NativeVectorType<128 / VectorSize, VectorSize, SetSign>;
- using VectorInput = NativeVectorType<128 / (VectorSize * 2), VectorSize * 2, SetSign>;
- auto vector = bit_cast<VectorInput>(c);
- VectorResult result;
-
- // FIXME: Find a way to not loop here
- for (size_t i = 0; i < VectorSize; ++i) {
- if constexpr (Mode == VectorExt::High)
- result[i] = vector[VectorSize + i];
- else if constexpr (Mode == VectorExt::Low)
- result[i] = vector[i];
- else
- VERIFY_NOT_REACHED();
- }
-
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 8:
- return "vec(16x8).ext(8x16)"sv;
- case 4:
- return "vec(32x4).ext(16x8)"sv;
- case 2:
- return "vec(64x2).ext(32x4)"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, typename Op, VectorExt Mode, template<typename> typename SetSign = MakeSigned>
-struct VectorIntegerExtOp {
- auto operator()(u128 lhs, u128 rhs) const
- {
- using VectorResult = NativeVectorType<128 / VectorSize, VectorSize, SetSign>;
- using VectorInput = NativeVectorType<128 / (VectorSize * 2), VectorSize * 2, SetSign>;
- auto first = bit_cast<VectorInput>(lhs);
- auto second = bit_cast<VectorInput>(rhs);
- VectorResult result;
- Op op;
-
- using ResultType = SetSign<NativeIntegralType<128 / VectorSize>>;
- // FIXME: Find a way to not loop here
- for (size_t i = 0; i < VectorSize; ++i) {
- if constexpr (Mode == VectorExt::High) {
- ResultType a = first[VectorSize + i];
- ResultType b = second[VectorSize + i];
- result[i] = op(a, b);
- } else if constexpr (Mode == VectorExt::Low) {
- ResultType a = first[i];
- ResultType b = second[i];
- result[i] = op(a, b);
- } else
- VERIFY_NOT_REACHED();
- }
-
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 8:
- return "vec(16x8).ext_op(8x16)"sv;
- case 4:
- return "vec(32x4).ext_op(16x8)"sv;
- case 2:
- return "vec(64x2).ext_op(32x4)"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, typename Op, template<typename> typename SetSign = MakeSigned>
-struct VectorIntegerBinaryOp {
- auto operator()(u128 lhs, u128 rhs) const
- {
- using VectorType = NativeVectorType<128 / VectorSize, VectorSize, SetSign>;
- auto first = bit_cast<VectorType>(lhs);
- auto second = bit_cast<VectorType>(rhs);
- VectorType result;
- Op op;
-
- // FIXME: Find a way to not loop here
- for (size_t i = 0; i < VectorSize; ++i) {
- result[i] = op(first[i], second[i]);
- }
-
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16).binary_op"sv;
- case 8:
- return "vec(16x8).binary_op"sv;
- case 4:
- return "vec(32x4).binary_op"sv;
- case 2:
- return "vec(64x2).binary_op"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize>
-struct VectorBitmask {
- auto operator()(u128 lhs) const
- {
- using VectorType = NativeVectorType<128 / VectorSize, VectorSize, MakeSigned>;
- auto value = bit_cast<VectorType>(lhs);
- u32 result = 0;
-
- for (size_t i = 0; i < VectorSize; ++i)
- result |= static_cast<u32>(value[i] < 0) << i;
-
- return result;
- }
-
- static StringView name() { return "bitmask"sv; }
-};
-
-template<size_t VectorSize>
-struct VectorMultiplyAdd {
- auto operator()(u128 a1, u128 a2, u128 a3) const
- {
- using VectorInput = NativeFloatingVectorType<128 / VectorSize, VectorSize, NativeFloatingType<128 / VectorSize>>;
- auto a = bit_cast<VectorInput>(a1);
- auto b = bit_cast<VectorInput>(a2);
- auto c = bit_cast<VectorInput>(a3);
- // Spec talks about rounding and such, but v8's arm impl just does vmul + vadd with nothing in between.
- return bit_cast<u128>(a * b + c);
- }
-};
-
-template<size_t VectorSize>
-struct VectorMultiplySub {
- auto operator()(u128 a1, u128 a2, u128 a3) const
- {
- using VectorInput = NativeFloatingVectorType<128 / VectorSize, VectorSize, NativeFloatingType<128 / VectorSize>>;
- auto a = bit_cast<VectorInput>(a1);
- auto b = bit_cast<VectorInput>(a2);
- auto c = bit_cast<VectorInput>(a3);
- // Spec talks about rounding and such, but v8's arm impl just does vmul + vsub with nothing in between.
- return bit_cast<u128>(a * b - c);
- }
-};
-
-template<size_t VectorSize, typename ContinuationOp = Identity>
-struct VectorDotProduct {
- template<typename... ContinuationArgs>
- auto operator()(u128 lhs, u128 rhs, ContinuationArgs&&... args) const
- {
- using VectorInput = NativeVectorType<128 / (VectorSize * 2), VectorSize * 2, MakeSigned>;
- using VectorResult = NativeVectorType<128 / VectorSize, VectorSize, MakeSigned>;
- auto v1 = bit_cast<VectorInput>(lhs);
- auto v2 = bit_cast<VectorInput>(rhs);
- VectorResult result;
-
- using ResultType = MakeUnsigned<NativeIntegralType<128 / VectorSize>>;
- for (size_t i = 0; i < VectorSize; ++i) {
- ResultType low = v1[i * 2] * v2[i * 2];
- ResultType high = v1[(i * 2) + 1] * v2[(i * 2) + 1];
- result[i] = low + high;
- }
-
- return ContinuationOp { forward<ContinuationArgs>(args)... }(bit_cast<u128>(result));
- }
-
- static StringView name() { return "dot"sv; }
-};
-
-struct VectorRelaxedDotI8I7AddS {
- auto operator()(u128 lhs, u128 rhs, u128 acc) const
- {
- using VectorInput = Native128ByteVectorOf<i8, MakeSigned>;
- using VectorResult = Native128ByteVectorOf<i32, MakeSigned>;
- using VectorAcc = Native128ByteVectorOf<i32, MakeSigned>;
-
- auto v1 = bit_cast<VectorInput>(lhs);
- auto v2 = bit_cast<VectorInput>(rhs);
- auto accumulator = bit_cast<VectorAcc>(acc);
- VectorResult result {};
-
- // Each i32 lane is the sum of 4 i8*i8 products, plus accumulator
- for (size_t lane = 0; lane < 4; ++lane) {
- i32 sum = 0;
- for (size_t i = 0; i < 4; ++i) {
- auto const idx = lane * 4 + i;
- sum += static_cast<i32>(v1[idx]) * static_cast<i32>(v2[idx]);
- }
- result[lane] = sum + accumulator[lane];
- }
-
- return bit_cast<u128>(result);
- }
-
- static StringView name() { return "i32x4.relaxed_dot_i8x16_i7x16_add_s"sv; }
-};
-
-template<size_t VectorSize, typename Element>
-struct VectorNarrow {
- auto operator()(u128 lhs, u128 rhs) const
- {
- using VectorInput = NativeVectorType<128 / (VectorSize / 2), VectorSize / 2, MakeSigned>;
- using VectorResult = NativeVectorType<128 / VectorSize, VectorSize, MakeUnsigned>;
- auto v1 = bit_cast<VectorInput>(lhs);
- auto v2 = bit_cast<VectorInput>(rhs);
- VectorResult result;
-
- for (size_t i = 0; i < (VectorSize / 2); ++i) {
- if (v1[i] <= NumericLimits<Element>::min())
- result[i] = NumericLimits<Element>::min();
- else if (v1[i] >= NumericLimits<Element>::max())
- result[i] = NumericLimits<Element>::max();
- else
- result[i] = v1[i];
- }
- for (size_t i = 0; i < (VectorSize / 2); ++i) {
- if (v2[i] <= NumericLimits<Element>::min())
- result[i + VectorSize / 2] = NumericLimits<Element>::min();
- else if (v2[i] >= NumericLimits<Element>::max())
- result[i + VectorSize / 2] = NumericLimits<Element>::max();
- else
- result[i + VectorSize / 2] = v2[i];
- }
-
- return bit_cast<u128>(result);
- }
-
- static StringView name() { return "narrow"sv; }
-};
-
-template<size_t VectorSize, typename Op, template<typename> typename SetSign = MakeSigned>
-struct VectorIntegerUnaryOp {
- auto operator()(u128 lhs) const
- {
- using VectorType = NativeVectorType<128 / VectorSize, VectorSize, SetSign>;
- auto value = bit_cast<VectorType>(lhs);
- VectorType result;
- Op op;
-
- // FIXME: Find a way to not loop here
- for (size_t i = 0; i < VectorSize; ++i) {
- result[i] = op(value[i]);
- }
-
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 16:
- return "vec(8x16).unary_op"sv;
- case 8:
- return "vec(16x8).unary_op"sv;
- case 4:
- return "vec(32x4).unary_op"sv;
- case 2:
- return "vec(64x2).unary_op"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, typename Op>
-struct VectorFloatBinaryOp {
- auto operator()(u128 lhs, u128 rhs) const
- {
- using VectorType = NativeFloatingVectorType<128, VectorSize, NativeFloatingType<128 / VectorSize>>;
- auto first = bit_cast<VectorType>(lhs);
- auto second = bit_cast<VectorType>(rhs);
- VectorType result;
- Op op;
- for (size_t i = 0; i < VectorSize; ++i) {
- result[i] = op(first[i], second[i]);
- }
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 4:
- return "vecf(32x4).binary_op"sv;
- case 2:
- return "vecf(64x2).binary_op"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t VectorSize, typename Op>
-struct VectorFloatUnaryOp {
- auto operator()(u128 lhs) const
- {
- using VectorType = NativeFloatingVectorType<128, VectorSize, NativeFloatingType<128 / VectorSize>>;
- auto value = bit_cast<VectorType>(lhs);
- VectorType result;
- Op op;
- for (size_t i = 0; i < VectorSize; ++i) {
- result[i] = op(value[i]);
- }
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (VectorSize) {
- case 4:
- return "vecf(32x4).unary_op"sv;
- case 2:
- return "vecf(64x2).unary_op"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-template<size_t ResultSize, size_t InputSize, typename ResultType, typename InputType, typename Op>
-struct VectorConvertOp {
- auto operator()(u128 lhs) const
- {
- using VectorInput = NativeVectorType<128 / InputSize, InputSize, MakeUnsigned>;
- using VectorResult = NativeVectorType<128 / ResultSize, ResultSize, MakeUnsigned>;
- auto value = bit_cast<VectorInput>(lhs);
- VectorResult result;
- Op op;
- auto size = min(InputSize, ResultSize);
- for (size_t i = 0; i < size; ++i)
- result[i] = bit_cast<ResultType>(op(bit_cast<InputType>(value[i])));
- // FIXME: We shouldn't need this, but the auto-vectorizer sometimes doesn't see that we
- // need to pad with zeroes when InputSize < ResultSize (i.e. converting from f64x2 -> f32x4).
- // So we put this here to make sure. Putting [[clang::optnone]] over this function resolves
- // this issue, but that would be pretty unacceptable...
- if constexpr (InputSize < ResultSize) {
- constexpr size_t remaining = ResultSize - InputSize;
- for (size_t i = 0; i < remaining; ++i)
- result[i + InputSize] = 0;
- }
- return bit_cast<u128>(result);
- }
-
- static StringView name()
- {
- switch (ResultSize) {
- case 4:
- return "vec(32x4).cvt_op"sv;
- case 2:
- return "vec(64x2).cvt_op"sv;
- default:
- VERIFY_NOT_REACHED();
- }
- }
-};
-
-struct Floor {
- template<typename Lhs>
- auto operator()(Lhs lhs) const
- {
- if (isnan(lhs))
- return AK::NaN<Lhs>;
-
- if constexpr (IsSame<Lhs, float>)
- return floorf(lhs);
- else if constexpr (IsSame<Lhs, double>)
- return floor(lhs);
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "floor"sv; }
-};
-
-struct Truncate {
- template<typename Lhs>
- auto operator()(Lhs lhs) const
- {
- if (isnan(lhs))
- return AK::NaN<Lhs>;
-
- if constexpr (IsSame<Lhs, float>)
- return truncf(lhs);
- else if constexpr (IsSame<Lhs, double>)
- return trunc(lhs);
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "truncate"sv; }
-};
-
-struct NearbyIntegral {
- template<typename Lhs>
- auto operator()(Lhs lhs) const
- {
- if constexpr (IsSame<Lhs, float>)
- return nearbyintf(lhs);
- else if constexpr (IsSame<Lhs, double>)
- return nearbyint(lhs);
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "round"sv; }
-};
-
-struct SquareRoot {
- template<typename Lhs>
- auto operator()(Lhs lhs) const
- {
- if constexpr (IsSame<Lhs, float>)
- return sqrtf(lhs);
- else if constexpr (IsSame<Lhs, double>)
- return sqrt(lhs);
- else
- VERIFY_NOT_REACHED();
- }
-
- static StringView name() { return "sqrt"sv; }
-};
-
-template<typename Result>
-struct Wrap {
- template<typename Lhs>
- Result operator()(Lhs lhs) const
- {
- return static_cast<MakeUnsigned<Result>>(bit_cast<MakeUnsigned<Lhs>>(lhs));
- }
-
- static StringView name() { return "wrap"sv; }
-};
-
-template<typename ResultT>
-struct CheckedTruncate {
- template<typename Lhs>
- AK::ErrorOr<ResultT, StringView> operator()(Lhs lhs) const
- {
- if (isnan(lhs) || isinf(lhs)) // "undefined", let's just trap.
- return "Truncation undefined behavior"sv;
-
- Lhs truncated;
- if constexpr (IsSame<float, Lhs>)
- truncated = truncf(lhs);
- else if constexpr (IsSame<double, Lhs>)
- truncated = trunc(lhs);
- else
- VERIFY_NOT_REACHED();
-
- // FIXME: This function assumes that all values of ResultT are representable in Lhs
- // the assumption comes from the fact that this was used exclusively by LibJS,
- // which only considers values that are all representable in 'double'.
- if (!AK::is_within_range<ResultT>(static_cast<long double>(truncated)))
- return "Truncation out of range"sv;
-
- return static_cast<ResultT>(truncated);
- }
-
- static StringView name() { return "truncate.checked"sv; }
-};
-
-template<typename ResultT>
-struct Extend {
- template<typename Lhs>
- ResultT operator()(Lhs lhs) const
- {
- return lhs;
- }
-
- static StringView name() { return "extend"sv; }
-};
-
-template<typename ResultT>
-struct Convert {
- template<typename Lhs>
- ResultT operator()(Lhs lhs) const
- {
- auto interpretation = bit_cast<Lhs>(lhs);
- return static_cast<ResultT>(interpretation);
- }
-
- static StringView name() { return "convert"sv; }
-};
-
-template<typename ResultT>
-struct Reinterpret {
- template<typename Lhs>
- ResultT operator()(Lhs lhs) const
- {
- return bit_cast<ResultT>(lhs);
- }
-
- static StringView name() { return "reinterpret"sv; }
-};
-
-struct Promote {
- double operator()(float lhs) const
- {
- if (isnan(lhs))
- return nan(""); // FIXME: Ensure canonical NaN remains canonical
- return static_cast<double>(lhs);
- }
-
- static StringView name() { return "promote"sv; }
-};
-
-struct Demote {
- float operator()(double lhs) const
- {
- if (isnan(lhs))
- return nanf(""); // FIXME: Ensure canonical NaN remains canonical
-
- if (isinf(lhs))
- return copysignf(__builtin_huge_valf(), lhs);
-
- return static_cast<float>(lhs);
- }
-
- static StringView name() { return "demote"sv; }
-};
-
-template<typename InitialType>
-struct SignExtend {
- template<typename Lhs>
- Lhs operator()(Lhs lhs) const
- {
- auto unsigned_representation = bit_cast<MakeUnsigned<Lhs>>(lhs);
- auto truncated_unsigned_representation = static_cast<MakeUnsigned<InitialType>>(unsigned_representation);
- auto initial_value = bit_cast<InitialType>(truncated_unsigned_representation);
- return static_cast<Lhs>(initial_value);
- }
-
- static StringView name() { return "extend"sv; }
-};
-
-template<typename ResultT>
-struct SaturatingTruncate {
- template<typename Lhs>
- ResultT operator()(Lhs lhs) const
- {
- if (isnan(lhs))
- return 0;
-
- if (isinf(lhs)) {
- if (lhs < 0)
- return NumericLimits<ResultT>::min();
- return NumericLimits<ResultT>::max();
- }
-
- // FIXME: This assumes that all values in ResultT are representable in 'double'.
- // that assumption is not correct, which makes this function yield incorrect values
- // for 'edge' values of type i64.
- constexpr auto convert = []<typename ConvertT>(ConvertT truncated_value) {
- if (truncated_value < NumericLimits<ResultT>::min())
- return NumericLimits<ResultT>::min();
- if constexpr (IsSame<ConvertT, float>) {
- if (truncated_value >= static_cast<ConvertT>(NumericLimits<ResultT>::max()))
- return NumericLimits<ResultT>::max();
- } else {
- if (static_cast<double>(truncated_value) >= static_cast<double>(NumericLimits<ResultT>::max()))
- return NumericLimits<ResultT>::max();
- }
- return static_cast<ResultT>(truncated_value);
- };
-
- if constexpr (IsSame<Lhs, float>)
- return convert(truncf(lhs));
- else
- return convert(trunc(lhs));
- }
-
- static StringView name() { return "truncate.saturating"sv; }
-};
-
-template<typename ResultT, typename Op>
-struct SaturatingOp {
- template<typename Lhs, typename Rhs>
- ResultT operator()(Lhs lhs, Rhs rhs) const
- {
- Op op;
-
- double result = op(lhs, rhs);
-
- if (result <= static_cast<double>(NumericLimits<ResultT>::min())) {
- return NumericLimits<ResultT>::min();
- }
-
- if (result >= static_cast<double>(NumericLimits<ResultT>::max())) {
- return NumericLimits<ResultT>::max();
- }
-
- return static_cast<ResultT>(result);
- }
-
- static StringView name() { return "saturating_op"sv; }
-};
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/Validator.cpp b/Libraries/LibWasm/AbstractMachine/Validator.cpp
deleted file mode 100644
index 2e76899d3f5..00000000000
--- a/Libraries/LibWasm/AbstractMachine/Validator.cpp
+++ /dev/null
@@ -1,5294 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/GenericShorthands.h>
-#include <AK/HashTable.h>
-#include <AK/SourceLocation.h>
-#include <AK/TemporaryChange.h>
-#include <AK/Try.h>
-#include <LibWasm/AbstractMachine/Validator.h>
-#include <LibWasm/Printer/Printer.h>
-
-namespace Wasm {
-
-ErrorOr<void, ValidationError> Validator::validate(Module& module)
-{
- // Pre-emptively make invalid. The module will be set to `Valid` at the end
- // of validation.
- module.set_validation_status(Module::ValidationStatus::Invalid, {});
-
- // Note: The spec performs this after populating the context, but there's no real reason to do so,
- // as this has no dependency.
- HashTable<StringView> seen_export_names;
- for (auto& export_ : module.export_section().entries())
- if (seen_export_names.try_set(export_.name()).release_value_but_fixme_should_propagate_errors() != AK::HashSetResult::InsertedNewEntry)
- return Errors::duplicate_export_name(export_.name());
-
- m_context = {};
-
- m_context.types.extend(module.type_section().types());
- m_context.data_count = module.data_count_section().count();
-
- // https://webassembly.github.io/spec/core/valid/modules.html#types
- // Intern the type section's recursive groups as defined types ("the defined type sequence
- // dt* is of the form roll*_x(rectype)") before anything else can refer to them; the rest of
- // the sub type validation rule runs in validate(TypeSection const&) below.
- {
- auto canonical_types = TRY(canonicalize_module_types(module.type_section()));
- m_context.canonical_types.extend(canonical_types);
- module.set_canonical_types(move(canonical_types));
- }
- TRY(validate(module.type_section()));
-
- for (auto& import_ : module.import_section().imports()) {
- TRY(import_.description().visit(
- [&](TypeIndex const& index) -> ErrorOr<void, ValidationError> {
- if (m_context.types.size() <= index.value())
- return Errors::invalid("TypeIndex"sv);
-
- auto const& type = m_context.types[index.value()];
- if (!type.is_function())
- return Errors::invalid("function import type"sv);
-
- m_context.functions.append(type.function());
- m_context.function_type_indices.append(index);
- m_context.imported_function_count++;
- return {};
- },
- [&](FunctionType const& type) -> ErrorOr<void, ValidationError> {
- m_context.functions.append(type);
- m_context.function_type_indices.append({});
- m_context.imported_function_count++;
- return {};
- },
- [&](TableType const& type) -> ErrorOr<void, ValidationError> {
- m_context.tables.append(type);
- return {};
- },
- [&](MemoryType const& type) -> ErrorOr<void, ValidationError> {
- m_context.memories.append(type);
- return {};
- },
- [&](GlobalType const& type) -> ErrorOr<void, ValidationError> {
- m_globals_without_internal_globals.append(type);
- m_context.globals.append(type);
- return {};
- },
- [&](TagType const&) -> ErrorOr<void, ValidationError> {
- m_context.tags.append(import_.description().get<TagType>());
- return {};
- }));
- }
-
- if (module.code_section().functions().size() != module.function_section().types().size())
- return Errors::invalid("FunctionSection"sv);
-
- m_context.functions.ensure_capacity(module.function_section().types().size() + m_context.functions.size());
- m_context.function_type_indices.ensure_capacity(module.function_section().types().size() + m_context.function_type_indices.size());
- for (auto& index : module.function_section().types()) {
- if (m_context.types.size() <= index.value() || !m_context.types[index.value()].is_function())
- return Errors::invalid("TypeIndex"sv);
- m_context.functions.append(m_context.types[index.value()].function());
- m_context.function_type_indices.append(index);
- }
-
- m_context.tables.ensure_capacity(m_context.tables.size() + module.table_section().tables().size());
- for (auto& table : module.table_section().tables())
- m_context.tables.append(table.type());
-
- m_context.memories.ensure_capacity(m_context.memories.size() + module.memory_section().memories().size());
- for (auto& memory : module.memory_section().memories())
- m_context.memories.append(memory.type());
-
- m_context.globals.ensure_capacity(m_context.globals.size() + module.global_section().entries().size());
- for (auto& global : module.global_section().entries())
- m_context.globals.append(global.type());
-
- m_context.elements.ensure_capacity(module.element_section().segments().size());
- for (auto& segment : module.element_section().segments())
- m_context.elements.append(segment.type);
-
- m_context.datas.resize(module.data_section().data().size());
-
- m_context.tags.ensure_capacity(m_context.tags.size() + module.tag_section().tags().size());
- for (auto& tag : module.tag_section().tags())
- m_context.tags.append(TagType(tag.type(), tag.flags()));
-
- // We need to build the set of declared functions to check that `ref.func` uses a specific set of predetermined functions, found in:
- // - Element initializer expressions
- // - Global initializer expressions
- // - Exports
- auto scan_expression_for_function_indices = [&](auto& expression) {
- for (auto& instruction : expression.instructions()) {
- if (instruction.opcode() == Instructions::ref_func) {
- auto index = instruction.arguments().template get<FunctionIndex>();
- m_context.references->tree.insert(index.value(), index);
- }
- }
- };
- for (auto& export_ : module.export_section().entries()) {
- if (!export_.description().has<FunctionIndex>())
- continue;
- auto index = export_.description().get<FunctionIndex>();
- m_context.references->tree.insert(index.value(), index);
- }
- for (auto& segment : module.element_section().segments()) {
- for (auto& expression : segment.init)
- scan_expression_for_function_indices(expression);
- }
- for (auto& segment : module.global_section().entries())
- scan_expression_for_function_indices(segment.expression());
- for (auto& table : module.table_section().tables())
- scan_expression_for_function_indices(table.initializer());
-
- TRY(validate(module.import_section()));
- TRY(validate(module.export_section()));
- TRY(validate(module.start_section()));
- TRY(validate(module.data_section()));
- TRY(validate(module.element_section()));
- TRY(validate(module.global_section()));
- TRY(validate(module.memory_section()));
- TRY(validate(module.table_section()));
- TRY(validate(module.code_section()));
- TRY(validate(module.tag_section()));
-
- for (auto& entry : module.code_section().functions())
- module.set_minimum_call_record_allocation_size(max(entry.func().body().compiled_instructions.max_call_rec_size, module.minimum_call_record_allocation_size()));
-
- module.set_validation_status(Module::ValidationStatus::Valid, {});
- return {};
-}
-
-void compile_module_to_native(Module& module)
-{
- auto cache_config = module.take_cranelift_cache_config();
- auto stats = module.take_compile_stats();
-
- bool installing = false;
- bool capturing = false;
-
- if (cache_config.has_value()) {
- auto hash = ReadonlyBytes { cache_config->wasm_hash.data(), 32 };
- if (!cache_config->existing_blob.is_empty())
- installing = try_install_cranelift_cache_blob(hash, cache_config->existing_blob.bytes());
- if (!installing && cache_config->on_compiled) {
- begin_cranelift_cache_capture();
- capturing = true;
- }
- }
-
- ScopeGuard cleanup = [&] {
- auto cranelift_start = MonotonicTime::now();
- flush_cranelift_batch();
- auto cranelift_duration = MonotonicTime::now() - cranelift_start;
-
- if (installing)
- abort_cranelift_cache_install();
-
- size_t produced_blob_size = 0;
- if (capturing) {
- auto hash = ReadonlyBytes { cache_config->wasm_hash.data(), 32 };
- if (auto blob = serialize_cranelift_cache_blob(hash); blob.has_value() && cache_config->on_compiled) {
- produced_blob_size = blob->size();
- cache_config->on_compiled(blob.release_value());
- } else {
- abort_cranelift_cache_capture();
- }
- }
-
- if (stats.has_value()) {
- stats->cranelift_time = cranelift_duration;
- stats->cranelift_blob_size_bytes = produced_blob_size;
- stats->cache_hit = installing;
- size_t count = 0;
- size_t tier_up_functions = 0;
- size_t tier_up_checkpoints = 0;
- for (auto& entry : module.code_section().functions()) {
- auto const& ci = entry.func().body().compiled_instructions;
- if (ci.cranelift_compiled)
- ++count;
- if (ci.has_tier_up_checkpoints) {
- ++tier_up_functions;
- for (auto const& dispatch : ci.dispatches) {
- if (dispatch.instruction->opcode() == Instructions::synthetic_tier_up)
- ++tier_up_checkpoints;
- }
- }
- }
- stats->function_count = count;
- stats->tier_up_function_count = tier_up_functions;
- stats->tier_up_checkpoint_count = tier_up_checkpoints;
- record_module_stats(stats.release_value());
- }
-
- set_cranelift_active_function_index(NumericLimits<u32>::max());
- };
-
- size_t imported_function_count = 0;
- for (auto& import_ : module.import_section().imports()) {
- import_.description().visit(
- [&](TypeIndex const& type_index) {
- auto& types = module.type_section().types();
- if (type_index.value() < types.size() && types[type_index.value()].is_function())
- ++imported_function_count;
- },
- [&](FunctionType const&) { ++imported_function_count; },
- [&](auto const&) { });
- }
-
- size_t function_index = imported_function_count;
- for (auto& entry : module.code_section().functions()) {
- auto& compiled = entry.func().body().compiled_instructions;
- set_cranelift_active_function_index(static_cast<u32>(function_index++));
- if (compiled.cranelift_eligible)
- try_cranelift_compile(compiled, compiled.cranelift_result_arity);
- }
-}
-
-ErrorOr<void, ValidationError> ensure_cranelift_compiled(Module& module)
-{
- if (!module.try_begin_cranelift_compilation()) {
- module.wait_for_cranelift_compilation();
- return {};
- }
-
- if (module.validation_status() == Module::ValidationStatus::Invalid) {
- module.finish_cranelift_compilation();
- return ValidationError { module.validation_error() };
- }
-
- compile_module_to_native(module);
- module.finish_cranelift_compilation();
- return {};
-}
-
-void start_cranelift_compilation(Module& module)
-{
- (void)ensure_cranelift_compiled(module);
-}
-
-ErrorOr<void, ValidationError> Validator::validate(ImportSection const& section)
-{
- for (auto& import_ : section.imports())
- TRY(import_.description().visit([&](auto& entry) { return validate(entry); }));
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(ExportSection const& section)
-{
- for (auto& export_ : section.entries())
- TRY(export_.description().visit([&](auto& entry) -> ErrorOr<void, ValidationError> { TRY(validate(entry)); return {}; }));
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(StartSection const& section)
-{
- if (!section.function().has_value())
- return {};
- TRY(validate(section.function()->index()));
- FunctionType const& type = m_context.functions[section.function()->index().value()];
- if (!type.parameters().is_empty() || !type.results().is_empty())
- return Errors::invalid("start function signature"sv);
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(DataSection const& section)
-{
- if (m_context.data_count.has_value() && section.data().size() != m_context.data_count)
- return Errors::invalid("data count does not match segment count"sv);
- for (auto& entry : section.data()) {
- TRY(entry.value().visit(
- [](DataSection::Data::Passive const&) { return ErrorOr<void, ValidationError> {}; },
- [&](DataSection::Data::Active const& active) -> ErrorOr<void, ValidationError> {
- auto memory = TRY(validate(active.index));
- auto const at = memory.limits().address_value_type();
-
- auto expression_result = TRY(validate(active.offset, { at }));
-
- if (!expression_result.is_constant)
- return Errors::invalid("active data initializer"sv);
-
- if (expression_result.result_types.size() != 1 || !expression_result.result_types.first().is_of_kind(at.kind()))
- return Errors::invalid("active data initializer type"sv, at, expression_result.result_types);
-
- return {};
- }));
- }
-
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(ElementSection const& section)
-{
- for (auto& segment : section.segments()) {
- // https://webassembly.github.io/spec/core/valid/modules.html#element-segments
- // - The reference type elemtype is valid.
- TRY(validate(segment.type));
- if (!segment.type.is_reference())
- return Errors::invalid("element reference type"sv);
-
- TRY(segment.mode.visit(
- [](ElementSection::Declarative const&) -> ErrorOr<void, ValidationError> { return {}; },
- [](ElementSection::Passive const&) -> ErrorOr<void, ValidationError> { return {}; },
- [&](ElementSection::Active const& active) -> ErrorOr<void, ValidationError> {
- // https://webassembly.github.io/spec/core/valid/modules.html#element-segments
- TRY(validate(active.index));
- auto table = m_context.tables[active.index.value()];
- if (!matches_reference_type(segment.type, table.element_type(), m_context.type_context()))
- return Errors::invalid("active element reference type"sv);
- auto at = table.limits().address_value_type();
- auto expression_result = TRY(validate(active.expression, { at }));
- if (!expression_result.is_constant)
- return Errors::invalid("active element initializer"sv);
- if (expression_result.result_types.size() != 1 || !expression_result.result_types.first().is_of_kind(at.kind()))
- return Errors::invalid("active element initializer type"sv, at, expression_result.result_types);
- return {};
- }));
-
- for (auto& expression : segment.init) {
- if (expression.instructions().is_empty())
- continue;
- // https://webassembly.github.io/spec/core/valid/modules.html#element-segments
- auto result = TRY(validate(expression, { segment.type }));
- if (!result.is_constant)
- return Errors::invalid("element initializer"sv);
- if (result.result_types.size() != 1)
- return Errors::invalid("element initializer type"sv, segment.type, result.result_types);
- }
- }
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(GlobalSection const& section)
-{
- // https://webassembly.github.io/spec/core/valid/modules.html#modules
- auto section_validator = fork();
- section_validator.m_context.globals = m_globals_without_internal_globals;
-
- for (auto& entry : section.entries()) {
- auto& type = entry.type();
- TRY(section_validator.validate(type));
- auto expression_result = TRY(section_validator.validate(entry.expression(), { type.type() }));
- if (!expression_result.is_constant)
- return Errors::invalid("global variable initializer"sv);
- if (expression_result.result_types.size() != 1)
- return Errors::invalid("global variable initializer type"sv, ValueType(ValueType::I32), expression_result.result_types);
- section_validator.m_context.globals.append(type);
- }
-
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(MemorySection const& section)
-{
- for (auto& entry : section.memories())
- TRY(validate(entry.type()));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/modules.html#tables
-ErrorOr<void, ValidationError> Validator::validate(TableSection const& section)
-{
- auto section_validator = fork();
- section_validator.m_context.globals = m_globals_without_internal_globals;
-
- for (auto& entry : section.tables()) {
- TRY(section_validator.validate(entry.type()));
- auto expression_result = TRY(section_validator.validate(entry.initializer(), { entry.type().element_type() }));
- if (!expression_result.is_constant)
- return Errors::invalid("table initializer"sv);
- if (expression_result.result_types.size() != 1)
- return Errors::invalid("table initializer type"sv, entry.type().element_type(), expression_result.result_types);
- }
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(CodeSection const& section)
-{
- Vector<CodeSection::Func const*> callee_bodies;
- callee_bodies.resize(m_context.imported_function_count + section.functions().size());
-
- size_t index = m_context.imported_function_count;
- for (auto& entry : section.functions()) {
- auto function_index = index++;
- VERIFY(function_index <= NumericLimits<u32>::max());
- TRY(validate(FunctionIndex { static_cast<u32>(function_index) }));
- auto& function_type = m_context.functions[function_index];
- auto& function = entry.func();
-
- auto function_validator = fork();
- function_validator.m_context.locals = {};
- function_validator.m_context.locals.extend(function_type.parameters());
- function_validator.m_context.current_function_parameter_count = function_type.parameters().size();
- for (auto& local : function.locals()) {
- // https://webassembly.github.io/spec/core/valid/modules.html#functions
- // The locals' value types must be valid (in particular, type uses must exist).
- TRY(function_validator.validate(local.type()));
- for (size_t i = 0; i < local.n(); ++i)
- function_validator.m_context.locals.append(local.type());
- }
-
- // https://webassembly.github.io/spec/core/valid/modules.html#functions
- function_validator.m_local_initialized.clear_with_capacity();
- function_validator.m_local_init_log.clear_with_capacity();
- for (auto& parameter : function_type.parameters()) {
- (void)parameter;
- function_validator.m_local_initialized.append(true);
- }
- for (auto& local : function.locals()) {
- for (size_t i = 0; i < local.n(); ++i)
- function_validator.m_local_initialized.append(local.type().is_defaultable());
- }
-
- function_validator.push_frame(Frame { function_type, FrameKind::Function, (size_t)0 });
-
- auto results = TRY(function_validator.validate(function.body(), function_type.results(), callee_bodies.span(), function_index));
- if (results.result_types.size() != function_type.results().size())
- return Errors::invalid("function result"sv, function_type.results(), results.result_types);
-
- callee_bodies[function_index] = &function;
-
- if (function.body().compiled_instructions.max_call_rec_size != 0) {
- size_t max_callee_locals = 0;
- for (auto& insn : function.body().instructions()) {
- if (!first_is_one_of(insn.opcode(), Instructions::call, Instructions::synthetic_call_with_record_0, Instructions::synthetic_call_with_record_1))
- continue;
- auto callee_index = insn.arguments().template get<FunctionIndex>();
- if (callee_index.value() - m_context.imported_function_count < section.functions().size())
- max_callee_locals = max(max_callee_locals, section.functions()[callee_index.value() - m_context.imported_function_count].func().total_local_count());
- }
-
- function.body().compiled_instructions.max_call_rec_size += max_callee_locals;
- }
- }
-
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(TagSection const& section)
-{
- for (auto& entry : section.tags())
- TRY(validate(entry));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/types.html#recursive-types
-ErrorOr<void, ValidationError> Validator::validate(TypeSection const& section)
-{
- for (size_t type_index = 0; type_index < section.types().size(); ++type_index)
- TRY(validate(section.types()[type_index], type_index));
-
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(TableType const& type)
-{
- TRY(validate(type.element_type()));
- Optional<u64> bound = type.limits().address_type() == AddressType::I64 ? Optional<u64> {} : (1ull << 32) - 1;
- return validate(type.limits(), bound);
-}
-
-ErrorOr<void, ValidationError> Validator::validate(MemoryType const& type)
-{
- u64 bound = type.limits().address_type() == AddressType::I64 ? 1ull << 48 : Constants::wasm32_max_pages;
- return validate(type.limits(), bound);
-}
-
-ErrorOr<void, ValidationError> Validator::validate(Wasm::TagType const& tag_type)
-{
- // The function type t1^n -> t2^m must be valid
- TRY(validate(tag_type.type()));
- auto& type = m_context.types[tag_type.type().value()];
- if (!type.is_function())
- return Errors::invalid("TagType"sv);
-
- auto& func = type.function();
-
- // The type sequence t2^m must be empty
- if (!func.results().is_empty())
- return Errors::invalid("TagType"sv);
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(ValueType const& type)
-{
- if (type.is_typeuse()) {
- TRY(validate(type.unsafe_typeindex()));
- }
-
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/types.html#recursive-types
-ErrorOr<void, ValidationError> Validator::validate(TypeSection::Type const& type, size_t this_type_index)
-{
- // - The length of x* is less than or equal to 1.
- if (type.supertypes().size() > 1)
- return Errors::invalid("supertype count, only a single supertype is allowed"sv);
-
- // - For all x in x*:
- for (auto supertype_index : type.supertypes()) {
- // - The index x is less than x0.
- if (supertype_index.value() >= this_type_index)
- return Errors::invalid("supertype index, must precede the subtype"sv);
-
- // - The type C.types[x] exists.
- TRY(validate(supertype_index));
-
- // - The sub type unroll(C.types[x]) is of the form (sub y* comptype').
- auto const& supertype = m_context.types[supertype_index.value()];
- if (supertype.is_final())
- return Errors::invalid("supertype, must not be final"sv);
-
- // - The composite type comptype matches the composite type comptype'.
- auto const* defined_type = m_context.canonical_types[this_type_index];
- auto const* defined_supertype = m_context.canonical_types[supertype_index.value()];
- if (!matches_composite_type(defined_type->expansion(), defined_supertype->expansion(), TypeContext {}))
- return Errors::invalid("subtype, composite type must match its declared supertype"sv);
- }
-
- return type.description().visit(
- [&](FunctionType const& function) { return validate(function); },
- [&](StructType const& struct_) { return validate(struct_); },
- [&](ArrayType const& array) { return validate(array); });
-}
-
-ErrorOr<void, ValidationError> Validator::validate(FunctionType const& type)
-{
- for (auto param : type.parameters()) {
- TRY(validate(param));
- }
-
- for (auto param : type.results()) {
- TRY(validate(param));
- }
-
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(StructType const& type)
-{
- for (auto field : type.fields()) {
- TRY(validate(field.type()));
- }
-
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(ArrayType const& array)
-{
- return validate(array.type().type());
-}
-
-ErrorOr<void, ValidationError> Validator::validate(GlobalType const& type)
-{
- return validate(type.type());
-}
-
-ErrorOr<FunctionType, ValidationError> Validator::validate(BlockType const& type)
-{
- if (type.kind() == BlockType::Index) {
- TRY(validate(type.type_index()));
-
- if (!m_context.types[type.type_index().value()].is_function())
- return Errors::invalid("BlockType"sv);
-
- return m_context.types[type.type_index().value()].function();
- }
-
- if (type.kind() == BlockType::Type) {
- FunctionType function_type { {}, { type.value_type() } };
- TRY(validate(function_type));
- return function_type;
- }
-
- if (type.kind() == BlockType::Empty)
- return FunctionType { {}, {} };
-
- return Errors::invalid("BlockType"sv);
-}
-
-ErrorOr<void, ValidationError> Validator::validate(Limits const& limits, Optional<u64> bound)
-{
- auto check_bound = [bound](auto value) {
- if (!bound.has_value())
- return true;
- return static_cast<u64>(value) <= bound.value();
- };
-
- if (!check_bound(limits.min()))
- return Errors::out_of_bounds("limit minimum"sv, limits.min(), 0, bound);
-
- if (limits.max().has_value() && (limits.max().value() < limits.min() || !check_bound(*limits.max()))) {
- return Errors::out_of_bounds("limit maximum"sv, limits.max().value(), limits.min(), bound);
- }
-
- return {};
-}
-
-template<u64 opcode>
-ErrorOr<void, ValidationError> Validator::validate_instruction(Instruction const& instruction, Stack&, bool&)
-{
- return Errors::invalid(ByteString::formatted("instruction opcode ({:#x}) (missing validation!)", instruction.opcode().value()));
-}
-
-#define VALIDATE_INSTRUCTION(name) \
- template<> \
- ErrorOr<void, ValidationError> Validator::validate_instruction<Instructions::name.value()>([[maybe_unused]] Instruction const& instruction, [[maybe_unused]] Stack& stack, [[maybe_unused]] bool& is_constant)
-
-// https://webassembly.github.io/spec/core/bikeshed/#-tmathsfhrefsyntax-instr-numericmathsfconstc
-VALIDATE_INSTRUCTION(i32_const)
-{
- is_constant = true;
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_const)
-{
- is_constant = true;
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_const)
-{
- is_constant = true;
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_const)
-{
- is_constant = true;
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#-tmathsfhrefsyntax-unopmathitunop
-VALIDATE_INSTRUCTION(i32_clz)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_ctz)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_popcnt)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_clz)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_ctz)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_popcnt)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_abs)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_neg)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_sqrt)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_ceil)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_floor)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_trunc)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_nearest)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_abs)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_neg)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_sqrt)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_ceil)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_floor)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_trunc)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_nearest)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_extend16_s)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_extend8_s)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_extend32_s)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_extend16_s)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_extend8_s)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::I64));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#-tmathsfhrefsyntax-binopmathitbinop
-VALIDATE_INSTRUCTION(i32_add)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- is_constant = true;
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_sub)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- is_constant = true;
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_mul)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- is_constant = true;
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_divs)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_divu)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_rems)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_remu)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_and)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_or)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_xor)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_shl)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_shrs)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_shru)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_rotl)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_rotr)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_add)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- is_constant = true;
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_sub)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- is_constant = true;
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_mul)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- is_constant = true;
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_divs)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_divu)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_rems)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_remu)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_and)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_or)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_xor)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_shl)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_shrs)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_shru)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_rotl)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_rotr)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_add)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_sub)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_mul)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_div)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_min)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_max)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_copysign)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_add)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_sub)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_mul)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_div)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_min)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_max)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_copysign)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#-tmathsfhrefsyntax-testopmathittestop
-VALIDATE_INSTRUCTION(i32_eqz)
-{
- TRY((stack.take<ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_eqz)
-{
- TRY((stack.take<ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#-tmathsfhrefsyntax-relopmathitrelop
-VALIDATE_INSTRUCTION(i32_eq)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_ne)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_lts)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_ltu)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_gts)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_gtu)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_les)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_leu)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_ges)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_geu)
-{
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_eq)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_ne)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_lts)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_ltu)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_gts)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_gtu)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_les)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_leu)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_ges)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_geu)
-{
- TRY((stack.take<ValueType::I64, ValueType::I64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_eq)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_ne)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_lt)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_le)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_gt)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_ge)
-{
- TRY((stack.take<ValueType::F32, ValueType::F32>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_eq)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_ne)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_lt)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_le)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_gt)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_ge)
-{
- TRY((stack.take<ValueType::F64, ValueType::F64>()));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#-t_2mathsfhrefsyntax-cvtopmathitcvtopmathsf_t_1mathsf_hrefsyntax-sxmathitsx
-VALIDATE_INSTRUCTION(i32_wrap_i64)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_extend_si32)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_extend_ui32)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_sf32)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_uf32)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_sf64)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_uf64)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_sf32)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_uf32)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_sf64)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_uf64)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_sat_f32_s)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_sat_f32_u)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_sat_f64_s)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_trunc_sat_f64_u)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_sat_f32_s)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_sat_f32_u)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_sat_f64_s)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_trunc_sat_f64_u)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_convert_si32)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_convert_ui32)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_convert_si64)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_convert_ui64)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_convert_si32)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_convert_ui32)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_convert_si64)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_convert_ui64)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_demote_f64)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_promote_f32)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_reinterpret_i32)
-{
- TRY(stack.take_and_put<ValueType::I32>(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_reinterpret_i64)
-{
- TRY(stack.take_and_put<ValueType::I64>(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_reinterpret_f32)
-{
- TRY(stack.take_and_put<ValueType::F32>(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_reinterpret_f64)
-{
- TRY(stack.take_and_put<ValueType::F64>(ValueType::I64));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#reference-instructions%E2%91%A2
-
-VALIDATE_INSTRUCTION(ref_null)
-{
- is_constant = true;
- stack.append(instruction.arguments().get<ValueType>());
- return {};
-}
-
-VALIDATE_INSTRUCTION(ref_is_null)
-{
- if (stack.is_empty() || !stack.last().is_reference())
- return Errors::invalid_stack_state(stack, Tuple { "reference" });
-
- TRY(stack.take_last());
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(ref_func)
-{
- auto index = instruction.arguments().get<FunctionIndex>();
- TRY(validate(index));
-
- if (m_context.references->tree.find(index.value()) == nullptr)
- return Errors::invalid("function reference"sv);
-
- is_constant = true;
-
- // https://webassembly.github.io/gc/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-ref-mathsf-ref-func-x
- // ref.func x : [] → [(ref dt)]
- auto type_index = m_context.function_type_indices[index.value()];
- auto ref_type = type_index.has_value() ? ValueType(ValueType::TypeUseReference, *type_index) : ValueType(ValueType::FunctionReference);
- ref_type.set_nullable(false);
- stack.append(ref_type);
-
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#parametric-instructions%E2%91%A2
-VALIDATE_INSTRUCTION(drop)
-{
- TRY(stack.take_last());
- return {};
-}
-
-VALIDATE_INSTRUCTION(select)
-{
- TRY(stack.take<ValueType::I32>());
- auto arg0_type = TRY(stack.take_last());
- auto arg1_type = TRY(stack.take_last());
-
- if (arg0_type != arg1_type || arg0_type.concrete_type.is_reference() || arg1_type.concrete_type.is_reference())
- return Errors::invalid("select argument types"sv, Vector { arg0_type, arg0_type }, Vector { arg0_type, arg1_type });
-
- stack.append(arg0_type.is_known ? arg0_type : arg1_type);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(select_typed)
-{
- auto& required_types = instruction.arguments().get<Vector<ValueType>>();
- if (required_types.size() != 1)
- return Errors::invalid("select types"sv, "exactly one type"sv, required_types);
-
- // https://webassembly.github.io/spec/core/valid/instructions.html#parametric-instructions
- // select t: valid with [t t i32] -> [t] if the value type t is valid; both operands must match the annotated type.
- TRY(validate(required_types.first()));
- TRY(stack.take<ValueType::I32>());
- TRY(stack.take(required_types.first()));
- TRY(stack.take(required_types.first()));
-
- stack.append(required_types.first());
-
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#variable-instructions%E2%91%A2
-// https://webassembly.github.io/spec/core/valid/instructions.html#variable-instructions
-VALIDATE_INSTRUCTION(local_get)
-{
- auto index = TRY(validate(instruction.local_index()));
- if (!m_local_initialized[index.value()])
- return Errors::invalid("local.get of an uninitialized non-defaultable local"sv);
-
- stack.append(m_context.locals[index.value()]);
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#variable-instructions
-VALIDATE_INSTRUCTION(local_set)
-{
- auto index = TRY(validate(instruction.local_index()));
-
- auto& value_type = m_context.locals[index.value()];
- TRY(stack.take(value_type));
- mark_local_initialized(index.value());
-
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#variable-instructions
-// local.tee x is valid with the instruction type t ->_x t; afterwards the local counts as
-// initialized (the init set x).
-VALIDATE_INSTRUCTION(local_tee)
-{
- auto index = TRY(validate(instruction.local_index()));
-
- auto& value_type = m_context.locals[index.value()];
- TRY(stack.take(value_type));
- mark_local_initialized(index.value());
- stack.append(value_type);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(global_get)
-{
- auto index = instruction.arguments().get<GlobalIndex>();
- TRY(validate(index));
-
- auto& global = m_context.globals[index.value()];
-
- is_constant = !global.is_mutable();
- stack.append(global.type());
- return {};
-}
-
-VALIDATE_INSTRUCTION(global_set)
-{
- auto index = instruction.arguments().get<GlobalIndex>();
- TRY(validate(index));
-
- auto& global = m_context.globals[index.value()];
-
- if (!global.is_mutable())
- return Errors::invalid("global variable for global.set"sv);
-
- TRY(stack.take(global.type()));
-
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#table-instructions%E2%91%A2
-VALIDATE_INSTRUCTION(table_get)
-{
- auto index = instruction.arguments().get<TableIndex>();
- auto table = TRY(validate(index));
-
- TRY(stack.take(table.limits().address_value_type()));
- stack.append(table.element_type());
- return {};
-}
-
-VALIDATE_INSTRUCTION(table_set)
-{
- auto index = instruction.arguments().get<TableIndex>();
- auto table = TRY(validate(index));
-
- TRY(stack.take(table.element_type()));
-
- TRY(stack.take(table.limits().address_value_type()));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(table_size)
-{
- auto index = instruction.arguments().get<TableIndex>();
- auto table = TRY(validate(index));
-
- stack.append(table.limits().address_value_type());
- return {};
-}
-
-VALIDATE_INSTRUCTION(table_grow)
-{
- auto index = instruction.arguments().get<TableIndex>();
- auto table = TRY(validate(index));
-
- auto const at = table.limits().address_value_type();
-
- TRY(stack.take(at));
- TRY(stack.take(table.element_type()));
-
- stack.append(at);
- return {};
-}
-
-VALIDATE_INSTRUCTION(table_fill)
-{
- auto index = instruction.arguments().get<TableIndex>();
- auto table = TRY(validate(index));
-
- TRY(stack.take(table.limits().address_value_type()));
- TRY(stack.take(table.element_type()));
- TRY(stack.take(table.limits().address_value_type()));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(table_copy)
-{
- auto& args = instruction.arguments().get<Instruction::TableTableArgs>();
-
- auto lhs_table = TRY(validate(args.lhs));
- auto rhs_table = TRY(validate(args.rhs));
-
- if (!matches_reference_type(rhs_table.element_type(), lhs_table.element_type(), m_context.type_context()))
- return Errors::non_conforming_types("table.copy"sv, lhs_table.element_type(), rhs_table.element_type());
-
- auto const lhs_at = lhs_table.limits().address_value_type();
- auto const rhs_at = rhs_table.limits().address_value_type();
- auto const size_type = ValueType(lhs_at.kind() == ValueType::I32 || rhs_at.kind() == ValueType::I32 ? ValueType::I32 : ValueType::I64);
-
- TRY(stack.take(size_type));
- TRY(stack.take(rhs_at));
- TRY(stack.take(lhs_at));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(table_init)
-{
- auto& args = instruction.arguments().get<Instruction::TableElementArgs>();
-
- auto table = TRY(validate(args.table_index));
- TRY(validate(args.element_index));
-
- auto& element_type = m_context.elements[args.element_index.value()];
-
- if (!matches_reference_type(element_type, table.element_type(), m_context.type_context()))
- return Errors::non_conforming_types("table.init"sv, table.element_type(), element_type);
-
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- TRY((stack.take(table.limits().address_value_type())));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(elem_drop)
-{
- auto index = instruction.arguments().get<ElementIndex>();
- TRY(validate(index));
-
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#memory-instructions%E2%91%A2
-VALIDATE_INSTRUCTION(i32_load)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(i32))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(i32));
-
- TRY((take_memory_address(stack, memory, arg)));
-
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_load)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(i64))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(i64));
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_load)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(float))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(float));
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::F32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_load)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(double))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(double));
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::F64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_load16_s)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 16 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 16 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_load16_u)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 16 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 16 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_load8_s)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 8 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 8 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_load8_u)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 8 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 8 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_load32_s)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 32 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 32 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_load32_u)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 32 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 32 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_load16_s)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 16 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 16 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_load16_u)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 16 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 16 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_load8_s)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 8 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 8 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_load8_u)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 8 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 8 / 8);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I64));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_store)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(i32))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(i32));
-
- TRY((stack.take<ValueType::I32>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_store)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(i64))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(i64));
-
- TRY((stack.take<ValueType::I64>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32_store)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(float))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(float));
-
- TRY((stack.take<ValueType::F32>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(f64_store)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(double))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(double));
-
- TRY((stack.take<ValueType::F64>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_store16)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 16 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 16 / 8);
-
- TRY((stack.take<ValueType::I32>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(i32_store8)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 8 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 8 / 8);
-
- TRY((stack.take<ValueType::I32>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_store32)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 32 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 32 / 8);
-
- TRY((stack.take<ValueType::I64>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_store16)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 16 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 16 / 8);
-
- TRY((stack.take<ValueType::I64>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(i64_store8)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > 8 / 8)
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, 8 / 8);
-
- TRY((stack.take<ValueType::I64>()));
- TRY((take_memory_address(stack, memory, arg)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_size)
-{
- auto memory = TRY(validate(instruction.arguments().get<Instruction::MemoryIndexArgument>().memory_index));
-
- stack.append(memory.limits().address_value_type());
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_grow)
-{
- auto memory = TRY(validate(instruction.arguments().get<Instruction::MemoryIndexArgument>().memory_index));
-
- auto const at = memory.limits().address_value_type();
- TRY((stack.take(at)));
- stack.append(at);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_fill)
-{
- auto memory = TRY(validate(instruction.arguments().get<Instruction::MemoryIndexArgument>().memory_index));
-
- TRY((take_memory_address(stack, memory, { 0, 0 })));
- TRY((stack.take<ValueType::I32>()));
- TRY((take_memory_address(stack, memory, { 0, 0 })));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_copy)
-{
- auto& args = instruction.arguments().get<Instruction::MemoryCopyArgs>();
- auto src_memory = TRY(validate(args.src_index));
- auto dst_memory = TRY(validate(args.dst_index));
-
- auto const src_at = ValueType(src_memory.limits().address_value_type());
- auto const dst_at = ValueType(dst_memory.limits().address_value_type());
- auto const size_at = ValueType(src_at.kind() == ValueType::I32 || dst_at.kind() == ValueType::I32 ? ValueType::I32 : ValueType::I64);
-
- TRY((stack.take(size_at)));
- TRY((stack.take(src_at)));
- TRY((stack.take(dst_at)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_init)
-{
- if (!m_context.data_count.has_value())
- return Errors::invalid("memory.init, requires data count section"sv);
-
- auto& args = instruction.arguments().get<Instruction::MemoryInitArgs>();
-
- auto memory = TRY(validate(args.memory_index));
- TRY(validate(args.data_index));
-
- auto const at = memory.limits().address_value_type();
-
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- TRY((stack.take(at)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(data_drop)
-{
- if (!m_context.data_count.has_value())
- return Errors::invalid("data.drop, requires data count section"sv);
-
- auto index = instruction.arguments().get<DataIndex>();
- TRY(validate(index));
-
- return {};
-}
-
-// https://webassembly.github.io/spec/core/bikeshed/#control-instructions%E2%91%A2
-VALIDATE_INSTRUCTION(nop)
-{
- return {};
-}
-
-VALIDATE_INSTRUCTION(unreachable)
-{
- // https://webassembly.github.io/spec/core/bikeshed/#polymorphism
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
-
- return {};
-}
-
-// Note: This is responsible for _all_ structured instructions, and is *not* from the spec.
-VALIDATE_INSTRUCTION(structured_end)
-{
- if (m_frames.is_empty())
- return Errors::invalid("usage of structured end"sv);
-
- auto& last_frame = m_frames.last();
-
- // If this is true, then the `if` had no else. In that case, validate that the
- // empty else block produces the correct type.
- if (last_frame.kind == FrameKind::If) {
- bool is_constant = false;
- TRY(validate(Instruction(Instructions::structured_else), stack, is_constant));
- }
-
- auto& results = last_frame.type.results();
- for (size_t i = 1; i <= results.size(); ++i)
- TRY(stack.take(results[results.size() - i]));
-
- if (stack.size() != last_frame.initial_size)
- return Errors::stack_height_mismatch(stack, last_frame.initial_size);
-
- for (auto& result : results)
- stack.append(result);
-
- // Locals initialized within the block become uninitialized again when it exits.
- // https://webassembly.github.io/spec/core/appendix/algorithm.html
- roll_back_local_initializations(last_frame.local_init_log_height);
- m_frames.take_last();
-
- return {};
-}
-
-// Note: This is *not* from the spec.
-VALIDATE_INSTRUCTION(structured_else)
-{
- if (m_frames.is_empty())
- return Errors::invalid("usage of structured else"sv);
-
- if (m_frames.last().kind != FrameKind::If)
- return Errors::invalid("usage of structured else"sv);
-
- auto& frame = m_frames.last();
- auto& block_type = frame.type;
- auto& results = block_type.results();
-
- for (size_t i = 1; i <= results.size(); ++i)
- TRY(stack.take(results[results.size() - i]));
-
- if (stack.size() != frame.initial_size)
- return Errors::stack_height_mismatch(stack, frame.initial_size);
-
- frame.kind = FrameKind::Else;
- frame.unreachable = false;
-
- // https://webassembly.github.io/spec/core/appendix/algorithm.html
- roll_back_local_initializations(frame.local_init_log_height);
-
- for (auto& parameter : block_type.parameters())
- stack.append(parameter);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(block)
-{
- auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
- auto block_type = TRY(validate(args.block_type));
-
- auto& parameters = block_type.parameters();
- for (size_t i = 1; i <= parameters.size(); ++i)
- TRY(stack.take(parameters[parameters.size() - i]));
-
- push_frame(Frame { block_type, FrameKind::Block, stack.size() });
- for (auto& parameter : parameters)
- stack.append(parameter);
-
- args.meta = Instruction::StructuredInstructionArgs::Meta {
- .arity = static_cast<u32>(block_type.results().size()),
- .parameter_count = static_cast<u32>(parameters.size()),
- .tier_up_eligible = false,
- };
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(loop)
-{
- auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
- auto block_type = TRY(validate(args.block_type));
-
- auto& parameters = block_type.parameters();
- for (size_t i = 1; i <= parameters.size(); ++i)
- TRY(stack.take(parameters[parameters.size() - i]));
-
- auto const tier_up_eligible = parameters.is_empty() && stack.size() == 0;
-
- push_frame(Frame { block_type, FrameKind::Loop, stack.size() });
- for (auto& parameter : parameters)
- stack.append(parameter);
-
- args.meta = Instruction::StructuredInstructionArgs::Meta {
- .arity = static_cast<u32>(block_type.results().size()),
- .parameter_count = static_cast<u32>(parameters.size()),
- .tier_up_eligible = tier_up_eligible,
- };
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(if_)
-{
- auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
- auto block_type = TRY(validate(args.block_type));
-
- TRY(stack.take<ValueType::I32>());
-
- auto stack_snapshot = stack;
-
- auto& parameters = block_type.parameters();
- for (size_t i = 1; i <= parameters.size(); ++i)
- TRY(stack.take(parameters[parameters.size() - i]));
-
- push_frame(Frame { block_type, FrameKind::If, stack.size() });
- for (auto& parameter : parameters)
- stack.append(parameter);
-
- args.meta = Instruction::StructuredInstructionArgs::Meta {
- .arity = static_cast<u32>(block_type.results().size()),
- .parameter_count = static_cast<u32>(parameters.size()),
- .tier_up_eligible = false,
- };
-
- return {};
-}
-
-// https://webassembly.github.io/exception-handling/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-throw-x
-VALIDATE_INSTRUCTION(throw_)
-{
- auto tag_index = instruction.arguments().get<TagIndex>();
- TRY(validate(tag_index));
-
- auto tag_type = m_context.tags[tag_index.value()];
- TRY(validate(tag_type.type()));
- auto& type = m_context.types[tag_type.type().value()];
-
- if (!type.is_function())
- return Errors::invalid("throw type"sv, "a function type"sv, type);
-
- auto& func = type.function();
-
- if (!func.results().is_empty())
- return Errors::invalid("throw type"sv, "empty"sv, func.results());
-
- for (auto const& parameter : func.parameters().in_reverse())
- TRY(stack.take(parameter));
-
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
-
- return {};
-}
-
-// https://webassembly.github.io/exception-handling/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-throw-ref
-VALIDATE_INSTRUCTION(throw_ref)
-{
- TRY(stack.take<ValueType::ExceptionReference>());
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
- return {};
-}
-
-// https://webassembly.github.io/exception-handling/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-try-table-xref-syntax-instructions-syntax-blocktype-mathit-blocktype-xref-syntax-instructions-syntax-catch-mathit-catch-ast-xref-syntax-instructions-syntax-instr-mathit-instr-ast-xref-syntax-instructions-syntax-instr-control-mathsf-end
-// https://webassembly.github.io/exception-handling/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-catch-x-l
-// https://webassembly.github.io/exception-handling/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-catch-ref-x-l
-// https://webassembly.github.io/exception-handling/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-catch-all-l
-// https://webassembly.github.io/exception-handling/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-catch-all-ref-l
-VALIDATE_INSTRUCTION(try_table)
-{
- auto& args = instruction.arguments().get<Instruction::TryTableArgs>();
- auto block_type = TRY(validate(args.block_type));
-
- // https://webassembly.github.io/spec/core/valid/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-try-table-xref-syntax-types-syntax-blocktype-mathit-blocktype-xref-syntax-instructions-syntax-catch-mathit-catch-ast-xref-syntax-instructions-syntax-instr-mathit-instr-ast
- // try_table bt catch* instr* is valid with [t1*] -> [t2*] if:
- // - The block type bt is valid as some instruction type [t1*] -> [t2*].
- // - For all catch in catch*: the catch clause catch is valid.
- // Note: the catch clauses are validated under C, without the try_table's own label.
- for (auto& catch_ : args.catches()) {
- // - The label C.labels[l] exists.
- auto label = catch_.target_label();
- TRY(validate(label));
- auto& target_label_type = m_frames[(m_frames.size() - 1) - label.value()].labels();
-
- Vector<ValueType> expected_label_types;
- if (auto tag = catch_.matching_tag_index(); tag.has_value()) {
- // - The tag C.tags[x] exists.
- TRY(validate(tag.value()));
- auto tag_type = m_context.tags[tag->value()];
- TRY(validate(tag_type.type()));
- auto& type = m_context.types[tag_type.type().value()];
-
- // - The expansion of C.tags[x] is (func t* -> ε).
- if (!type.is_function())
- return Errors::invalid("catch tag type"sv, "a function type"sv, type);
- auto& func = type.function();
- if (!func.results().is_empty())
- return Errors::invalid("catch tag type"sv, "no results"sv, func.results());
-
- expected_label_types.extend(func.parameters());
- }
-
- // catch x l: the result type t* matches the label C.labels[l].
- // catch_ref x l: the result type t* (ref exn) matches the label C.labels[l].
- // catch_all l: the result type ε matches the label C.labels[l].
- // catch_all_ref l: the result type (ref exn) matches the label C.labels[l].
- if (catch_.is_ref())
- expected_label_types.append(ValueType(ValueType::ExceptionReference, false));
-
- if (!matches_result_types(expected_label_types.span(), target_label_type.span(), m_context.type_context()))
- return Errors::non_conforming_types("catch"sv, expected_label_types.span(), target_label_type.span());
- }
-
- auto& parameters = block_type.parameters();
- for (size_t i = 1; i <= parameters.size(); ++i)
- TRY(stack.take(parameters[parameters.size() - i]));
-
- args.meta = Instruction::TryTableArgs::Meta {
- .arity = static_cast<u32>(block_type.results().size()),
- .parameter_count = static_cast<u32>(parameters.size()),
- .tier_up_eligible = false,
- };
-
- push_frame(Frame { block_type, FrameKind::TryTable, stack.size() });
- for (auto& parameter : parameters)
- stack.append(parameter);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(br)
-{
- auto& args = instruction.arguments().get<Instruction::BranchArgs>();
- TRY(validate(args.label));
-
- auto& target = m_frames[(m_frames.size() - 1) - args.label.value()];
-
- auto& type = target.labels();
- for (size_t i = 1; i <= type.size(); ++i)
- TRY(stack.take(type[type.size() - i]));
-
- args.has_stack_adjustment = target.initial_size != stack.size();
-
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
- return {};
-}
-
-VALIDATE_INSTRUCTION(br_if)
-{
- auto& args = instruction.arguments().get<Instruction::BranchArgs>();
- TRY(validate(args.label));
-
- TRY(stack.take<ValueType::I32>());
-
- auto& target = m_frames[(m_frames.size() - 1) - args.label.value()];
- auto& type = target.labels();
-
- Vector<StackEntry> entries;
- entries.ensure_capacity(type.size());
-
- for (size_t i = 0; i < type.size(); ++i) {
- auto& entry = type[type.size() - i - 1];
- TRY(stack.take(entry));
- entries.append(entry);
- }
-
- for (size_t i = 0; i < entries.size(); ++i)
- stack.append(entries[entries.size() - i - 1]);
-
- args.has_stack_adjustment = target.initial_size != stack.size();
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(br_table)
-{
- auto& args = instruction.arguments().get<Instruction::TableBranchArgs>();
- TRY(validate(args.default_));
-
- for (auto& label : args.labels)
- TRY(validate(label));
-
- TRY(stack.take<ValueType::I32>());
-
- auto& default_types = m_frames[(m_frames.size() - 1) - args.default_.value()].labels();
- auto arity = default_types.size();
-
- for (auto& label : args.labels) {
- auto& label_types = m_frames[(m_frames.size() - 1) - label.value()].labels();
- if (label_types.size() != arity)
- return Errors::invalid("br_table label arity mismatch"sv);
- Vector<StackEntry> popped {};
- for (size_t i = 0; i < arity; ++i) {
- auto stack_entry = TRY(stack.take(label_types[label_types.size() - i - 1]));
- popped.append(stack_entry);
- }
- for (auto popped_type : popped.in_reverse())
- stack.append(popped_type);
- }
-
- for (size_t i = 0; i < arity; ++i) {
- auto expected = default_types[default_types.size() - i - 1];
- TRY((stack.take(expected)));
- }
-
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(return_)
-{
- auto& return_types = m_frames.first().type.results();
- for (size_t i = 0; i < return_types.size(); ++i)
- TRY((stack.take(return_types[return_types.size() - i - 1])));
-
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(call)
-{
- auto index = instruction.arguments().get<FunctionIndex>();
- TRY(validate(index));
-
- auto& function_type = m_context.functions[index.value()];
- for (size_t i = 0; i < function_type.parameters().size(); ++i)
- TRY(stack.take(function_type.parameters()[function_type.parameters().size() - i - 1]));
-
- for (auto& type : function_type.results())
- stack.append(type);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(call_indirect)
-{
- auto& args = instruction.arguments().get<Instruction::IndirectCallArgs>();
- auto table = TRY(validate(args.table));
- TRY(validate(args.type));
-
- if (!matches_reference_type(table.element_type(), ValueType(ValueType::FunctionReference), m_context.type_context()))
- return Errors::invalid("table element type for call.indirect"sv, "a function reference"sv, table.element_type());
-
- auto& type = m_context.types[args.type.value()];
-
- if (!type.is_function())
- return Errors::invalid("type for call.indirect"sv, "a function type"sv, type);
-
- auto& func = type.function();
- TRY(stack.take(table.limits().address_value_type()));
-
- for (size_t i = 0; i < func.parameters().size(); ++i)
- TRY(stack.take(func.parameters()[func.parameters().size() - i - 1]));
-
- for (auto& type : func.results())
- stack.append(type);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(return_call)
-{
- auto index = instruction.arguments().get<FunctionIndex>();
- TRY(validate(index));
-
- auto& function_type = m_context.functions[index.value()];
- for (size_t i = 0; i < function_type.parameters().size(); ++i)
- TRY(stack.take(function_type.parameters()[function_type.parameters().size() - i - 1]));
-
- auto const& return_types = m_frames.first().type.results();
- if (return_types != function_type.results())
- return Errors::invalid("return_call target"sv, function_type.results(), return_types);
-
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(return_call_indirect)
-{
- auto& args = instruction.arguments().get<Instruction::IndirectCallArgs>();
- TRY(validate(args.table));
- TRY(validate(args.type));
-
- auto& table = m_context.tables[args.table.value()];
- if (!matches_reference_type(table.element_type(), ValueType(ValueType::FunctionReference), m_context.type_context()))
- return Errors::invalid("table element type for call.indirect"sv, "a function reference"sv, table.element_type());
-
- auto& type = m_context.types[args.type.value()];
- if (!type.is_function())
- return Errors::invalid("type for return_call_indirect"sv, "a function type"sv, table.element_type());
-
- auto& func = type.function();
-
- TRY(stack.take<ValueType::I32>());
-
- for (size_t i = 0; i < func.parameters().size(); ++i)
- TRY(stack.take(func.parameters()[func.parameters().size() - i - 1]));
-
- auto& return_types = m_frames.first().type.results();
- if (return_types != func.results())
- return Errors::invalid("return_call_indirect target"sv, func.results(), return_types);
-
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(call_ref)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- TRY(validate(type_index));
-
- auto const& type = m_context.types[type_index.value()];
- if (!type.is_function())
- return Errors::invalid("type for call_ref"sv, "a function type"sv, type);
-
- auto const& func = type.function();
-
- TRY(stack.take(ValueType(ValueType::TypeUseReference, type_index)));
-
- for (size_t i = 0; i < func.parameters().size(); ++i)
- TRY(stack.take(func.parameters()[func.parameters().size() - i - 1]));
-
- for (auto const& type : func.results())
- stack.append(type);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(return_call_ref)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- TRY(validate(type_index));
-
- auto const& type = m_context.types[type_index.value()];
- if (!type.is_function())
- return Errors::invalid("type for return_call_ref"sv, "a function type"sv, type);
-
- auto const& func = type.function();
-
- TRY(stack.take(ValueType(ValueType::TypeUseReference, type_index)));
-
- for (size_t i = 0; i < func.parameters().size(); ++i)
- TRY(stack.take(func.parameters()[func.parameters().size() - i - 1]));
-
- auto const& return_types = m_frames.first().type.results();
- auto const& callee_results = func.results();
- if (return_types.size() != callee_results.size())
- return Errors::invalid("return_call_ref target"sv, callee_results, return_types);
- for (size_t i = 0; i < return_types.size(); ++i) {
- StackEntry entry { callee_results[i] };
- if (entry != return_types[i])
- return Errors::invalid("return_call_ref target"sv, callee_results, return_types);
- }
-
- m_frames.last().unreachable = true;
- stack.resize(m_frames.last().initial_size);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_load)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(u128))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(u128));
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::V128));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_load8x8_s)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 8;
- constexpr auto M = 8;
- constexpr auto max_alignment = N * M / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load8x8_u)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 8;
- constexpr auto M = 8;
- constexpr auto max_alignment = N * M / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load16x4_s)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 16;
- constexpr auto M = 4;
- constexpr auto max_alignment = N * M / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load16x4_u)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 16;
- constexpr auto M = 4;
- constexpr auto max_alignment = N * M / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load32x2_s)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 32;
- constexpr auto M = 2;
- constexpr auto max_alignment = N * M / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load32x2_u)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 32;
- constexpr auto M = 2;
- constexpr auto max_alignment = N * M / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load8_splat)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 8;
- constexpr auto max_alignment = N / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load16_splat)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 16;
- constexpr auto max_alignment = N / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load32_splat)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 32;
- constexpr auto max_alignment = N / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_load64_splat)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 64;
- constexpr auto max_alignment = N / 8;
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- return stack.take_and_put<ValueType::I32>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_store)
-{
- auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
-
- TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1ull << arg.align) > sizeof(u128))
- return Errors::out_of_bounds("memory op alignment"sv, 1ull << arg.align, 0, sizeof(u128));
-
- TRY((stack.take<ValueType::V128, ValueType::I32>()));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_const)
-{
- is_constant = true;
- stack.append(ValueType(ValueType::V128));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i8x16_shuffle)
-{
- auto const& arg = instruction.arguments().get<Instruction::ShuffleArgument>();
- for (auto lane : arg.lanes) {
- if (lane >= 32)
- return Errors::out_of_bounds("shuffle lane"sv, lane, 0, 32);
- }
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_swizzle)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-enum class Shape {
- I8x16,
- I16x8,
- I32x4,
- I64x2,
- F32x4,
- F64x2,
-};
-
-template<Shape shape>
-static constexpr Wasm::ValueType::Kind unpacked()
-{
- switch (shape) {
- case Shape::I8x16:
- case Shape::I16x8:
- case Shape::I32x4:
- return Wasm::ValueType::I32;
- case Shape::I64x2:
- return Wasm::ValueType::I64;
- case Shape::F32x4:
- return Wasm::ValueType::F32;
- case Shape::F64x2:
- return Wasm::ValueType::F64;
- }
-}
-
-template<Shape shape>
-static constexpr size_t dimensions()
-{
- switch (shape) {
- case Shape::I8x16:
- return 16;
- case Shape::I16x8:
- return 8;
- case Shape::I32x4:
- return 4;
- case Shape::I64x2:
- return 2;
- case Shape::F32x4:
- return 4;
- case Shape::F64x2:
- return 2;
- }
-}
-
-VALIDATE_INSTRUCTION(i8x16_splat)
-{
- constexpr auto unpacked_shape = unpacked<Shape::I8x16>();
- return stack.take_and_put<unpacked_shape>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_splat)
-{
- constexpr auto unpacked_shape = unpacked<Shape::I16x8>();
- return stack.take_and_put<unpacked_shape>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_splat)
-{
- constexpr auto unpacked_shape = unpacked<Shape::I32x4>();
- return stack.take_and_put<unpacked_shape>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_splat)
-{
- constexpr auto unpacked_shape = unpacked<Shape::I64x2>();
- return stack.take_and_put<unpacked_shape>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_splat)
-{
- constexpr auto unpacked_shape = unpacked<Shape::F32x4>();
- return stack.take_and_put<unpacked_shape>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_splat)
-{
- constexpr auto unpacked_shape = unpacked<Shape::F64x2>();
- return stack.take_and_put<unpacked_shape>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_extract_lane_s)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I8x16;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(i8x16_extract_lane_u)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I8x16;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(i8x16_replace_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I8x16;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<unpacked<shape>(), ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extract_lane_s)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I16x8;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(i16x8_extract_lane_u)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I16x8;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(i16x8_replace_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I16x8;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<unpacked<shape>(), ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extract_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I32x4;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(i32x4_replace_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I32x4;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<unpacked<shape>(), ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extract_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I64x2;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(i64x2_replace_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::I64x2;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<unpacked<shape>(), ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_extract_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::F32x4;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(f32x4_replace_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::F32x4;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<unpacked<shape>(), ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_extract_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::F64x2;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<ValueType::V128>(unpacked<shape>());
-}
-
-VALIDATE_INSTRUCTION(f64x2_replace_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::LaneIndex>();
- constexpr auto shape = Shape::F64x2;
- constexpr auto max_lane = dimensions<shape>();
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("extract lane"sv, arg.lane, 0, max_lane);
- return stack.take_and_put<unpacked<shape>(), ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_eq)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_ne)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_lt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_lt_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_gt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_gt_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_le_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_le_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_ge_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_ge_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_eq)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_ne)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_lt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_lt_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_gt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_gt_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_le_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_le_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_ge_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_ge_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_eq)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_ne)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_lt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_lt_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_gt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_gt_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_le_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_le_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_ge_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_ge_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_eq)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_ne)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_lt)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_gt)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_le)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_ge)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_eq)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_ne)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_lt)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_gt)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_le)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_ge)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_not)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_and)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_andnot)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_or)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_xor)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_bitselect)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(v128_any_true)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(v128_load8_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 8;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- stack.append(ValueType(ValueType::V128));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_load16_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 16;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- stack.append(ValueType(ValueType::V128));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_load32_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 32;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- stack.append(ValueType(ValueType::V128));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_load64_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 64;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- stack.append(ValueType(ValueType::V128));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_store8_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 8;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_store16_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 16;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_store32_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 32;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_store64_lane)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryAndLaneArgument>();
- constexpr auto N = 64;
- constexpr auto max_lane = 128 / N;
- constexpr auto max_alignment = N / 8;
-
- if (arg.lane >= max_lane)
- return Errors::out_of_bounds("lane index"sv, arg.lane, 0u, max_lane);
-
- auto memory = TRY(validate(arg.memory.memory_index));
-
- if (arg.memory.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.memory.align, 0, 64);
-
- if ((1 << arg.memory.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.memory.align, 0u, max_alignment);
-
- TRY((stack.take<ValueType::V128>()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_load32_zero)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 32;
- constexpr auto max_alignment = N / 8;
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::V128));
- return {};
-}
-
-VALIDATE_INSTRUCTION(v128_load64_zero)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- constexpr auto N = 64;
- constexpr auto max_alignment = N / 8;
-
- auto memory = TRY(validate(arg.memory_index));
-
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- if ((1 << arg.align) > max_alignment)
- return Errors::out_of_bounds("memory op alignment"sv, 1 << arg.align, 0u, max_alignment);
-
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::V128));
- return {};
-}
-
-VALIDATE_INSTRUCTION(f32x4_demote_f64x2_zero)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_promote_low_f32x4)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_abs)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_neg)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_popcnt)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_all_true)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i8x16_bitmask)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i8x16_narrow_i16x8_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_narrow_i16x8_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_ceil)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_floor)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_trunc)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_nearest)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_shl)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_shr_s)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_shr_u)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_add)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_add_sat_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_add_sat_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_sub)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_sub_sat_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_sub_sat_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_ceil)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_floor)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_min_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_min_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_max_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_max_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_trunc)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_avgr_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extadd_pairwise_i8x16_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extadd_pairwise_i8x16_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extadd_pairwise_i16x8_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extadd_pairwise_i16x8_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_abs)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_neg)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_q15mulr_sat_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_all_true)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i16x8_bitmask)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i16x8_narrow_i32x4_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_narrow_i32x4_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extend_low_i8x16_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extend_high_i8x16_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extend_low_i8x16_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extend_high_i8x16_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_shl)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_shr_s)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_shr_u)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_add)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_add_sat_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_add_sat_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_sub)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_sub_sat_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_sub_sat_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_nearest)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_mul)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_min_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_min_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_max_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_max_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_avgr_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extmul_low_i8x16_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extmul_high_i8x16_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extmul_low_i8x16_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_extmul_high_i8x16_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_abs)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_neg)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_all_true)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i32x4_bitmask)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extend_low_i16x8_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extend_high_i16x8_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extend_low_i16x8_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extend_high_i16x8_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_shl)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_shr_s)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_shr_u)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_add)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_sub)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_mul)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_min_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_min_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_max_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_max_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_dot_i16x8_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extmul_low_i16x8_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extmul_high_i16x8_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extmul_low_i16x8_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_extmul_high_i16x8_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_abs)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_neg)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_all_true)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i64x2_bitmask)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::I32);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extend_low_i32x4_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extend_high_i32x4_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extend_low_i32x4_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extend_high_i32x4_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_shl)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_shr_s)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_shr_u)
-{
- return stack.take_and_put<ValueType::I32, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_add)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_sub)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_mul)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_eq)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_ne)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_lt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_gt_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_le_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_ge_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extmul_low_i32x4_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extmul_high_i32x4_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extmul_low_i32x4_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_extmul_high_i32x4_u)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_abs)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_neg)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_sqrt)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_add)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_sub)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_mul)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_div)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_min)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_max)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_pmin)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_pmax)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_abs)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_neg)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_sqrt)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_add)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_sub)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_mul)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_div)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_min)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_max)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_pmin)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_pmax)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_trunc_sat_f32x4_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_trunc_sat_f32x4_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_convert_i32x4_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_convert_i32x4_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_trunc_sat_f64x2_s_zero)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_trunc_sat_f64x2_u_zero)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_convert_low_i32x4_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_convert_low_i32x4_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_relaxed_swizzle)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_relaxed_trunc_f32x4_s)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_relaxed_trunc_f32x4_u)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_relaxed_trunc_f64x2_s_zero)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_relaxed_trunc_f64x2_u_zero)
-{
- return stack.take_and_put<ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_relaxed_madd)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_relaxed_nmadd)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_relaxed_madd)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_relaxed_nmadd)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i8x16_relaxed_laneselect)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_relaxed_laneselect)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_relaxed_laneselect)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i64x2_relaxed_laneselect)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_relaxed_min)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f32x4_relaxed_max)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_relaxed_min)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(f64x2_relaxed_max)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_relaxed_q15mulr_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i16x8_relaxed_dot_i8x16_i7x16_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-VALIDATE_INSTRUCTION(i32x4_relaxed_dot_i8x16_i7x16_add_s)
-{
- return stack.take_and_put<ValueType::V128, ValueType::V128, ValueType::V128>(ValueType::V128);
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#reference-instructions
-VALIDATE_INSTRUCTION(ref_eq)
-{
- TRY(stack.take(ValueType(ValueType::EqReference)));
- TRY(stack.take(ValueType(ValueType::EqReference)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#reference-instructions
-VALIDATE_INSTRUCTION(ref_as_non_null)
-{
- auto entry = TRY(stack.take_last());
- if (entry.is_known && !entry.concrete_type.is_reference())
- return Errors::invalid_stack_state(stack, Tuple { "reference" });
-
- if (entry.is_known) {
- auto type = entry.concrete_type;
- type.set_nullable(false);
- stack.append(type);
- } else {
- stack.append(entry);
- }
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#control-instructions
-VALIDATE_INSTRUCTION(br_on_null)
-{
- auto& args = instruction.arguments().get<Instruction::BranchArgs>();
- TRY(validate(args.label));
-
- auto entry = TRY(stack.take_last());
- if (entry.is_known && !entry.concrete_type.is_reference())
- return Errors::invalid_stack_state(stack, Tuple { "reference" });
-
- auto& target = m_frames[(m_frames.size() - 1) - args.label.value()];
- auto& type = target.labels();
-
- for (size_t i = 0; i < type.size(); ++i)
- TRY(stack.take(type[type.size() - i - 1]));
- for (auto& label_type : type)
- stack.append(label_type);
-
- if (entry.is_known) {
- auto result = entry.concrete_type;
- result.set_nullable(false);
- stack.append(result);
- } else {
- stack.append(entry);
- }
-
- args.has_stack_adjustment = target.initial_size != stack.size();
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#control-instructions
-VALIDATE_INSTRUCTION(br_on_non_null)
-{
- auto& args = instruction.arguments().get<Instruction::BranchArgs>();
- TRY(validate(args.label));
-
- auto& target = m_frames[(m_frames.size() - 1) - args.label.value()];
- auto& type = target.labels();
- if (type.is_empty() || !type.last().is_reference())
- return Errors::invalid("br_on_non_null label type"sv, "t* (ref null? ht)"sv, type);
-
- auto expected = type.last();
- expected.set_nullable(true);
- TRY(stack.take(expected));
-
- for (size_t i = 0; i + 1 < type.size(); ++i)
- TRY(stack.take(type[type.size() - i - 2]));
- for (size_t i = 0; i + 1 < type.size(); ++i)
- stack.append(type[i]);
-
- args.has_stack_adjustment = target.initial_size != stack.size();
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(struct_new)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- TRY(validate(type_index));
- auto const& type = m_context.types[type_index.value()];
- if (!type.is_struct())
- return Errors::invalid("struct.new type"sv, "a struct type"sv, type);
-
- auto& fields = type.struct_().fields();
- for (size_t i = 0; i < fields.size(); ++i)
- TRY(stack.take(fields[fields.size() - i - 1].type().unpacked()));
-
- stack.append(ValueType(ValueType::TypeUseReference, type_index, false));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(struct_new_default)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- TRY(validate(type_index));
- auto const& type = m_context.types[type_index.value()];
- if (!type.is_struct())
- return Errors::invalid("struct.new_default type"sv, "a struct type"sv, type);
-
- for (auto& field : type.struct_().fields()) {
- if (!field.type().is_defaultable())
- return Errors::invalid("struct.new_default field type, must be defaultable"sv);
- }
-
- stack.append(ValueType(ValueType::TypeUseReference, type_index, false));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-ErrorOr<void, ValidationError> Validator::validate_struct_get(Stack& stack, Instruction const& instruction, bool requires_packed)
-{
- auto& args = instruction.arguments().get<Instruction::StructFieldArgs>();
- TRY(validate(args.type_index));
- auto const& type = m_context.types[args.type_index.value()];
- if (!type.is_struct())
- return Errors::invalid("struct.get type"sv, "a struct type"sv, type);
-
- auto& fields = type.struct_().fields();
- if (args.field_index >= fields.size())
- return Errors::invalid("struct.get field index"sv);
- auto field_type = fields[args.field_index].type();
- if (field_type.is_packed() != requires_packed)
- return Errors::invalid("struct.get signedness, present iff the field type is packed"sv);
-
- TRY(stack.take(ValueType(ValueType::TypeUseReference, args.type_index)));
- stack.append(field_type.unpacked());
- return {};
-}
-
-VALIDATE_INSTRUCTION(struct_get)
-{
- return validate_struct_get(stack, instruction, false);
-}
-
-VALIDATE_INSTRUCTION(struct_get_s)
-{
- return validate_struct_get(stack, instruction, true);
-}
-
-VALIDATE_INSTRUCTION(struct_get_u)
-{
- return validate_struct_get(stack, instruction, true);
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(struct_set)
-{
- auto& args = instruction.arguments().get<Instruction::StructFieldArgs>();
- TRY(validate(args.type_index));
- auto const& type = m_context.types[args.type_index.value()];
- if (!type.is_struct())
- return Errors::invalid("struct.set type"sv, "a struct type"sv, type);
-
- auto& fields = type.struct_().fields();
- if (args.field_index >= fields.size())
- return Errors::invalid("struct.set field index"sv);
- auto& field = fields[args.field_index];
- if (!field.is_mutable())
- return Errors::invalid("struct.set field, must be mutable"sv);
-
- TRY(stack.take(field.type().unpacked()));
- TRY(stack.take(ValueType(ValueType::TypeUseReference, args.type_index)));
- return {};
-}
-
-ErrorOr<FieldType, ValidationError> Validator::array_field_type(TypeIndex type_index, StringView instruction_name, bool requires_mutable)
-{
- TRY(validate(type_index));
- auto const& type = m_context.types[type_index.value()];
- if (!type.is_array())
- return Errors::invalid(instruction_name, "an array type"sv, type);
- if (requires_mutable && !type.array().type().is_mutable())
- return Errors::invalid(instruction_name, "a mutable array type"sv, type);
- return type.array().type();
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_new)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- auto field = TRY(array_field_type(type_index, "array.new type"sv, false));
-
- TRY(stack.take<ValueType::I32>());
- TRY(stack.take(field.type().unpacked()));
- stack.append(ValueType(ValueType::TypeUseReference, type_index, false));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_new_default)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- auto field = TRY(array_field_type(type_index, "array.new_default type"sv, false));
- if (!field.type().is_defaultable())
- return Errors::invalid("array.new_default element type, must be defaultable"sv);
-
- TRY(stack.take<ValueType::I32>());
- stack.append(ValueType(ValueType::TypeUseReference, type_index, false));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_new_fixed)
-{
- auto& args = instruction.arguments().get<Instruction::ArrayNewFixedArgs>();
- auto field = TRY(array_field_type(args.type_index, "array.new_fixed type"sv, false));
-
- for (size_t i = 0; i < args.count; ++i)
- TRY(stack.take(field.type().unpacked()));
- stack.append(ValueType(ValueType::TypeUseReference, args.type_index, false));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_new_data)
-{
- auto& args = instruction.arguments().get<Instruction::ArrayDataArgs>();
- auto field = TRY(array_field_type(args.type_index, "array.new_data type"sv, false));
- if (field.type().is_reference())
- return Errors::invalid("array.new_data element type"sv, "a numeric or vector type"sv, field.type());
-
- if (!m_context.data_count.has_value())
- return Errors::invalid("array.new_data, requires data count section"sv);
- TRY(validate(args.data_index));
-
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::TypeUseReference, args.type_index, false));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_new_elem)
-{
- auto& args = instruction.arguments().get<Instruction::ArrayElemArgs>();
- auto field = TRY(array_field_type(args.type_index, "array.new_elem type"sv, false));
- if (!field.type().is_reference())
- return Errors::invalid("array.new_elem element type"sv, "a reference type"sv, field.type());
-
- TRY(validate(args.element_index));
- auto segment_type = m_context.elements[args.element_index.value()];
- if (!matches_reference_type(segment_type, field.type(), m_context.type_context()))
- return Errors::invalid("array.new_elem element segment type"sv, field.type(), segment_type);
-
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- stack.append(ValueType(ValueType::TypeUseReference, args.type_index, false));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-ErrorOr<void, ValidationError> Validator::validate_array_get(Stack& stack, Instruction const& instruction, bool requires_packed)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- auto field = TRY(array_field_type(type_index, "array.get type"sv, false));
- if (field.type().is_packed() != requires_packed)
- return Errors::invalid("array.get signedness, present iff the element type is packed"sv);
-
- TRY(stack.take<ValueType::I32>());
- TRY(stack.take(ValueType(ValueType::TypeUseReference, type_index)));
- stack.append(field.type().unpacked());
- return {};
-}
-
-VALIDATE_INSTRUCTION(array_get)
-{
- return validate_array_get(stack, instruction, false);
-}
-
-VALIDATE_INSTRUCTION(array_get_s)
-{
- return validate_array_get(stack, instruction, true);
-}
-
-VALIDATE_INSTRUCTION(array_get_u)
-{
- return validate_array_get(stack, instruction, true);
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_set)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- auto field = TRY(array_field_type(type_index, "array.set type"sv, true));
-
- TRY(stack.take(field.type().unpacked()));
- TRY(stack.take<ValueType::I32>());
- TRY(stack.take(ValueType(ValueType::TypeUseReference, type_index)));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_len)
-{
- TRY(stack.take(ValueType(ValueType::ArrayReference)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_fill)
-{
- auto type_index = instruction.arguments().get<TypeIndex>();
- auto field = TRY(array_field_type(type_index, "array.fill type"sv, true));
-
- TRY(stack.take<ValueType::I32>());
- TRY(stack.take(field.type().unpacked()));
- TRY(stack.take<ValueType::I32>());
- TRY(stack.take(ValueType(ValueType::TypeUseReference, type_index)));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_copy)
-{
- auto& args = instruction.arguments().get<Instruction::ArrayCopyArgs>();
- auto destination_field = TRY(array_field_type(args.destination_type_index, "array.copy destination type"sv, true));
- auto source_field = TRY(array_field_type(args.source_type_index, "array.copy source type"sv, false));
-
- if (!matches_field_type(FieldType { false, source_field.type() }, FieldType { false, destination_field.type() }, m_context.type_context()))
- return Errors::invalid("array.copy source element type"sv, destination_field.type(), source_field.type());
-
- TRY((stack.take<ValueType::I32, ValueType::I32>()));
- TRY(stack.take(ValueType(ValueType::TypeUseReference, args.source_type_index)));
- TRY(stack.take<ValueType::I32>());
- TRY(stack.take(ValueType(ValueType::TypeUseReference, args.destination_type_index)));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_init_data)
-{
- auto& args = instruction.arguments().get<Instruction::ArrayDataArgs>();
- auto field = TRY(array_field_type(args.type_index, "array.init_data type"sv, true));
- if (field.type().is_reference())
- return Errors::invalid("array.init_data element type"sv, "a numeric or vector type"sv, field.type());
-
- if (!m_context.data_count.has_value())
- return Errors::invalid("array.init_data, requires data count section"sv);
- TRY(validate(args.data_index));
-
- TRY((stack.take<ValueType::I32, ValueType::I32, ValueType::I32>()));
- TRY(stack.take(ValueType(ValueType::TypeUseReference, args.type_index)));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#aggregate-reference-instructions
-VALIDATE_INSTRUCTION(array_init_elem)
-{
- auto& args = instruction.arguments().get<Instruction::ArrayElemArgs>();
- auto field = TRY(array_field_type(args.type_index, "array.init_elem type"sv, true));
- if (!field.type().is_reference())
- return Errors::invalid("array.init_elem element type"sv, "a reference type"sv, field.type());
-
- TRY(validate(args.element_index));
- auto segment_type = m_context.elements[args.element_index.value()];
- if (!matches_reference_type(segment_type, field.type(), m_context.type_context()))
- return Errors::invalid("array.init_elem element segment type"sv, field.type(), segment_type);
-
- TRY((stack.take<ValueType::I32, ValueType::I32, ValueType::I32>()));
- TRY(stack.take(ValueType(ValueType::TypeUseReference, args.type_index)));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#reference-instructions
-ErrorOr<void, ValidationError> Validator::validate_ref_test_or_cast(Stack& stack, Instruction const& instruction)
-{
- auto type = instruction.arguments().get<ValueType>();
- TRY(validate(type));
-
- auto top = ValueType(top_of_heap_type(type, m_context.type_context()));
- TRY(stack.take(top));
- return {};
-}
-
-VALIDATE_INSTRUCTION(ref_test)
-{
- TRY(validate_ref_test_or_cast(stack, instruction));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(ref_test_null)
-{
- TRY(validate_ref_test_or_cast(stack, instruction));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#reference-instructions
-VALIDATE_INSTRUCTION(ref_cast)
-{
- TRY(validate_ref_test_or_cast(stack, instruction));
- stack.append(instruction.arguments().get<ValueType>());
- return {};
-}
-
-VALIDATE_INSTRUCTION(ref_cast_null)
-{
- TRY(validate_ref_test_or_cast(stack, instruction));
- stack.append(instruction.arguments().get<ValueType>());
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#control-instructions
-ErrorOr<void, ValidationError> Validator::validate_br_on_cast(Stack& stack, Instruction const& instruction, bool branch_on_failure)
-{
- auto& args = instruction.arguments().get<Instruction::BranchOnCastArgs>();
- TRY(validate(args.branch.label));
- TRY(validate(args.source_type));
- TRY(validate(args.target_type));
-
- if (!matches_reference_type(args.target_type, args.source_type, m_context.type_context()))
- return Errors::invalid("br_on_cast target type"sv, args.source_type, args.target_type);
-
- auto& target = m_frames[(m_frames.size() - 1) - args.branch.label.value()];
- auto& label_types = target.labels();
- if (label_types.is_empty() || !label_types.last().is_reference())
- return Errors::invalid("br_on_cast label type"sv, "t* rt"sv, label_types);
- auto& label_reference_type = label_types.last();
-
- // https://webassembly.github.io/spec/core/valid/conventions.html#conventions
- // rt1 \ rt2 = (ref ht1) if rt2 = (ref null ht2)
- // = (ref null1? ht1) otherwise
- auto difference = args.source_type;
- if (args.target_type.is_nullable())
- difference.set_nullable(false);
-
- auto& branched_type = branch_on_failure ? difference : args.target_type;
- if (!matches_reference_type(branched_type, label_reference_type, m_context.type_context()))
- return Errors::invalid("br_on_cast label type"sv, label_reference_type, branched_type);
-
- TRY(stack.take(args.source_type));
- for (size_t i = 0; i + 1 < label_types.size(); ++i)
- TRY(stack.take(label_types[label_types.size() - i - 2]));
- for (size_t i = 0; i + 1 < label_types.size(); ++i)
- stack.append(label_types[i]);
-
- stack.append(branch_on_failure ? args.target_type : difference);
- args.branch.has_stack_adjustment = target.initial_size != stack.size();
- return {};
-}
-
-VALIDATE_INSTRUCTION(br_on_cast)
-{
- return validate_br_on_cast(stack, instruction, false);
-}
-
-VALIDATE_INSTRUCTION(br_on_cast_fail)
-{
- return validate_br_on_cast(stack, instruction, true);
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#external-reference-instructions
-VALIDATE_INSTRUCTION(any_convert_extern)
-{
- auto entry = TRY(stack.take_last());
- bool nullable = true;
- if (entry.is_known) {
- if (!matches_value_type(entry.concrete_type, ValueType(ValueType::ExternReference), m_context.type_context()))
- return Errors::invalid("any.convert_extern operand"sv, ValueType(ValueType::ExternReference), entry);
- nullable = entry.concrete_type.is_nullable();
- } else {
- nullable = false;
- }
- stack.append(ValueType(ValueType::AnyReference, nullable));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#external-reference-instructions
-VALIDATE_INSTRUCTION(extern_convert_any)
-{
- auto entry = TRY(stack.take_last());
- bool nullable = true;
- if (entry.is_known) {
- if (!matches_value_type(entry.concrete_type, ValueType(ValueType::AnyReference), m_context.type_context()))
- return Errors::invalid("extern.convert_any operand"sv, ValueType(ValueType::AnyReference), entry);
- nullable = entry.concrete_type.is_nullable();
- } else {
- nullable = false;
- }
- stack.append(ValueType(ValueType::ExternReference, nullable));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#scalar-reference-instructions
-VALIDATE_INSTRUCTION(ref_i31)
-{
- TRY(stack.take<ValueType::I32>());
- stack.append(ValueType(ValueType::I31Reference, false));
- is_constant = true;
- return {};
-}
-
-// https://webassembly.github.io/spec/core/valid/instructions.html#scalar-reference-instructions
-VALIDATE_INSTRUCTION(i31_get_s)
-{
- TRY(stack.take(ValueType(ValueType::I31Reference)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(i31_get_u)
-{
- TRY(stack.take(ValueType(ValueType::I31Reference)));
- stack.append(ValueType(ValueType::I32));
- return {};
-}
-
-VALIDATE_INSTRUCTION(synthetic_end_expression)
-{
- is_constant = true;
- return {}; // Always valid.
-}
-
-// https://webassembly.github.io/threads/core/valid/instructions.html#atomic-memory-instructions
-ErrorOr<void, ValidationError> Validator::validate_atomic_memory_argument(Instruction::MemoryArgument const& arg, size_t access_size)
-{
- if (arg.align > 64)
- return Errors::out_of_bounds("memory op alignment value"sv, arg.align, 0, 64);
-
- // Unlike plain memory accesses, atomic accesses must be exactly naturally aligned.
- if ((1ull << arg.align) != access_size)
- return Errors::invalid("atomic memory op alignment"sv, access_size, 1ull << arg.align);
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(atomic_load)
-{
- auto const& arg = instruction.arguments().get<Instruction::AtomicMemoryArgument>();
- auto memory = TRY(validate(arg.memory.memory_index));
- TRY(validate_atomic_memory_argument(arg.memory, arg.access_size()));
-
- TRY((take_memory_address(stack, memory, arg.memory)));
- stack.append(arg.value_type());
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(atomic_store)
-{
- auto const& arg = instruction.arguments().get<Instruction::AtomicMemoryArgument>();
- auto memory = TRY(validate(arg.memory.memory_index));
- TRY(validate_atomic_memory_argument(arg.memory, arg.access_size()));
-
- TRY(stack.take(arg.value_type()));
- TRY((take_memory_address(stack, memory, arg.memory)));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(atomic_rmw)
-{
- auto const& arg = instruction.arguments().get<Instruction::AtomicMemoryArgument>();
- auto memory = TRY(validate(arg.memory.memory_index));
- TRY(validate_atomic_memory_argument(arg.memory, arg.access_size()));
-
- TRY(stack.take(arg.value_type()));
- TRY((take_memory_address(stack, memory, arg.memory)));
- stack.append(arg.value_type());
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(atomic_rmw_cmpxchg)
-{
- auto const& arg = instruction.arguments().get<Instruction::AtomicMemoryArgument>();
- auto memory = TRY(validate(arg.memory.memory_index));
- TRY(validate_atomic_memory_argument(arg.memory, arg.access_size()));
-
- TRY(stack.take(arg.value_type())); // replacement
- TRY(stack.take(arg.value_type())); // expected
- TRY((take_memory_address(stack, memory, arg.memory)));
- stack.append(arg.value_type());
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_atomic_notify)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- auto memory = TRY(validate(arg.memory_index));
- TRY(validate_atomic_memory_argument(arg, sizeof(i32)));
-
- TRY((stack.take<ValueType::I32>())); // count
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I32));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_atomic_wait32)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- auto memory = TRY(validate(arg.memory_index));
- TRY(validate_atomic_memory_argument(arg, sizeof(i32)));
-
- TRY((stack.take<ValueType::I64>())); // timeout
- TRY((stack.take<ValueType::I32>())); // expected
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I32));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(memory_atomic_wait64)
-{
- auto const& arg = instruction.arguments().get<Instruction::MemoryArgument>();
- auto memory = TRY(validate(arg.memory_index));
- TRY(validate_atomic_memory_argument(arg, sizeof(i64)));
-
- TRY((stack.take<ValueType::I64>())); // timeout
- TRY((stack.take<ValueType::I64>())); // expected
- TRY((take_memory_address(stack, memory, arg)));
- stack.append(ValueType(ValueType::I32));
-
- return {};
-}
-
-VALIDATE_INSTRUCTION(atomic_fence)
-{
- return {};
-}
-
-ErrorOr<void, ValidationError> Validator::validate(Instruction const& instruction, Stack& stack, bool& is_constant)
-{
- switch (instruction.opcode().value()) {
-#define M(name, integer_value, ...) \
- case Instructions::name.value(): \
- dbgln_if(WASM_VALIDATOR_DEBUG, "checking {}, stack = {}", #name, stack); \
- return validate_instruction<integer_value>(instruction, stack, is_constant);
-
- ENUMERATE_WASM_OPCODES(M)
-
-#undef M
- default:
- is_constant = false;
- return Errors::invalid(ByteString::formatted("instruction opcode ({:#x})", instruction.opcode().value()));
- }
-}
-
-ErrorOr<Validator::ExpressionTypeResult, ValidationError> Validator::validate(Expression const& expression, Vector<ValueType> const& result_types, Span<CodeSection::Func const* const> callee_bodies, size_t current_function_index)
-{
- if (m_frames.is_empty())
- m_frames.empend(FunctionType { {}, result_types }, FrameKind::Function, (size_t)0);
- auto stack = Stack(m_frames, m_context.type_context());
- bool is_constant_expression = true;
-
- for (auto& instruction : expression.instructions()) {
- bool is_constant = false;
- TRY(validate(instruction, stack, is_constant));
-
- is_constant_expression &= is_constant;
- }
-
- auto expected_result_types = result_types;
- while (!expected_result_types.is_empty())
- TRY(stack.take(expected_result_types.take_last()));
-
- for (auto& type : result_types)
- stack.append(type);
- m_frames.take_last();
-
- expression.set_stack_usage_hint(stack.max_known_size());
-
- VERIFY(m_frames.is_empty());
-
- // Now that we're in happy land, try to compile the expression down to a list of labels to help dispatch.
- expression.compiled_instructions = try_compile_instructions(expression, m_context.functions.span(), callee_bodies, current_function_index, m_context.locals.size(), m_context.imported_function_count);
-
- if (expression.compiled_instructions.direct && !is_constant_expression) {
- bool has_unsupported_types = false;
- for (auto& type : m_context.locals) {
- if (type.is_reference() || type.kind() == ValueType::V128) {
- has_unsupported_types = true;
- break;
- }
- }
- if (!has_unsupported_types) {
- for (auto& type : result_types) {
- if (type.is_reference() || type.kind() == ValueType::V128) {
- has_unsupported_types = true;
- break;
- }
- }
- }
- // Also skip 64-bit addressing (cranelift truncates base to u32).
- if (!has_unsupported_types) {
- for (auto& mem : m_context.memories) {
- if (mem.limits().address_type() == AddressType::I64) {
- has_unsupported_types = true;
- break;
- }
- }
- }
- // Also skip if any call targets a function with multi-value returns.
- if (!has_unsupported_types) {
- for (auto& insn : expression.instructions()) {
- if (insn.opcode() == Instructions::call) {
- auto func_idx = insn.arguments().get<FunctionIndex>().value();
- if (func_idx < m_context.functions.size() && m_context.functions[func_idx].results().size() > 1) {
- has_unsupported_types = true;
- break;
- }
- }
- }
- }
- // Also skip multi-value return functions.
- if (!has_unsupported_types && result_types.size() <= 1) {
- expression.compiled_instructions.cranelift_eligible = true;
- expression.compiled_instructions.cranelift_result_arity = static_cast<u32>(result_types.size());
- expression.compiled_instructions.cranelift_local_count = static_cast<u32>(m_context.locals.size()) + expression.compiled_instructions.cranelift_inlined_locals;
- expression.compiled_instructions.cranelift_param_count = static_cast<u32>(m_context.current_function_parameter_count);
- expression.compiled_instructions.cranelift_local_types.ensure_capacity(m_context.locals.size());
- for (auto& type : m_context.locals)
- expression.compiled_instructions.cranelift_local_types.unchecked_append(to_underlying(type.kind()));
- }
- }
-
- return ExpressionTypeResult { stack.release_vector(), is_constant_expression };
-}
-
-ByteString Validator::Errors::find_instruction_name(SourceLocation const& location)
-{
- auto index = location.function_name().find('<');
- auto end_index = location.function_name().find('>');
- if (!index.has_value() || !end_index.has_value())
- return ByteString::formatted("{}", location);
-
- auto opcode = location.function_name().substring_view(index.value() + 1, end_index.value() - index.value() - 1).to_number<unsigned>();
- if (!opcode.has_value())
- return ByteString::formatted("{}", location);
-
- return instruction_name(OpCode { *opcode });
-}
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/Validator.h b/Libraries/LibWasm/AbstractMachine/Validator.h
deleted file mode 100644
index 328170305be..00000000000
--- a/Libraries/LibWasm/AbstractMachine/Validator.h
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/COWVector.h>
-#include <AK/Debug.h>
-#include <AK/RedBlackTree.h>
-#include <AK/SourceLocation.h>
-#include <AK/Tuple.h>
-#include <AK/Vector.h>
-#include <LibWasm/Forward.h>
-#include <LibWasm/TypeSystem.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-struct Context {
- struct RefRBTree : RefCounted<RefRBTree> {
- RedBlackTree<size_t, FunctionIndex> tree;
- };
-
- COWVector<TypeSection::Type> types;
- COWVector<DefinedType const*> canonical_types;
- COWVector<FunctionType> functions;
- COWVector<Optional<TypeIndex>> function_type_indices;
- COWVector<StructType> structs;
- COWVector<ArrayType> arrays;
- COWVector<TableType> tables;
- COWVector<MemoryType> memories;
- COWVector<GlobalType> globals;
- COWVector<ValueType> elements;
- COWVector<bool> datas;
- COWVector<ValueType> locals;
- COWVector<TagType> tags;
- Optional<u32> data_count;
- RefPtr<RefRBTree> references { make_ref_counted<RefRBTree>() };
- size_t imported_function_count { 0 };
- size_t current_function_parameter_count { 0 };
-
- TypeContext type_context() const { return TypeContext { canonical_types.span() }; }
-};
-
-struct ValidationError : public Error {
- ValidationError(ByteString error)
- : Error(Error::from_string_view(error.view()))
- , error_string(move(error))
- {
- }
-
- ByteString error_string;
-};
-
-class Validator {
- AK_MAKE_NONCOPYABLE(Validator);
- AK_MAKE_NONMOVABLE(Validator);
-
-public:
- Validator() = default;
-
- [[nodiscard]] Validator fork() const
- {
- return Validator { m_context };
- }
-
- // Module
- ErrorOr<void, ValidationError> validate(Module&);
- ErrorOr<void, ValidationError> validate(ImportSection const&);
- ErrorOr<void, ValidationError> validate(ExportSection const&);
- ErrorOr<void, ValidationError> validate(StartSection const&);
- ErrorOr<void, ValidationError> validate(DataSection const&);
- ErrorOr<void, ValidationError> validate(ElementSection const&);
- ErrorOr<void, ValidationError> validate(GlobalSection const&);
- ErrorOr<void, ValidationError> validate(MemorySection const&);
- ErrorOr<void, ValidationError> validate(TableSection const&);
- ErrorOr<void, ValidationError> validate(CodeSection const&);
- ErrorOr<void, ValidationError> validate(TagSection const&);
- ErrorOr<void, ValidationError> validate(FunctionSection const&) { return {}; }
- ErrorOr<void, ValidationError> validate(DataCountSection const&) { return {}; }
- ErrorOr<void, ValidationError> validate(TypeSection const&);
- ErrorOr<void, ValidationError> validate(CustomSection const&) { return {}; }
-
- ErrorOr<void, ValidationError> validate(TypeIndex index) const
- {
- if (index.value() < m_context.types.size())
- return {};
- return Errors::invalid("TypeIndex"sv);
- }
-
- ErrorOr<void, ValidationError> validate(FunctionIndex index) const
- {
- if (index.value() < m_context.functions.size())
- return {};
- return Errors::invalid("FunctionIndex"sv);
- }
-
- ErrorOr<MemoryType, ValidationError> validate(MemoryIndex index) const
- {
- if (index.value() < m_context.memories.size())
- return m_context.memories[index.value()];
- return Errors::invalid("MemoryIndex"sv);
- }
-
- ErrorOr<void, ValidationError> validate(ElementIndex index) const
- {
- if (index.value() < m_context.elements.size())
- return {};
- return Errors::invalid("ElementIndex"sv);
- }
-
- ErrorOr<void, ValidationError> validate(DataIndex index) const
- {
- if (index.value() < m_context.datas.size())
- return {};
- return Errors::invalid("DataIndex"sv);
- }
-
- ErrorOr<void, ValidationError> validate(GlobalIndex index) const
- {
- if (index.value() < m_context.globals.size())
- return {};
- return Errors::invalid("GlobalIndex"sv);
- }
-
- ErrorOr<void, ValidationError> validate(LabelIndex index) const
- {
- if (index.value() < m_frames.size())
- return {};
- return Errors::invalid("LabelIndex"sv);
- }
-
- ErrorOr<LocalIndex, ValidationError> validate(LocalIndex index) const
- {
- if (index.value() < m_context.locals.size())
- return index;
- return Errors::invalid("LocalIndex"sv);
- }
-
- ErrorOr<TableType, ValidationError> validate(TableIndex index) const
- {
- if (index.value() < m_context.tables.size())
- return m_context.tables[index.value()];
- return Errors::invalid("TableIndex"sv);
- }
-
- ErrorOr<void, ValidationError> validate(TagIndex index) const
- {
- if (index.value() < m_context.tags.size())
- return {};
- return Errors::invalid("TagIndex"sv);
- }
-
- enum class FrameKind {
- Block,
- Loop,
- If,
- Else,
- Function,
- TryTable,
- };
-
- struct Frame {
- FunctionType type;
- FrameKind kind;
- size_t initial_size;
- // Stack polymorphism is handled with this field
- bool unreachable { false };
- // Height of the local-initialization undo log when this frame was entered.
- // https://webassembly.github.io/spec/core/appendix/algorithm.html
- size_t local_init_log_height { 0 };
-
- Vector<ValueType> const& labels() const
- {
- return kind != FrameKind::Loop ? type.results() : type.parameters();
- }
- };
-
- // Instructions
- struct StackEntry {
- StackEntry(ValueType type)
- : concrete_type(type)
- , is_known(true)
- {
- }
-
- explicit StackEntry()
- : concrete_type(ValueType::I32)
- , is_known(false)
- {
- }
-
- bool is_of_kind(ValueType::Kind kind) const
- {
- if (is_known)
- return concrete_type.kind() == kind;
- return true;
- }
-
- bool is_numeric() const { return !is_known || concrete_type.is_numeric(); }
- bool is_reference() const { return !is_known || concrete_type.is_reference(); }
-
- static bool is_subtype_of(ValueType const& concrete, ValueType const& expected)
- {
- if (concrete == expected)
- return true;
- // A typed function reference (ref [$null] $t) is a subtype of (ref [$null] func) when nullability is compatible.
- if (expected.kind() == ValueType::FunctionReference && concrete.is_typeuse()
- && (expected.is_nullable() || !concrete.is_nullable()))
- return true;
- // A non-nullable reference is a subtype of its nullable counterpart.
- if (expected.is_nullable() && !concrete.is_nullable()) {
- auto nullable_concrete = concrete;
- nullable_concrete.set_nullable(true);
- return nullable_concrete == expected;
- }
- return false;
- }
-
- bool operator==(ValueType const& other) const
- {
- if (!is_known)
- return true;
- return is_subtype_of(concrete_type, other);
- }
-
- bool operator==(StackEntry const& other) const
- {
- if (!is_known || !other.is_known)
- return true;
- return is_subtype_of(concrete_type, other.concrete_type);
- }
-
- ValueType concrete_type;
- bool is_known { true };
- };
-
- // This is a wrapper that can model "polymorphic" stacks,
- // by treating unknown stack entries as a potentially infinite number of entries
- class Stack {
- template<typename, typename>
- friend struct AK::Formatter;
-
- public:
- explicit Stack(Vector<Frame, 16>&&, TypeContext const&) = delete;
-
- explicit Stack(Vector<Frame, 16> const& frames, TypeContext const& type_context)
- : m_frames(frames)
- , m_type_context(type_context)
- {
- }
-
- TypeContext const& type_context() const { return m_type_context; }
-
- bool is_empty() const { return m_entries.is_empty(); }
- auto& last() const { return m_entries.last(); }
- auto& last() { return m_entries.last(); }
- auto& at(size_t index) const { return m_entries.at(index); }
- auto& at(size_t index) { return m_entries.at(index); }
- size_t size() const { return m_entries.size(); }
- void resize(size_t size)
- {
- m_entries.resize(size);
- m_max_known_size = max(m_max_known_size, size);
- }
-
- ErrorOr<StackEntry, ValidationError> take_last()
- {
- if (size() == m_frames.last().initial_size && m_frames.last().unreachable)
- return StackEntry();
- if (size() == m_frames.last().initial_size)
- return Errors::invalid("stack state"sv, "<any>"sv, "<nothing>"sv);
- return m_entries.take_last();
- }
- void append(StackEntry entry)
- {
- m_entries.append(entry);
- m_max_known_size = max(m_max_known_size, size());
- }
-
- ErrorOr<StackEntry, ValidationError> take(ValueType type, SourceLocation location = SourceLocation::current())
- {
- auto type_on_stack = TRY(take_last());
- if (type_on_stack.is_known && !matches_value_type(type_on_stack.concrete_type, type, m_type_context))
- return Errors::invalid("stack state"sv, type, type_on_stack, location);
-
- return type_on_stack;
- }
-
- template<auto... kinds>
- ErrorOr<void, ValidationError> take(SourceLocation location = SourceLocation::current())
- {
- for (auto kind : { kinds... })
- TRY(take(Wasm::ValueType(kind), location));
- return {};
- }
- template<auto... kinds>
- ErrorOr<void, ValidationError> take_and_put(Wasm::ValueType::Kind kind, SourceLocation location = SourceLocation::current())
- {
- TRY(take<kinds...>(location));
- append(Wasm::ValueType(kind));
- return {};
- }
-
- Vector<StackEntry, 8> release_vector()
- {
- m_max_known_size = 0;
- return exchange(m_entries, {});
- }
-
- size_t max_known_size() const { return m_max_known_size; }
-
- private:
- Vector<StackEntry, 8> m_entries;
- Vector<Frame, 16> const& m_frames;
- TypeContext m_type_context;
- size_t m_max_known_size { 0 };
- };
-
- struct ExpressionTypeResult {
- Vector<StackEntry> result_types;
- bool is_constant { false };
- };
- ErrorOr<ExpressionTypeResult, ValidationError> validate(Expression const&, Vector<ValueType> const&, Span<CodeSection::Func const* const> callee_bodies = {}, size_t current_function_index = 0);
- ErrorOr<void, ValidationError> validate(Instruction const& instruction, Stack& stack, bool& is_constant);
- template<u64 opcode>
- ErrorOr<void, ValidationError> validate_instruction(Instruction const&, Stack& stack, bool& is_constant);
-
- // Types
- ErrorOr<void, ValidationError> validate(Limits const&, Optional<u64> bound); // n <= bound && m? <= bound
- ErrorOr<FunctionType, ValidationError> validate(BlockType const&);
- ErrorOr<void, ValidationError> validate(FunctionType const&);
- ErrorOr<void, ValidationError> validate(StructType const&);
- ErrorOr<void, ValidationError> validate(ArrayType const&);
- ErrorOr<void, ValidationError> validate(TableType const&);
- ErrorOr<void, ValidationError> validate(MemoryType const&);
- ErrorOr<void, ValidationError> validate(GlobalType const&);
- ErrorOr<void, ValidationError> validate(TagType const&);
- ErrorOr<void, ValidationError> validate(ValueType const&);
- ErrorOr<void, ValidationError> validate(TypeSection::Type const&, size_t this_type_index);
-
- // Proposal 'memory64'
- ErrorOr<void, ValidationError> take_memory_address(Stack& stack, MemoryType const& memory, Instruction::MemoryArgument const& arg)
- {
- if (memory.limits().address_type() == AddressType::I64) {
- TRY((stack.take<ValueType::I64>()));
- } else {
- if (arg.offset > NumericLimits<u32>::max())
- return Errors::out_of_bounds("memory op offset"sv, arg.offset, 0, NumericLimits<u32>::max());
- TRY((stack.take<ValueType::I32>()));
- }
- return {};
- }
-
-private:
- explicit Validator(Context context)
- : m_context(move(context))
- {
- }
-
- ErrorOr<void, ValidationError> validate_atomic_memory_argument(Instruction::MemoryArgument const&, size_t access_size);
- ErrorOr<void, ValidationError> validate_struct_get(Stack&, Instruction const&, bool requires_packed);
- ErrorOr<FieldType, ValidationError> array_field_type(TypeIndex, StringView instruction_name, bool requires_mutable);
- ErrorOr<void, ValidationError> validate_array_get(Stack&, Instruction const&, bool requires_packed);
- ErrorOr<void, ValidationError> validate_ref_test_or_cast(Stack&, Instruction const&);
- ErrorOr<void, ValidationError> validate_br_on_cast(Stack&, Instruction const&, bool branch_on_failure);
-
- struct Errors {
- static ValidationError invalid(StringView name, SourceLocation location = SourceLocation::current())
- {
- if constexpr (WASM_VALIDATOR_DEBUG)
- return ByteString::formatted("Invalid {} in {}", name, find_instruction_name(location));
- else
- return ByteString::formatted("Invalid {}", name);
- }
-
- template<typename Expected, typename Given>
- static ValidationError invalid(StringView name, Expected expected, Given given, SourceLocation location = SourceLocation::current())
- {
- if constexpr (WASM_VALIDATOR_DEBUG)
- return ByteString::formatted("Invalid {} in {}, expected {} but got {}", name, find_instruction_name(location), expected, given);
- else
- return ByteString::formatted("Invalid {}, expected {} but got {}", name, expected, given);
- }
-
- template<typename... Args>
- static ValidationError non_conforming_types(StringView name, Args... args)
- {
- return ByteString::formatted("Non-conforming types for {}: {}", name, Vector { args... });
- }
-
- static ValidationError duplicate_export_name(StringView name) { return ByteString::formatted("Duplicate exported name '{}'", name); }
- static ValidationError multiple_start_sections() { return ByteString("Found multiple start sections"sv); }
- static ValidationError stack_height_mismatch(Stack const& stack, size_t expected_height) { return ByteString::formatted("Stack height mismatch, got {} but expected length {}", stack, expected_height); }
-
- template<typename T, typename U, typename V>
- static ValidationError out_of_bounds(StringView name, V value, T min, U max) { return ByteString::formatted("Value {} for {} is out of bounds ({},{})", value, name, min, max); }
-
- template<typename... Expected>
- static ValidationError invalid_stack_state(Stack const& stack, Tuple<Expected...> expected, SourceLocation location = SourceLocation::current())
- {
- constexpr size_t count = expected.size();
- StringBuilder builder;
- if constexpr (WASM_VALIDATOR_DEBUG)
- builder.appendff("Invalid stack state in {}: ", find_instruction_name(location));
- else
- builder.appendff("Invalid stack state in <unknown>: ");
-
- builder.append("Expected [ "sv);
-
- expected.apply_as_args([&]<typename... Ts>(Ts const&... args) {
- (builder.appendff("{} ", args), ...);
- });
-
- builder.append("], but found [ "sv);
-
- auto actual_size = stack.size();
- for (size_t i = 1; i <= min(count, actual_size); ++i) {
- auto& entry = stack.at(actual_size - i);
- if (entry.is_known) {
- builder.appendff("{} ", entry.concrete_type);
- } else {
- builder.appendff("<polymorphic stack>");
- break;
- }
- }
- builder.append(']');
- return { builder.to_byte_string() };
- }
-
- private:
- static ByteString find_instruction_name(SourceLocation const&);
- };
-
- // https://webassembly.github.io/spec/core/valid/conventions.html#local-types
- void push_frame(Frame frame)
- {
- frame.local_init_log_height = m_local_init_log.size();
- m_frames.append(move(frame));
- }
- void mark_local_initialized(u32 local_index)
- {
- if (m_local_initialized[local_index])
- return;
- m_local_initialized[local_index] = true;
- m_local_init_log.append(local_index);
- }
- void roll_back_local_initializations(size_t log_height)
- {
- while (m_local_init_log.size() > log_height)
- m_local_initialized[m_local_init_log.take_last()] = false;
- }
-
- Context m_context;
- Vector<Frame, 16> m_frames;
- Vector<bool> m_local_initialized;
- Vector<u32> m_local_init_log;
- COWVector<GlobalType> m_globals_without_internal_globals;
-};
-
-}
-
-template<>
-struct AK::Formatter<Wasm::Validator::StackEntry> : public AK::Formatter<StringView> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Validator::StackEntry const& value)
- {
- if (value.is_known)
- return Formatter<StringView>::format(builder, value.concrete_type.kind_name());
-
- return Formatter<StringView>::format(builder, "<unknown>"sv);
- }
-};
-
-template<>
-struct AK::Formatter<Wasm::Validator::Stack> : public AK::Formatter<Vector<Wasm::Validator::StackEntry>> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Validator::Stack const& value)
- {
- return Formatter<Vector<Wasm::Validator::StackEntry>>::format(builder, value.m_entries);
- }
-};
-
-template<>
-struct AK::Formatter<Wasm::ValueType> : public AK::Formatter<StringView> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::ValueType const& value)
- {
- return Formatter<StringView>::format(builder, value.kind_name());
- }
-};
-
-template<>
-struct AK::Formatter<Wasm::ValidationError> : public AK::Formatter<StringView> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::ValidationError const& error)
- {
- return Formatter<StringView>::format(builder, error.error_string);
- }
-};
-
-template<>
-struct AK::Formatter<Wasm::TypeSection::Type> : public AK::Formatter<StringView> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::TypeSection::Type const& type)
- {
- return Formatter<StringView>::format(builder, type.name());
- }
-};
diff --git a/Libraries/LibWasm/AbstractMachine/ValueStack.cpp b/Libraries/LibWasm/AbstractMachine/ValueStack.cpp
deleted file mode 100644
index 85de15eab34..00000000000
--- a/Libraries/LibWasm/AbstractMachine/ValueStack.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Vector.h>
-#include <AK/kmalloc.h>
-#include <LibWasm/AbstractMachine/ValueStack.h>
-
-#if defined(AK_OS_WINDOWS)
-# include <windows.h>
-#else
-# include <sys/mman.h>
-#endif
-
-namespace Wasm {
-
-namespace {
-
-void* allocate_region()
-{
-#if defined(AK_OS_WINDOWS)
- auto* region = VirtualAlloc(nullptr, ValueStack::reservation_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
- VERIFY(region);
-#else
- auto* region = mmap(nullptr, ValueStack::reservation_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
- VERIFY(region != MAP_FAILED);
-#endif
- return region;
-}
-
-void free_region(void* region)
-{
-#if defined(AK_OS_WINDOWS)
- VirtualFree(region, 0, MEM_RELEASE);
-#else
- munmap(region, ValueStack::reservation_size);
-#endif
-}
-
-// The pool is intentionally leaked at thread exit to avoid unmapping during teardown.
-struct RegionPool {
- AK_ALLOC_WITH_KMALLOC;
-
- static constexpr size_t max_pooled_regions = 4;
- Vector<void*, max_pooled_regions> regions;
-};
-
-RegionPool& region_pool()
-{
- static thread_local auto* pool = new RegionPool;
- return *pool;
-}
-
-}
-
-ValueStack::ValueStack()
-{
- auto& pool = region_pool();
- void* region = pool.regions.is_empty() ? allocate_region() : pool.regions.take_last();
- m_base = static_cast<Value*>(region);
- m_top = m_base;
- m_limit = m_base + max_values;
-}
-
-ValueStack::~ValueStack()
-{
- auto& pool = region_pool();
- if (pool.regions.size() < RegionPool::max_pooled_regions)
- pool.regions.unchecked_append(m_base);
- else
- free_region(m_base);
-}
-
-void ValueStack::reset_and_clear()
-{
- m_top = m_base;
- for (size_t i = 0; i < conservative_scan_slack; ++i)
- m_base[i] = Value(0);
-}
-
-}
diff --git a/Libraries/LibWasm/AbstractMachine/ValueStack.h b/Libraries/LibWasm/AbstractMachine/ValueStack.h
deleted file mode 100644
index d8cef08f632..00000000000
--- a/Libraries/LibWasm/AbstractMachine/ValueStack.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Noncopyable.h>
-#include <AK/Span.h>
-#include <AK/Types.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/Export.h>
-
-namespace Wasm {
-
-// A fixed reservation keeps the backing stable for compiled code and is recycled between calls.
-class WASM_API ValueStack {
- AK_MAKE_NONCOPYABLE(ValueStack);
- AK_MAKE_NONMOVABLE(ValueStack);
-
-public:
- static constexpr size_t reservation_size = 64 * MiB;
- static constexpr size_t max_values = reservation_size / sizeof(Value);
-
- ValueStack();
- ~ValueStack();
-
- ALWAYS_INLINE size_t size() const { return static_cast<size_t>(m_top - m_base); }
- ALWAYS_INLINE bool is_empty() const { return m_top == m_base; }
-
- ALWAYS_INLINE void append(Value value)
- {
- VERIFY(m_top != m_limit);
- *m_top++ = value;
- }
- ALWAYS_INLINE void unchecked_append(Value value) { *m_top++ = value; }
-
- ALWAYS_INLINE Value take_last()
- {
- VERIFY(m_top != m_base);
- return *--m_top;
- }
- ALWAYS_INLINE Value unsafe_take_last() { return *--m_top; }
- ALWAYS_INLINE Value& last() { return *(m_top - 1); }
- ALWAYS_INLINE Value& unsafe_last() { return *(m_top - 1); }
-
- ALWAYS_INLINE Value* data() { return m_base; }
- ALWAYS_INLINE Value const* data() const { return m_base; }
- ALWAYS_INLINE Value* begin() { return m_base; }
- ALWAYS_INLINE Value* end() { return m_top; }
- ALWAYS_INLINE Value const* begin() const { return m_base; }
- ALWAYS_INLINE Value const* end() const { return m_top; }
- ALWAYS_INLINE Span<Value> span() { return { m_base, size() }; }
- ALWAYS_INLINE ReadonlySpan<Value> span() const { return { m_base, size() }; }
-
- ALWAYS_INLINE void shrink(size_t new_size, bool = false) // mirroring keep_capacity, ignored
- {
- VERIFY(new_size <= size());
- m_top = m_base + new_size;
- }
-
- ALWAYS_INLINE void restore_size(size_t size)
- {
- VERIFY(size <= max_values);
- m_top = m_base + size;
- }
- void reset_and_clear();
-
- void remove(size_t index, size_t count)
- {
- VERIFY(index + count <= size());
- __builtin_memmove(m_base + index, m_base + index + count, (size() - index - count) * sizeof(Value));
- m_top -= count;
- }
-
- ALWAYS_INLINE void ensure_capacity(size_t total) { VERIFY(total <= max_values); }
-
- ALWAYS_INLINE Value* allocate(size_t count)
- {
- VERIFY(static_cast<size_t>(m_limit - m_top) >= count);
- auto* result = m_top;
- m_top += count;
- return result;
- }
- ALWAYS_INLINE Value* mark() const { return m_top; }
- ALWAYS_INLINE void release_to(Value* mark)
- {
- VERIFY(mark >= m_base && mark <= m_top);
- m_top = mark;
- }
-
- // The conservative GC scans a little past the top;
- // a value handed out by unsafe_take_last() can still be live in a caller's register when a collection runs.
- size_t conservative_scan_size() const { return min(size() + conservative_scan_slack, max_values); }
-
- static constexpr size_t base_offset() { return __builtin_offsetof(ValueStack, m_base); }
- static constexpr size_t top_offset() { return __builtin_offsetof(ValueStack, m_top); }
-
-private:
- static constexpr size_t conservative_scan_slack = 8;
-
- Value* m_base { nullptr };
- Value* m_top { nullptr };
- Value* m_limit { nullptr };
-};
-
-}
diff --git a/Libraries/LibWasm/CMakeLists.txt b/Libraries/LibWasm/CMakeLists.txt
index 20891c703cb..a897beeae8b 100644
--- a/Libraries/LibWasm/CMakeLists.txt
+++ b/Libraries/LibWasm/CMakeLists.txt
@@ -1,72 +1,13 @@
set(SOURCES
- AbstractMachine/AbstractMachine.cpp
- AbstractMachine/BytecodeInterpreter.cpp
- AbstractMachine/Configuration.cpp
- AbstractMachine/Validator.cpp
- AbstractMachine/ValueStack.cpp
- Parser/Parser.cpp
- Printer/Printer.cpp
- TypeSystem.cpp
+ Runtime.cpp
)
-# FIXME: Add Windows support
-if (NOT WIN32)
- list(APPEND SOURCES WASI/Wasi.cpp)
-endif()
-
-set(WASM_COMPILED_FAULT_RECOVERY_SUPPORTED 0)
-
-if(WIN32 AND (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64|aarch64|ARM64|arm64)$"))
- set(WASM_COMPILED_FAULT_RECOVERY_SUPPORTED 1)
-elseif(APPLE)
- set(WASM_COMPILED_FAULT_RECOVERY_SUPPORTED 1)
-elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|aarch64)$"))
- set(WASM_COMPILED_FAULT_RECOVERY_SUPPORTED 1)
-endif()
-
-if (ENABLE_CRANELIFT_JIT)
- list(APPEND SOURCES CraneliftBridge.cpp)
- build_rust_binary(
- MANIFEST_PATH Rust/Cargo.toml
- CRATE_NAME libwasm_cranelift
- BINARY_NAME cranelift-compiler
- OUTPUT_PATH_VAR WASM_CRANELIFT_COMPILER_BINARY
- FFI_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}"
- )
-else()
- list(APPEND SOURCES CraneliftStubs.cpp)
-endif()
-
ladybird_lib(LibWasm wasm EXPLICIT_SYMBOL_EXPORT)
-target_link_libraries(LibWasm PRIVATE LibCore LibFileSystem PUBLIC LibGC)
-target_compile_definitions(LibWasm PRIVATE
- WASM_COMPILED_FAULT_RECOVERY_SUPPORTED=${WASM_COMPILED_FAULT_RECOVERY_SUPPORTED}
-)
-
-if (ENABLE_CRANELIFT_JIT)
- if (APPLE)
- # The compiler handles untrusted WebAssembly, so it runs with the hardened runtime like the helpers.
- set(cranelift_compiler_signed_stamp "${CMAKE_CURRENT_BINARY_DIR}/cranelift_compiler_signed.stamp")
- add_custom_command(
- OUTPUT "${cranelift_compiler_signed_stamp}"
- COMMAND codesign -s - -f -o runtime "${WASM_CRANELIFT_COMPILER_BINARY}"
- COMMAND "${CMAKE_COMMAND}" -E touch "${cranelift_compiler_signed_stamp}"
- DEPENDS "${WASM_CRANELIFT_COMPILER_BINARY}"
- VERBATIM
- )
- add_custom_target(cranelift-compiler-sign DEPENDS "${cranelift_compiler_signed_stamp}")
- add_dependencies(cranelift-compiler-sign cranelift-compiler-build)
- add_dependencies(LibWasm cranelift-compiler-sign)
- endif()
- add_dependencies(LibWasm cranelift-compiler-build)
- target_include_directories(LibWasm PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")
- target_compile_definitions(LibWasm PRIVATE
- WASM_CRANELIFT=1
- WASM_CRANELIFT_COMPILER_PATH="${WASM_CRANELIFT_COMPILER_BINARY}"
- )
+import_rust_crate(MANIFEST_PATH Engine/Cargo.toml CRATE_NAME libwasm_engine FEATURES allocator FFI_HEADER RustFFI.h)
+target_link_libraries(LibWasm PRIVATE libwasm_engine PUBLIC LibGC)
+if ((LINUX OR BSD) AND NOT BUILD_SHARED_LIBS)
+ target_link_options(LibWasm INTERFACE LINKER:--allow-multiple-definition)
endif()
-add_subdirectory(Runtime)
-
include(wasm_spec_tests)
diff --git a/Libraries/LibWasm/Constants.h b/Libraries/LibWasm/Constants.h
deleted file mode 100644
index 3de19c91f0f..00000000000
--- a/Libraries/LibWasm/Constants.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Types.h>
-
-namespace Wasm::Constants {
-
-// Number types
-static constexpr auto i32_tag = 0x7f;
-static constexpr auto i64_tag = 0x7e;
-static constexpr auto f32_tag = 0x7d;
-static constexpr auto f64_tag = 0x7c;
-
-// Vector types
-static constexpr auto v128_tag = 0x7b;
-
-// Heap types
-static constexpr auto exn_reference_tag = 0x69;
-static constexpr auto array_reference_tag = 0x6a;
-static constexpr auto struct_reference_tag = 0x6b;
-static constexpr auto i31_reference_tag = 0x6c;
-static constexpr auto eq_reference_tag = 0x6d;
-static constexpr auto any_reference_tag = 0x6e;
-static constexpr auto extern_reference_tag = 0x6f;
-static constexpr auto function_reference_tag = 0x70;
-static constexpr auto none_reference_tag = 0x71;
-static constexpr auto noextern_reference_tag = 0x72;
-static constexpr auto nofunc_reference_tag = 0x73;
-static constexpr auto noexn_reference_tag = 0x74;
-
-// Reference types
-static constexpr auto nullable_reference_tag_tag = 0x63;
-static constexpr auto non_nullable_reference_tag_tag = 0x64;
-
-// Composite types
-static constexpr auto array_tag = 0x5e;
-static constexpr auto struct_tag = 0x5f;
-static constexpr auto function_signature_tag = 0x60;
-static constexpr auto i16_tag = 0x77;
-static constexpr auto i8_tag = 0x78;
-
-// Recursive types
-static constexpr auto rec_group_tag = 0x4e;
-static constexpr auto sub_final_type_tag = 0x4f;
-static constexpr auto sub_type_tag = 0x50;
-
-// Global
-static constexpr auto const_tag = 0x00;
-static constexpr auto var_tag = 0x01;
-
-// Block
-static constexpr auto empty_block_tag = 0x40;
-
-// Import section
-static constexpr auto extern_function_tag = 0x00;
-static constexpr auto extern_table_tag = 0x01;
-static constexpr auto extern_memory_tag = 0x02;
-static constexpr auto extern_global_tag = 0x03;
-static constexpr auto extern_tag_tag = 0x04; // Proposal "exception-handling"
-
-static constexpr auto page_size = 64 * KiB;
-static constexpr u64 wasm32_max_pages = 1ull << 16;
-// FIXME: The compiled memory access path currently narrows memory64 addresses
-// to i32 before adding the memarg offset. Keep memory64 memories within
-// the currently supported address width until 64-bit memory accesses are
-// implemented there.
-static constexpr u64 wasm64_max_pages = wasm32_max_pages;
-static constexpr auto default_memory_reservation_size = 16 * MiB;
-// Compiled memory32 accesses to the default memory are unchecked: every memory32 memory reserves
-// the whole span such an access can reach - base (u32) plus memarg offset (u32) plus one page
-// for the access width - and anything past the committed size page-faults into a wasm trap.
-static constexpr u64 wasm32_guarded_reservation_size = (2 * (wasm32_max_pages * page_size)) + page_size;
-
-// Implementation-defined limits
-// These are not concretely defined by the spec, so the values are only defined by us.
-static constexpr auto minimum_stack_space_to_keep_free = 256 * KiB; // Note: Value is arbitrary and chosen by testing with ASAN
-static constexpr auto max_allowed_executed_instructions_per_call = 256 * 1024 * 1024;
-static constexpr auto max_allowed_vector_size = 500 * MiB;
-static constexpr auto max_allowed_table_size = 1024 * 1024;
-static constexpr auto max_allowed_function_locals_per_type = 42069; // Note: VERY arbitrary.
-
-// Messages used by the host
-static constexpr auto stack_exhaustion_message = "STACK-EXHAUSTION"sv;
-
-}
diff --git a/Libraries/LibWasm/CraneliftBridge.cpp b/Libraries/LibWasm/CraneliftBridge.cpp
deleted file mode 100644
index 17576e6cab9..00000000000
--- a/Libraries/LibWasm/CraneliftBridge.cpp
+++ /dev/null
@@ -1,1615 +0,0 @@
-/*
- * Copyright (c) 2026-present, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Array.h>
-#include <AK/ByteString.h>
-#include <AK/Checked.h>
-#include <AK/LexicalPath.h>
-#include <AK/NeverDestroyed.h>
-#include <AK/Platform.h>
-#include <AK/ScopeGuard.h>
-#include <AK/kmalloc.h>
-#include <CraneliftFFI.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibCore/Process.h>
-#include <LibCore/System.h>
-#include <LibFileSystem/FileSystem.h>
-#include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
-#include <LibWasm/AbstractMachine/Configuration.h>
-#include <LibWasm/Printer/Printer.h>
-#include <LibWasm/Types.h>
-#include <errno.h>
-#include <stdlib.h>
-
-#if defined(AK_OS_WINDOWS)
-# include <AK/Mutex.h>
-# include <AK/Windows.h>
-#else
-# include <fcntl.h>
-# include <sys/mman.h>
-# include <unistd.h>
-#endif
-
-#if defined(AK_OS_MACOS)
-# include <libkern/OSCacheControl.h>
-# include <pthread.h>
-#endif
-
-using namespace Wasm;
-using namespace Cranelift;
-
-namespace {
-
-struct InputHeader {
- u32 function_count;
- u32 layout_offset;
- u64 outcome_return;
- u64 output_size;
- u64 total_size;
-};
-
-struct InputFunctionEntry {
- u32 insn_offset;
- u32 insn_count;
- u32 result_arity;
- u32 num_locals;
- u32 locals_offset;
- u32 num_params;
-};
-
-static_assert(sizeof(InputHeader) == 32);
-static_assert(sizeof(InputFunctionEntry) == 24);
-
-struct OutputHeader {
- u32 function_count;
- u32 _pad;
- u64 code_base_offset;
- u64 reloc_region_start;
- u64 total_size;
-};
-
-struct OutputFunctionEntry {
- u64 code_offset;
- u32 code_size;
- u32 compiled;
- // Offset (relative to the start of the reloc region) and count of `HelperReloc`
- // entries describing the absolute helper addresses baked into this function's code.
- // On cache install we walk these and rewrite the 8 bytes at code+code_offset+offset
- // with the live address of helper N for the current process.
- u64 reloc_offset;
- u32 reloc_count;
- u32 _padding_after_reloc_count;
- u64 trap_offset;
- u32 trap_count;
- u32 _padding;
-};
-
-static_assert(sizeof(OutputHeader) == 32);
-static_assert(sizeof(OutputFunctionEntry) == 48);
-static_assert(offsetof(OutputFunctionEntry, trap_offset) == 32);
-
-struct CodeMapping {
- AK_ALLOC_WITH_KMALLOC;
-
- void* mapping;
- size_t size;
- Vector<CraneliftTrap> traps;
-};
-
-static constexpr size_t oop_code_region_min_size = 256 * KiB;
-static constexpr size_t oop_code_bytes_per_insn = 256;
-static constexpr size_t oop_reloc_region_min_size = 64 * KiB;
-static constexpr size_t oop_reloc_bytes_per_insn = 128;
-
-static size_t align_up(size_t value, size_t alignment)
-{
- VERIFY(alignment > 0);
- auto remainder = value % alignment;
- return remainder == 0 ? value : value + (alignment - remainder);
-}
-
-static ErrorOr<size_t> try_align_up(size_t value, size_t alignment)
-{
- VERIFY(alignment > 0);
- auto remainder = value % alignment;
- if (remainder == 0)
- return value;
-
- Checked<size_t> result = value;
- result += alignment - remainder;
- if (result.has_overflow())
- return Error::from_string_literal("Cranelift output size overflow");
- return result.value();
-}
-
-static ErrorOr<size_t> compute_output_buffer_size(size_t function_count, size_t instruction_count)
-{
- Checked<size_t> output_entries_size = sizeof(OutputFunctionEntry);
- output_entries_size *= function_count;
- if (output_entries_size.has_overflow())
- return Error::from_string_literal("Cranelift output size overflow");
-
- Checked<size_t> output_size = sizeof(OutputHeader);
- output_size += output_entries_size.value();
- if (output_size.has_overflow())
- return Error::from_string_literal("Cranelift output size overflow");
-
- output_size = TRY(try_align_up(output_size.value(), SERIALIZED_CODE_ALIGNMENT));
-
- Checked<size_t> maximum_code_size = instruction_count;
- maximum_code_size *= oop_code_bytes_per_insn;
- if (maximum_code_size.has_overflow())
- return Error::from_string_literal("Cranelift output size overflow");
-
- output_size += max(oop_code_region_min_size, maximum_code_size.value());
- if (output_size.has_overflow())
- return Error::from_string_literal("Cranelift output size overflow");
-
- output_size = TRY(try_align_up(output_size.value(), alignof(HelperReloc)));
-
- Checked<size_t> maximum_reloc_size = instruction_count;
- maximum_reloc_size *= oop_reloc_bytes_per_insn;
- if (maximum_reloc_size.has_overflow())
- return Error::from_string_literal("Cranelift output size overflow");
-
- output_size += max(oop_reloc_region_min_size, maximum_reloc_size.value());
- if (output_size.has_overflow())
- return Error::from_string_literal("Cranelift output is too large");
-
- return output_size.value();
-}
-
-struct BatchInput {
- Vector<CraneliftInsn> insns;
- u32 result_arity;
- u32 function_index;
- CompiledInstructions* target;
- u32 num_locals;
- u32 num_params;
-};
-
-// Disk-cache blob format. Stable: cached files name format_version + layout_hash so
-// any rebuild that changes those will simply miss the cache rather than try to
-// execute incompatible bytes.
-constexpr u64 cache_blob_magic = 0x4354494A4D534157ULL; // "WASMJITC" little-endian
-constexpr u32 cache_blob_format_version = 13;
-
-struct CacheBlobHeader {
- u64 magic;
- u32 format_version;
- u32 helper_count;
- u64 layout_hash;
- u8 wasm_hash[32];
- u32 function_count;
- u32 _pad;
-};
-static_assert(sizeof(CacheBlobHeader) == 64);
-
-struct CacheBlobFunctionEntry {
- u32 function_index;
- u32 code_size;
- u32 reloc_count;
- u32 trap_count;
-};
-static_assert(sizeof(CacheBlobFunctionEntry) == 16);
-
-struct CacheRecord {
- u32 function_index;
- ByteBuffer unpatched_code;
- Vector<HelperReloc> relocs;
- Vector<CraneliftTrap> traps;
-};
-
-// On a cache miss we capture every successful compile so we can hand the blob to a
-// store callback after validation finishes. On a cache hit we populate the install
-// map up front; the per-function lookup happens inside try_cranelift_compile when
-// the dispatch table for that function has just been built and is ready to receive
-// a handler_ptr.
-struct CacheCaptureState {
- bool capturing { false };
- Vector<CacheRecord> records;
-};
-struct PendingInstallState {
- bool active { false };
- HashMap<u32, CacheRecord> records;
-};
-struct CacheState {
- AK_ALLOC_WITH_KMALLOC;
-
- CacheCaptureState cache_capture;
- PendingInstallState pending_install;
- Vector<BatchInput> pending_batch;
-};
-
-static thread_local u32 s_active_function_index = NumericLimits<u32>::max();
-
-static CacheState& cranelift_cache_state()
-{
- static thread_local auto* state = new CacheState;
- return *state;
-}
-
-static CraneliftCompileCallback& cranelift_compile_callback()
-{
- static NeverDestroyed<CraneliftCompileCallback> callback;
- return *callback;
-}
-
-static u64 compute_layout_hash(RuntimeLayout const& layout)
-{
- auto fnv1a = [](u64 hash, u64 value) {
- for (int i = 0; i < 8; ++i) {
- hash ^= (value >> (i * 8)) & 0xff;
- hash *= 0x100000001b3ULL;
- }
- return hash;
- };
- u64 hash = 0xcbf29ce484222325ULL;
- hash = fnv1a(hash, layout.regs_offset);
- hash = fnv1a(hash, layout.value_size);
- hash = fnv1a(hash, layout.locals_base_offset);
- hash = fnv1a(hash, layout.memory_instances_offset);
- hash = fnv1a(hash, layout.global_instances_offset);
- hash = fnv1a(hash, layout.global_instance_value_offset);
- hash = fnv1a(hash, layout.memory_instance_data_offset);
- hash = fnv1a(hash, layout.memory_buffer_storage_offset_offset);
- hash = fnv1a(hash, layout.compiled_call_result_scratch_offset);
- hash = fnv1a(hash, layout.value_stack_base_offset);
- hash = fnv1a(hash, layout.value_stack_top_offset);
- hash = fnv1a(hash, layout.call_record_base_offset);
- return hash;
-}
-
-using RuntimeHelperAddresses = Array<size_t, HELPER_COUNT>;
-static_assert(HELPER_COUNT == 13);
-
-static bool apply_helper_relocs(u8* code_bytes, size_t code_size, HelperReloc const* relocs, size_t reloc_count, RuntimeHelperAddresses const& helper_addresses)
-{
- for (size_t i = 0; i < reloc_count; ++i) {
- auto const& r = relocs[i];
- if (r.helper_id >= HELPER_COUNT)
- return false;
- if (static_cast<size_t>(r.code_offset) + sizeof(u64) > code_size)
- return false;
- u64 addr = static_cast<u64>(helper_addresses[r.helper_id]) + static_cast<u64>(r.addend);
- __builtin_memcpy(code_bytes + r.code_offset, &addr, sizeof(addr));
- }
- return true;
-}
-
-// Allocate an RX-able page, copy the (still unpatched) machine code into it, apply the
-// helper-address patches, and install the resulting function pointer into `target`.
-// Used by both the fresh-compile path (bytes come from the subprocess shm) and the
-// cache-install path (bytes come from a `.wasmjit` blob).
-static bool install_compiled_function(CompiledInstructions& target, ReadonlyBytes code_bytes, HelperReloc const* relocs, size_t reloc_count, ReadonlySpan<CraneliftTrap> traps, RuntimeHelperAddresses const& helper_addresses)
-{
- if (target.dispatches.is_empty())
- return false;
-
- auto const code_size = code_bytes.size();
- if (code_size == 0)
- return false;
-
-#if defined(AK_OS_WINDOWS)
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- auto const page_size = static_cast<size_t>(si.dwPageSize);
- auto const rx_aligned_size = (code_size + page_size - 1) & ~(page_size - 1);
- auto* jit_mem = VirtualAlloc(nullptr, rx_aligned_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
- if (!jit_mem)
- return false;
- __builtin_memcpy(jit_mem, code_bytes.data(), code_size);
- if (!apply_helper_relocs(static_cast<u8*>(jit_mem), code_size, relocs, reloc_count, helper_addresses)) {
- VirtualFree(jit_mem, 0, MEM_RELEASE);
- return false;
- }
- DWORD old_protect;
- VirtualProtect(jit_mem, rx_aligned_size, PAGE_EXECUTE_READ, &old_protect);
- FlushInstructionCache(GetCurrentProcess(), jit_mem, code_size);
- auto* func_ptr = static_cast<u8 const*>(jit_mem);
- auto* handle = new CodeMapping { jit_mem, rx_aligned_size, {} };
-#elif defined(AK_OS_MACOS)
- auto const page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));
- auto const rx_aligned_size = (code_size + page_size - 1) & ~(page_size - 1);
- auto* jit_mapping = mmap(nullptr, rx_aligned_size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0);
- if (jit_mapping == MAP_FAILED)
- return false;
-
- pthread_jit_write_protect_np(0);
- __builtin_memcpy(jit_mapping, code_bytes.data(), code_size);
- if (!apply_helper_relocs(static_cast<u8*>(jit_mapping), code_size, relocs, reloc_count, helper_addresses)) {
- munmap(jit_mapping, rx_aligned_size);
- return false;
- }
- pthread_jit_write_protect_np(1);
- sys_icache_invalidate(jit_mapping, code_size);
- auto* func_ptr = static_cast<u8 const*>(jit_mapping);
- auto* handle = new CodeMapping { jit_mapping, rx_aligned_size, {} };
-#else
- auto const page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));
- auto const rx_aligned_size = (code_size + page_size - 1) & ~(page_size - 1);
- auto* rw_mapping = mmap(nullptr, rx_aligned_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
- if (rw_mapping == MAP_FAILED)
- return false;
- __builtin_memcpy(rw_mapping, code_bytes.data(), code_size);
- if (!apply_helper_relocs(static_cast<u8*>(rw_mapping), code_size, relocs, reloc_count, helper_addresses) || mprotect(rw_mapping, rx_aligned_size, PROT_READ | PROT_EXEC) != 0) {
- munmap(rw_mapping, rx_aligned_size);
- return false;
- }
- __builtin___clear_cache(static_cast<char*>(rw_mapping), static_cast<char*>(rw_mapping) + code_size);
- auto* func_ptr = static_cast<u8 const*>(rw_mapping);
- auto* handle = new CodeMapping { rw_mapping, rx_aligned_size, {} };
-#endif
-
- handle->traps.ensure_capacity(traps.size());
- for (auto const& trap : traps)
- handle->traps.unchecked_append(trap);
-
- target.cranelift_code_handle = handle;
- target.cranelift_code_size = code_size;
- target.cranelift_traps = handle->traps.data();
- target.cranelift_trap_count = handle->traps.size();
- target.cranelift_compiled = true;
- publish_cranelift_entry(target, bit_cast<FlatPtr>(func_ptr));
- return true;
-}
-
-}
-
-extern "C" {
-
-static ALWAYS_INLINE i32 wasm_cl_run_compiled(BytecodeInterpreter& interpreter, Configuration& config, CompiledFunctionEntry const& entry, Value* callee_locals)
-{
- BytecodeInterpreter::CallFrameHandle handle { interpreter, config };
- config.set_frame_lightweight(*entry.module, callee_locals, *entry.expression, entry.arity, entry.max_call_rec_size);
- config.ip() = 0;
-
- interpreter.clear_trap();
- using HandlerFn = Outcome (*)(BytecodeInterpreter&, Configuration&, Instruction const*, u32, Dispatch const*, SourcesAndDestination const*);
- auto const handler = bit_cast<HandlerFn>(entry.handler_ptr);
- auto outcome = handler(interpreter, config, entry.first_insn, 0, bit_cast<Dispatch const*>(entry.dispatches_ptr), bit_cast<SourcesAndDestination const*>(entry.src_dst_ptr));
-
- if (outcome != Outcome::Return) {
- interpreter.set_trap("Compiled function returned unexpectedly"sv);
- return 1;
- }
- if (interpreter.did_trap())
- return 1;
- if (entry.arity == 1)
- config.compiled_call_result_scratch() = config.value_stack().unsafe_take_last();
- // No label pop: set_frame_lightweight doesn't push labels.
- return 0;
-}
-
-static NEVER_INLINE COLD i32 wasm_cl_run_compiled_with_heap_locals(BytecodeInterpreter& interpreter, Configuration& config, CompiledFunctionEntry const& entry, Value const* args, size_t arg_count)
-{
- auto total = arg_count + entry.total_local_count;
- Vector<Value, ArgumentsStaticSize> heap_locals;
- heap_locals.ensure_capacity(total);
- heap_locals.resize_and_keep_capacity(total);
- auto* callee_locals = heap_locals.data();
- for (size_t i = 0; i < arg_count; i++)
- callee_locals[i] = args[i];
- // The non-argument slots are left uninitialized; the compiled entry block zeroes its own locals.
- return wasm_cl_run_compiled(interpreter, config, entry, callee_locals);
-}
-
-static ALWAYS_INLINE i32 wasm_cl_finish_call(BytecodeInterpreter& interpreter, Configuration& config, FunctionAddress address, Value const* args, size_t arg_count)
-{
- if (interpreter.trap_if_insufficient_native_stack_space())
- return 1;
-
- auto* instance = config.store().unsafe_get(address);
-
- if (auto* wasm_function = instance->get_pointer<WasmFunction>(); wasm_function
- && !config.should_limit_instruction_count()
- && cranelift_entry_acquire(wasm_function->code().func().body().compiled_instructions) != 0) {
-
- // Fast compiled-to-compiled call: stack-allocate locals + non-owning frame.
- auto& func = wasm_function->code().func();
- auto& ci = func.body().compiled_instructions;
- CompiledFunctionEntry const entry {
- .handler_ptr = cranelift_entry_acquire(ci),
- .dispatches_ptr = bit_cast<FlatPtr>(ci.dispatches.data()),
- .src_dst_ptr = bit_cast<FlatPtr>(ci.src_dst_mappings.data()),
- .first_insn = ci.dispatches[0].instruction,
- .expression = &func.body(),
- .module = &wasm_function->module(),
- // Match the direct-call table's sizing: the JIT frame is grown by the inlined-callee
- // locals too, so the buffer must cover them or the callee scribbles past its end.
- .total_local_count = static_cast<u32>(func.total_local_count()) + ci.cranelift_inlined_locals,
- .arity = static_cast<u32>(wasm_function->type().results().size()),
- .max_call_rec_size = static_cast<u32>(ci.max_call_rec_size),
- };
-
- if (arg_count + entry.total_local_count > 64) [[unlikely]]
- return wasm_cl_run_compiled_with_heap_locals(interpreter, config, entry, args, arg_count);
-
- // Opt out of -ftrivial-auto-var-init: only the argument slots are written below, and the
- // compiled entry block initializes its own locals, so nothing reads the rest.
- __attribute__((uninitialized)) Value callee_locals[64];
- for (size_t i = 0; i < arg_count; i++)
- callee_locals[i] = args[i];
- return wasm_cl_run_compiled(interpreter, config, entry, callee_locals);
- }
-
- Vector<Value, ArgumentsStaticSize> args_vec;
- config.get_arguments_allocation_if_possible(args_vec, arg_count);
- args_vec.ensure_capacity(arg_count);
- for (size_t i = 0; i < arg_count; i++)
- args_vec.unchecked_append(args[i]);
-
- // direct-threaded interpreter path:
- if (auto* wasm_function = instance->get_pointer<WasmFunction>(); wasm_function && !config.should_limit_instruction_count() && wasm_function->code().func().body().compiled_instructions.direct) {
- BytecodeInterpreter::CallFrameHandle handle { interpreter, config };
- if (auto prepare_result = config.prepare_wasm_call(*wasm_function, args_vec); prepare_result.is_error()) {
- interpreter.set_trap(prepare_result.release_error());
- return 1;
- }
- config.ip() = 0;
- auto outcome = interpreter.run_compiled_function_direct(config);
- if (outcome != Outcome::Return) {
- interpreter.set_trap("Compiled function returned unexpectedly"sv);
- return 1;
- }
- if (interpreter.did_trap())
- return 1;
- if (config.frame().arity() == 1)
- config.compiled_call_result_scratch() = config.value_stack().unsafe_take_last();
- if (config.label_stack().size() > config.frame().label_index())
- config.label_stack().shrink(config.frame().label_index(), true);
- return 0;
- }
-
- // non-compiled call (interpreter or host function)
- Wasm::Result result { Vector<Value> {} };
- if (instance->has<WasmFunction>()) {
- BytecodeInterpreter::CallFrameHandle handle { interpreter, config };
- result = config.call(interpreter, address, args_vec);
- } else {
- result = config.call(interpreter, address, args_vec);
- config.release_arguments_allocation(args_vec);
- }
-
- if (result.is_trap()) {
- interpreter.set_trap(move(result.trap()));
- return 1;
- }
-
- if (!result.values().is_empty())
- config.compiled_call_result_scratch() = result.values().first();
- return 0;
-}
-
-i32 wasm_cl_call_function(void* interp_ptr, void* config_ptr, i32 func_index);
-i32 wasm_cl_call_function(void* interp_ptr, void* config_ptr, i32 func_index)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
-
- auto const& module = config.frame().module();
- auto const& functions = module.functions();
- if (static_cast<size_t>(func_index) >= functions.size())
- return 1;
-
- auto address = functions[func_index];
-
- SourcesAndDestination addrs {};
- addrs.sources[0] = Dispatch::RegisterOrStack::Stack;
- addrs.sources[1] = Dispatch::RegisterOrStack::Stack;
- addrs.sources[2] = Dispatch::RegisterOrStack::Stack;
- addrs.destination = Dispatch::RegisterOrStack::Stack;
-
- auto outcome = interpreter.call_address(config, address, addrs,
- BytecodeInterpreter::CallAddressSource::DirectCall,
- BytecodeInterpreter::CallType::UsingStack);
-
- return outcome == Outcome::Return && interpreter.did_trap() ? 1 : 0;
-}
-
-void wasm_cl_set_trap(void* interp_ptr, u8 const* msg, i32 len);
-void wasm_cl_set_trap(void* interp_ptr, u8 const* msg, i32 len)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- interpreter.set_trap(StringView(reinterpret_cast<char const*>(msg), len));
-}
-
-static inline MemoryInstance* wasm_cl_get_memory(void* config_ptr, u32 mem_idx)
-{
- auto& config = *static_cast<Configuration*>(config_ptr);
- return config.memory_instance(mem_idx);
-}
-
-i64 wasm_cl_memory_size(void* config_ptr, u32 mem_idx);
-i64 wasm_cl_memory_size(void* config_ptr, u32 mem_idx)
-{
- auto* memory = wasm_cl_get_memory(config_ptr, mem_idx);
- return static_cast<i64>(memory->size() / Constants::page_size);
-}
-
-i32 wasm_cl_memory_grow(void* config_ptr, u32 mem_idx, i32 pages);
-i32 wasm_cl_memory_grow(void* config_ptr, u32 mem_idx, i32 pages)
-{
- auto* memory = wasm_cl_get_memory(config_ptr, mem_idx);
- auto old_pages = memory->size() / Constants::page_size;
- if (!memory->grow(pages * Constants::page_size))
- return -1;
- return static_cast<i32>(old_pages);
-}
-
-i32 wasm_cl_call_indirect(void* interp_ptr, void* config_ptr, i32 table_idx, i32 type_idx, i32 element_index);
-i32 wasm_cl_call_indirect(void* interp_ptr, void* config_ptr, i32 table_idx, i32 type_idx, i32 element_index)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
-
- auto const& module = config.frame().module();
- auto table_address = module.tables()[table_idx];
- auto* table_instance = config.store().get(table_address);
- if (!table_instance || element_index < 0 || static_cast<size_t>(element_index) >= table_instance->elements().size())
- return interpreter.set_trap(Trap::from_string("Table index out of bounds"));
-
- auto& element = table_instance->elements()[element_index];
- if (!element.ref().has<Reference::Func>())
- return interpreter.set_trap(Trap::from_string("Table element is not a function reference"));
-
- auto address = element.ref().get<Reference::Func>().address;
- auto* function = config.store().get(address);
- if (!function)
- return interpreter.set_trap(Trap::from_string("Indirect call to freed function"));
- // https://webassembly.github.io/spec/core/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-call-indirect-x-y
- // call_indirect's runtime check is a defined-type match (a downcast), not structural equality.
- auto const* type_actual = function->visit([](auto& f) { return f.defined_type(); });
- auto const* type_expected = module.canonical_types()[type_idx];
- if (!type_actual || !matches_defined_type(*type_actual, *type_expected))
- return interpreter.set_trap(Trap::from_string("Indirect call type mismatch"));
-
- auto const& function_type = function->visit([](auto const& value) -> FunctionType const& { return value.type(); });
- if (function_type.results().size() <= 1) {
- auto parameter_count = function_type.parameters().size();
- if (parameter_count > config.value_stack().size())
- return interpreter.set_trap(Trap::from_string("Insufficient arguments for indirect call"));
-
- auto arguments = config.value_stack().span().slice_from_end(parameter_count);
- config.value_stack().shrink(config.value_stack().size() - parameter_count);
- auto did_trap = wasm_cl_finish_call(interpreter, config, address, arguments.data(), arguments.size());
- if (!did_trap && !function_type.results().is_empty())
- config.value_stack().unchecked_append(config.compiled_call_result_scratch());
- return did_trap;
- }
-
- SourcesAndDestination addrs {};
- addrs.sources[0] = Dispatch::RegisterOrStack::Stack;
- addrs.sources[1] = Dispatch::RegisterOrStack::Stack;
- addrs.sources[2] = Dispatch::RegisterOrStack::Stack;
- addrs.destination = Dispatch::RegisterOrStack::Stack;
-
- auto outcome = interpreter.call_address(config, address, addrs, BytecodeInterpreter::CallAddressSource::IndirectCall, BytecodeInterpreter::CallType::UsingStack);
-
- return outcome == Outcome::Return && interpreter.did_trap() ? 1 : 0;
-}
-
-i32 wasm_cl_memory_copy(void* interp_ptr, void* config_ptr, u32 dst_mem, u32 src_mem, i32 dst_offset, i32 src_offset, i32 count);
-i32 wasm_cl_memory_copy(void* interp_ptr, void* config_ptr, u32 dst_mem, u32 src_mem, i32 dst_offset, i32 src_offset, i32 count)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto* src_instance = wasm_cl_get_memory(config_ptr, src_mem);
- auto* dst_instance = wasm_cl_get_memory(config_ptr, dst_mem);
-
- auto src_end = static_cast<u64>(static_cast<u32>(src_offset)) + static_cast<u32>(count);
- auto dst_end = static_cast<u64>(static_cast<u32>(dst_offset)) + static_cast<u32>(count);
- if (src_end > src_instance->size() || dst_end > dst_instance->size())
- return interpreter.set_trap(Trap::from_string("Memory access out of bounds"));
-
- if (count > 0)
- dst_instance->data().copy_from(src_instance->data(), static_cast<u32>(src_offset), static_cast<u32>(dst_offset), static_cast<u32>(count));
-
- return 0;
-}
-
-i32 wasm_cl_memory_fill(void* interp_ptr, void* config_ptr, u32 mem_idx, i32 offset, i32 value, i32 count);
-i32 wasm_cl_memory_fill(void* interp_ptr, void* config_ptr, u32 mem_idx, i32 offset, i32 value, i32 count)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto* instance = wasm_cl_get_memory(config_ptr, mem_idx);
-
- auto end = static_cast<u64>(static_cast<u32>(offset)) + static_cast<u32>(count);
- if (end > instance->size())
- return interpreter.set_trap(Trap::from_string("Memory access out of bounds"));
-
- if (count > 0)
- instance->data().fill(static_cast<u32>(offset), static_cast<u8>(value), static_cast<u32>(count));
-
- return 0;
-}
-
-i32 wasm_cl_call_with_record(void* interp_ptr, void* config_ptr, i32 func_index);
-i32 wasm_cl_call_with_record(void* interp_ptr, void* config_ptr, i32 func_index)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
-
- auto const& module = config.frame().module();
- auto const& functions = module.functions();
- if (static_cast<size_t>(func_index) >= functions.size())
- return 1;
-
- auto address = functions[func_index];
- auto* instance = config.store().get(address);
- if (!instance) {
- interpreter.set_trap("Attempt to call nonexistent function by address"sv);
- return 1;
- }
-
- FunctionType const* type { nullptr };
- instance->visit([&](auto const& function) { type = &function.type(); });
-
- return wasm_cl_finish_call(interpreter, config, address, config.call_record_base(), type->parameters().size());
-}
-
-static NEVER_INLINE COLD i32 wasm_cl_direct_call_fallback(BytecodeInterpreter& interpreter, Configuration& config, i32 func_index, Value const* args, size_t arg_count)
-{
- return wasm_cl_finish_call(interpreter, config, config.frame().module().functions()[func_index], args, arg_count);
-}
-
-// Direct compiled-to-compiled call. Falls back to wasm_cl_finish_call for non-compiled targets.
-static ALWAYS_INLINE i32 wasm_cl_direct_call_impl(BytecodeInterpreter& interpreter, Configuration& config, i32 func_index, Value* args, size_t arg_count)
-{
- auto const* table = config.frame().compiled_fn_table();
- auto index = static_cast<size_t>(func_index);
- if (!table || index >= table->size() || !(*table)[index].module) [[unlikely]]
- return wasm_cl_direct_call_fallback(interpreter, config, func_index, args, arg_count);
-
- auto const& entry = (*table)[index];
-
- if (config.depth() > 500) [[unlikely]] {
- interpreter.set_trap(Constants::stack_exhaustion_message);
- return 1;
- }
-
- if (arg_count + entry.total_local_count > 64) [[unlikely]]
- return wasm_cl_run_compiled_with_heap_locals(interpreter, config, entry, args, arg_count);
-
- // Opt out of -ftrivial-auto-var-init as in wasm_cl_finish_call: only the argument slots are
- // written, and the compiled entry block initializes its own locals.
- __attribute__((uninitialized)) Value callee_locals[64];
- for (size_t i = 0; i < arg_count; i++)
- callee_locals[i] = args[i];
- return wasm_cl_run_compiled(interpreter, config, entry, callee_locals);
-}
-
-i32 wasm_cl_direct_call_0(void* interp_ptr, void* config_ptr, i32 func_index);
-i32 wasm_cl_direct_call_0(void* interp_ptr, void* config_ptr, i32 func_index)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
- return wasm_cl_direct_call_impl(interpreter, config, func_index, nullptr, 0);
-}
-
-i32 wasm_cl_direct_call_1(void* interp_ptr, void* config_ptr, i32 func_index, i64 arg0);
-i32 wasm_cl_direct_call_1(void* interp_ptr, void* config_ptr, i32 func_index, i64 arg0)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
- Value args[] = { Value(arg0) };
- return wasm_cl_direct_call_impl(interpreter, config, func_index, args, 1);
-}
-
-i32 wasm_cl_direct_call_2(void* interp_ptr, void* config_ptr, i32 func_index, i64 arg0, i64 arg1);
-i32 wasm_cl_direct_call_2(void* interp_ptr, void* config_ptr, i32 func_index, i64 arg0, i64 arg1)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
- Value args[] = { Value(arg0), Value(arg1) };
- return wasm_cl_direct_call_impl(interpreter, config, func_index, args, 2);
-}
-
-i32 wasm_cl_direct_call_3(void* interp_ptr, void* config_ptr, i32 func_index, i64 arg0, i64 arg1, i64 arg2);
-i32 wasm_cl_direct_call_3(void* interp_ptr, void* config_ptr, i32 func_index, i64 arg0, i64 arg1, i64 arg2)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
- Value args[] = { Value(arg0), Value(arg1), Value(arg2) };
- return wasm_cl_direct_call_impl(interpreter, config, func_index, args, 3);
-}
-
-// Thin frame push for direct compiled-to-compiled calls. Returns 1 on trap, 0 on success.
-i32 wasm_cl_push_frame(void* interp_ptr, void* config_ptr, Value* locals_ptr, u32, void const* module_ptr, void const* expression_ptr, u32 arity, u32 max_call_rec_size);
-i32 wasm_cl_push_frame(void* interp_ptr, void* config_ptr, Value* locals_ptr, u32 /* total_locals */, void const* module_ptr, void const* expression_ptr, u32 arity, u32 max_call_rec_size)
-{
- auto& interpreter = *static_cast<BytecodeInterpreter*>(interp_ptr);
- auto& config = *static_cast<Configuration*>(config_ptr);
- auto const& module = *static_cast<ModuleInstance const*>(module_ptr);
- auto const& expression = *static_cast<Expression const*>(expression_ptr);
-
- if (interpreter.trap_if_insufficient_native_stack_space())
- return 1;
-
- config.set_frame_lightweight(module, locals_ptr, expression, arity, max_call_rec_size);
- config.depth()++;
- return 0;
-}
-
-// Thin frame pop for direct compiled-to-compiled calls.
-void wasm_cl_pop_frame(void* config_ptr, u32 arity);
-void wasm_cl_pop_frame(void* config_ptr, u32 arity)
-{
- auto& config = *static_cast<Configuration*>(config_ptr);
- if (arity == 1)
- config.compiled_call_result_scratch() = config.value_stack().unsafe_take_last();
- if (!config.label_stack().is_empty())
- config.label_stack().take_last();
- config.unwind_impl();
-}
-}
-
-namespace Wasm {
-
-static RuntimeHelperAddresses make_runtime_helper_addresses()
-{
- RuntimeHelperAddresses addresses {};
- addresses[to_underlying(HelperId::call_function)] = bit_cast<uintptr_t>(&wasm_cl_call_function);
- addresses[to_underlying(HelperId::set_trap)] = bit_cast<uintptr_t>(&wasm_cl_set_trap);
- addresses[to_underlying(HelperId::memory_size)] = bit_cast<uintptr_t>(&wasm_cl_memory_size);
- addresses[to_underlying(HelperId::memory_grow)] = bit_cast<uintptr_t>(&wasm_cl_memory_grow);
- addresses[to_underlying(HelperId::call_with_record)] = bit_cast<uintptr_t>(&wasm_cl_call_with_record);
- addresses[to_underlying(HelperId::direct_call_0)] = bit_cast<uintptr_t>(&wasm_cl_direct_call_0);
- addresses[to_underlying(HelperId::direct_call_1)] = bit_cast<uintptr_t>(&wasm_cl_direct_call_1);
- addresses[to_underlying(HelperId::direct_call_2)] = bit_cast<uintptr_t>(&wasm_cl_direct_call_2);
- addresses[to_underlying(HelperId::direct_call_3)] = bit_cast<uintptr_t>(&wasm_cl_direct_call_3);
- addresses[to_underlying(HelperId::call_indirect)] = bit_cast<uintptr_t>(&wasm_cl_call_indirect);
- addresses[to_underlying(HelperId::memory_copy)] = bit_cast<uintptr_t>(&wasm_cl_memory_copy);
- addresses[to_underlying(HelperId::memory_fill)] = bit_cast<uintptr_t>(&wasm_cl_memory_fill);
- addresses[to_underlying(HelperId::primitive_storage_cage_base)] = bit_cast<uintptr_t>(&js_primitive_storage_cage_base);
- return addresses;
-}
-
-static RuntimeLayout make_runtime_layout()
-{
- return RuntimeLayout {
- .regs_offset = static_cast<u32>(offsetof(Configuration, regs)),
- .value_size = static_cast<u32>(sizeof(Value)),
- .locals_base_offset = static_cast<u32>(Configuration::locals_base_offset()),
- .memory_instances_offset = static_cast<u32>(Configuration::memory_instances_offset()),
- .global_instances_offset = static_cast<u32>(Configuration::global_instances_offset()),
- .global_instance_value_offset = static_cast<u32>(GlobalInstance::value_offset()),
- .memory_instance_data_offset = static_cast<u32>(MemoryInstance::data_offset()),
- .memory_buffer_storage_offset_offset = static_cast<u32>(MemoryBuffer::storage_offset_offset()),
- .compiled_call_result_scratch_offset = static_cast<u32>(Configuration::compiled_call_result_scratch_offset()),
- .value_stack_base_offset = static_cast<u32>(Configuration::value_stack_base_offset()),
- .value_stack_top_offset = static_cast<u32>(Configuration::value_stack_top_offset()),
- .call_record_base_offset = static_cast<u32>(Configuration::call_record_base_offset()),
- };
-}
-
-static RuntimeLayout const& runtime_layout()
-{
- static auto const layout = make_runtime_layout();
- return layout;
-}
-
-static u64 runtime_layout_hash()
-{
- static auto const hash = compute_layout_hash(runtime_layout());
- return hash;
-}
-
-static CraneliftInsn serialize_insn(Dispatch const& dispatch, SourcesAndDestination const& addr)
-{
- CraneliftInsn out {};
- auto const* insn = dispatch.instruction;
- out.opcode = insn->opcode().value();
- out.sources[0] = addr.sources[0];
- out.sources[1] = addr.sources[1];
- out.sources[2] = addr.sources[2];
- out.destination = addr.destination;
- out.imm1 = 0;
- out.imm2 = 0;
- out.imm3 = 0;
-
- auto const& args = insn->arguments();
- u32 opc = out.opcode;
-
- if (opc == Instructions::i32_const.value()) {
- out.imm1 = static_cast<i64>(args.get<i32>());
- } else if (opc == Instructions::i64_const.value()) {
- out.imm1 = args.get<i64>();
- } else if (opc == Instructions::f32_const.value()) {
- out.imm1 = static_cast<i64>(bit_cast<i32>(args.get<float>()));
- } else if (opc == Instructions::f64_const.value()) {
- out.imm1 = bit_cast<i64>(args.get<double>());
- } else if (opc == Instructions::local_get.value() || opc == Instructions::local_set.value() || opc == Instructions::local_tee.value()) {
- out.imm1 = static_cast<i64>(insn->local_index().value());
- } else if (opc == Instructions::global_get.value() || opc == Instructions::global_set.value()) {
- out.imm1 = static_cast<i64>(args.get<GlobalIndex>().value());
- } else if (opc == Instructions::br.value() || opc == Instructions::br_if.value()) {
- auto const& br_args = args.get<Instruction::BranchArgs>();
- out.imm1 = static_cast<i64>(br_args.label.value());
- } else if (opc == Instructions::block.value() || opc == Instructions::loop.value() || opc == Instructions::if_.value()) {
- auto const& struct_args = args.get<Instruction::StructuredInstructionArgs>();
- out.imm1 = static_cast<i64>(struct_args.end_ip.value());
- out.imm2 = struct_args.else_ip().has_value()
- ? static_cast<i64>(struct_args.else_ip()->value())
- : -1;
- u32 arity = struct_args.meta.arity;
- u32 param_count = struct_args.meta.parameter_count;
- out.imm3 = arity | (param_count << 16);
- } else if (opc == Instructions::br_table.value()) {
- auto const& table_args = args.get<Instruction::TableBranchArgs>();
- if (table_args.default_.value() > NumericLimits<u16>::max()) {
- out.imm3 = 0xff;
- return out;
- }
- for (auto const& label : table_args.labels) {
- if (label.value() > NumericLimits<u16>::max()) {
- out.imm3 = 0xff;
- return out;
- }
- }
-
- // Pack: imm3 low byte = min(label_count, 8), upper bits = default label.
- // First 4 labels in imm1, next 4 in imm2 (16 bits each).
- // If more than 8 labels, continuation instructions carry the rest.
- auto const total_labels = table_args.labels.size();
- auto const inline_count = min(total_labels, static_cast<size_t>(8));
- out.imm3 = static_cast<u32>(inline_count) | (static_cast<u32>(table_args.default_.value()) << 8);
- for (size_t i = 0; i < inline_count; ++i) {
- auto const encoded = static_cast<u64>(table_args.labels[i].value()) << ((i % 4) * 16);
- if (i < 4)
- out.imm1 |= static_cast<i64>(encoded);
- else
- out.imm2 |= static_cast<i64>(encoded);
- }
- } else if (opc == Instructions::call.value()) {
- out.imm1 = static_cast<i64>(args.get<FunctionIndex>().value());
- } else if (opc == Instructions::call_indirect.value()) {
- auto const& indirect_args = args.get<Instruction::IndirectCallArgs>();
- out.imm1 = static_cast<i64>(indirect_args.type.value());
- out.imm2 = static_cast<i64>(indirect_args.table.value());
- } else if (opc == Instructions::memory_copy.value()) {
- auto const& copy_args = args.get<Instruction::MemoryCopyArgs>();
- out.imm1 = static_cast<i64>(copy_args.dst_index.value());
- out.imm2 = static_cast<i64>(copy_args.src_index.value());
- } else if (opc == Instructions::memory_fill.value()) {
- auto const& fill_args = args.get<Instruction::MemoryIndexArgument>();
- out.imm1 = static_cast<i64>(fill_args.memory_index.value());
- } else if (opc >= Instructions::i32_load.value() && opc <= Instructions::i64_store32.value()) {
- auto const& mem_arg = args.get<Instruction::MemoryArgument>();
- out.imm1 = static_cast<i64>(mem_arg.offset);
- out.imm3 = static_cast<u32>(mem_arg.memory_index.value());
- } else if (opc == Instructions::memory_size.value()
- || opc == Instructions::memory_grow.value()) {
- auto const& mem_idx_arg = args.get<Instruction::MemoryIndexArgument>();
- out.imm1 = static_cast<i64>(mem_idx_arg.memory_index.value());
- }
-
- auto is_syn = [opc](OpCode op) { return opc == op.value(); };
- auto syn_between = [opc](OpCode lo, OpCode hi) { return opc >= lo.value() && opc <= hi.value(); };
-
- if (opc >= Instructions::SyntheticInstructionBase.value()) {
- if (syn_between(Instructions::synthetic_call_00, Instructions::synthetic_call_31)) {
- out.imm1 = static_cast<i64>(args.get<FunctionIndex>().value());
- } else if (is_syn(Instructions::synthetic_call_with_record_0) || is_syn(Instructions::synthetic_call_with_record_1)) {
- out.imm1 = static_cast<i64>(args.get<FunctionIndex>().value());
- } else if (is_syn(Instructions::synthetic_br_nostack) || is_syn(Instructions::synthetic_br_if_nostack)) {
- auto const& br_args = args.get<Instruction::BranchArgs>();
- out.imm1 = static_cast<i64>(br_args.label.value());
- } else if (is_syn(Instructions::synthetic_local_copy)) {
- out.imm1 = static_cast<i64>(insn->local_index().value());
- out.imm2 = static_cast<i64>(args.get<LocalIndex>().value());
- } else if (is_syn(Instructions::synthetic_i32_add2local)
- || syn_between(Instructions::synthetic_i32_sub2local, Instructions::synthetic_i32_shrs2local)
- || is_syn(Instructions::synthetic_i64_add2local)
- || syn_between(Instructions::synthetic_i64_sub2local, Instructions::synthetic_i64_shrs2local)) {
- out.imm1 = static_cast<i64>(insn->local_index().value());
- out.imm2 = static_cast<i64>(args.get<LocalIndex>().value());
- } else if (is_syn(Instructions::synthetic_i32_addconstlocal) || is_syn(Instructions::synthetic_i32_andconstlocal)) {
- out.imm1 = static_cast<i64>(args.get<i32>());
- out.imm2 = static_cast<i64>(insn->local_index().value());
- } else if (is_syn(Instructions::synthetic_i64_addconstlocal) || is_syn(Instructions::synthetic_i64_andconstlocal)) {
- out.imm1 = args.get<i64>();
- out.imm2 = static_cast<i64>(insn->local_index().value());
- } else if (is_syn(Instructions::synthetic_i32_storelocal) || is_syn(Instructions::synthetic_i64_storelocal)) {
- auto const& mem_arg = args.get<Instruction::MemoryArgument>();
- out.imm1 = static_cast<i64>(mem_arg.offset);
- out.imm2 = static_cast<i64>(insn->local_index().value());
- out.imm3 = static_cast<u32>(mem_arg.memory_index.value());
- } else if (is_syn(Instructions::synthetic_local_seti32_const)) {
- out.imm1 = static_cast<i64>(args.get<i32>());
- out.imm2 = static_cast<i64>(insn->local_index().value());
- } else if (is_syn(Instructions::synthetic_local_seti64_const)) {
- out.imm1 = args.get<i64>();
- out.imm2 = static_cast<i64>(insn->local_index().value());
- } else if (syn_between(Instructions::synthetic_argument_get, Instructions::synthetic_argument_tee)) {
- out.imm1 = static_cast<i64>(insn->local_index().value());
- }
- }
-
- return out;
-}
-
-ByteString const& cranelift_compiler_path()
-{
- // Lookup order: LADYBIRD_CRANELIFT_COMPILER, compile-time path, sibling-of-self.
- static NeverDestroyed<ByteString> s_path = []() -> ByteString {
- auto file_exists = [](ByteString const& path) {
- return FileSystem::exists(path);
- };
-
- if (auto const* env = getenv("LADYBIRD_CRANELIFT_COMPILER"); env && *env) {
- if (file_exists(env))
- return ByteString { env };
- }
-
- if (file_exists(WASM_CRANELIFT_COMPILER_PATH))
- return WASM_CRANELIFT_COMPILER_PATH;
-
- if (auto self_path = Core::System::current_executable_path(); !self_path.is_error()) {
- auto sibling = LexicalPath::join(LexicalPath::dirname(self_path.value()), "cranelift-compiler"sv).string();
- if (file_exists(sibling))
- return sibling;
- }
-
- return WASM_CRANELIFT_COMPILER_PATH;
- }();
-
- return *s_path;
-}
-
-template<typename T>
-static ErrorOr<T> read_cranelift_input(ReadonlyBytes input, size_t offset)
-{
- Checked<size_t> end = offset;
- end += sizeof(T);
- if (end.has_overflow() || end.value() > input.size())
- return Error::from_string_literal("Cranelift input is truncated");
-
- T value;
- input.slice(offset, sizeof(T)).copy_to({ &value, sizeof(T) });
- return value;
-}
-
-static ErrorOr<Core::AnonymousBuffer> create_cranelift_output_buffer(ReadonlyBytes input)
-{
- if (input.size() < sizeof(InputHeader))
- return Error::from_string_literal("Cranelift input header is truncated");
-
- auto header = TRY(read_cranelift_input<InputHeader>(input, 0));
- if (header.total_size != input.size())
- return Error::from_string_literal("Cranelift input size does not match its header");
-
- Checked<size_t> entries_size = sizeof(InputFunctionEntry);
- entries_size *= header.function_count;
- if (entries_size.has_overflow())
- return Error::from_string_literal("Cranelift input entries are too large");
-
- Checked<size_t> entries_end = sizeof(InputHeader);
- entries_end += entries_size.value();
- if (entries_end.has_overflow() || entries_end.value() > input.size())
- return Error::from_string_literal("Cranelift input entries are truncated");
-
- size_t instruction_count = 0;
- size_t locals_size = 0;
- for (size_t i = 0; i < header.function_count; ++i) {
- auto entry = TRY(read_cranelift_input<InputFunctionEntry>(input, sizeof(InputHeader) + i * sizeof(InputFunctionEntry)));
- Checked<size_t> new_instruction_count = instruction_count;
- new_instruction_count += entry.insn_count;
- if (new_instruction_count.has_overflow())
- return Error::from_string_literal("Cranelift instruction count overflow");
- instruction_count = new_instruction_count.value();
-
- Checked<size_t> new_locals_size = locals_size;
- new_locals_size += entry.num_locals;
- if (new_locals_size.has_overflow())
- return Error::from_string_literal("Cranelift locals size overflow");
- locals_size = new_locals_size.value();
- }
-
- auto insn_region_offset = align_up(entries_end.value(), alignof(CraneliftInsn));
- Checked<size_t> insn_region_size = instruction_count;
- insn_region_size *= sizeof(CraneliftInsn);
- if (insn_region_size.has_overflow())
- return Error::from_string_literal("Cranelift instruction region is too large");
-
- Checked<size_t> locals_region_offset = insn_region_offset;
- locals_region_offset += insn_region_size.value();
- if (locals_region_offset.has_overflow())
- return Error::from_string_literal("Cranelift locals region offset overflow");
-
- Checked<size_t> layout_offset = locals_region_offset.value();
- layout_offset += locals_size;
- if (layout_offset.has_overflow())
- return Error::from_string_literal("Cranelift layout offset overflow");
- auto aligned_layout_offset = align_up(layout_offset.value(), alignof(RuntimeLayout));
-
- Checked<size_t> expected_input_size = aligned_layout_offset;
- expected_input_size += sizeof(RuntimeLayout);
- if (expected_input_size.has_overflow() || expected_input_size.value() != input.size() || header.layout_offset != aligned_layout_offset)
- return Error::from_string_literal("Cranelift input regions are not canonical");
-
- size_t insn_cursor = insn_region_offset;
- size_t locals_cursor = locals_region_offset.value();
- for (size_t i = 0; i < header.function_count; ++i) {
- auto entry = TRY(read_cranelift_input<InputFunctionEntry>(input, sizeof(InputHeader) + i * sizeof(InputFunctionEntry)));
- if (entry.insn_offset != insn_cursor || entry.locals_offset != locals_cursor)
- return Error::from_string_literal("Cranelift input regions are not canonical");
-
- insn_cursor += static_cast<size_t>(entry.insn_count) * sizeof(CraneliftInsn);
- locals_cursor += entry.num_locals;
- }
-
- auto output_size = TRY(compute_output_buffer_size(header.function_count, instruction_count));
- if (header.output_size != output_size)
- return Error::from_string_literal("Cranelift output size does not match its input");
-
- return Core::AnonymousBuffer::create_with_size(output_size, Core::AnonymousBuffer::Sealability::Sealable);
-}
-
-static ErrorOr<Core::AnonymousBuffer> finalize_cranelift_output_buffer(Core::AnonymousBuffer const& output)
-{
- if (output.size() < sizeof(OutputHeader))
- return Error::from_string_literal("Cranelift output header is truncated");
-
- auto const& header = *output.data<OutputHeader>();
- auto output_size = static_cast<size_t>(header.total_size);
- if (output_size < sizeof(OutputHeader) || output_size > output.size())
- return Error::from_string_literal("Cranelift output size is invalid");
-
- auto output_fd = TRY(Core::System::dup(output.fd()));
- return Core::AnonymousBuffer::create_from_anon_fd(output_fd, output_size);
-}
-
-ErrorOr<Core::AnonymousBuffer> compile_cranelift_buffer(Core::AnonymousBuffer const& input)
-{
- auto output = TRY(create_cranelift_output_buffer(input.bytes()));
-
- // The child is given duplicates that it alone inherits, under their own values.
- auto compiler_input_fd = TRY(Core::System::dup(input.fd()));
- ScopeGuard close_compiler_input_fd { [&]() { (void)Core::System::close(compiler_input_fd); } };
-
- auto compiler_output_fd = TRY(Core::System::dup(output.fd()));
- ScopeGuard close_compiler_output_fd { [&]() { (void)Core::System::close(compiler_output_fd); } };
-
- Vector<ByteString> arguments;
- arguments.append(ByteString::number(compiler_input_fd));
- arguments.append(ByteString::number(input.size()));
- arguments.append(ByteString::number(compiler_output_fd));
- arguments.append(ByteString::number(output.size()));
-
- auto process = TRY(Core::Process::spawn({
- .name = "cranelift-compiler"sv,
- .executable = cranelift_compiler_path(),
- .die_with_parent = true,
- .arguments = arguments,
- .file_actions = {
- Core::FileAction::DupFd { .write_fd = compiler_input_fd, .fd = compiler_input_fd },
- Core::FileAction::DupFd { .write_fd = compiler_output_fd, .fd = compiler_output_fd },
- },
- }));
-
- if (TRY(process.wait_for_termination()) != 0)
- return Error::from_string_literal("Failed to compile a WebAssembly module");
-
- return finalize_cranelift_output_buffer(output);
-}
-
-static ErrorOr<void> try_cranelift_compile_batch(ReadonlySpan<BatchInput> batch)
-{
- if (batch.is_empty())
- return {};
-
- static auto helper_addresses = make_runtime_helper_addresses();
- auto const& layout = runtime_layout();
- u64 outcome_return = to_underlying(Outcome::Return);
-
- size_t function_count = batch.size();
- auto const entries_offset = sizeof(InputHeader);
- auto const entries_size = sizeof(InputFunctionEntry) * function_count;
-
- size_t total_insn_count = 0;
- size_t total_locals_bytes = 0;
- for (auto const& entry : batch) {
- total_insn_count += entry.insns.size();
- total_locals_bytes += entry.num_locals;
- }
-
- auto const insn_region_offset = align_up(entries_offset + entries_size, alignof(CraneliftInsn));
- auto const insn_bytes = total_insn_count * sizeof(CraneliftInsn);
- auto const locals_region_offset = insn_region_offset + insn_bytes; // u8, no alignment needed
- auto const layout_offset = align_up(locals_region_offset + total_locals_bytes, alignof(RuntimeLayout));
- auto const total_size = layout_offset + sizeof(RuntimeLayout);
- auto const output_size = TRY(compute_output_buffer_size(function_count, total_insn_count));
-
- auto buffer = TRY(Core::AnonymousBuffer::create_with_size(total_size, Core::AnonymousBuffer::Sealability::Sealable));
- auto* base = buffer.data<u8>();
- __builtin_memset(base, 0, total_size);
-
- auto* header = reinterpret_cast<InputHeader*>(base);
- *header = InputHeader {
- .function_count = static_cast<u32>(function_count),
- .layout_offset = static_cast<u32>(layout_offset),
- .outcome_return = outcome_return,
- .output_size = output_size,
- .total_size = total_size,
- };
-
- size_t insn_cursor = insn_region_offset;
- size_t locals_cursor = locals_region_offset;
- for (size_t i = 0; i < function_count; ++i) {
- auto const& input = batch[i];
- auto* entry = reinterpret_cast<InputFunctionEntry*>(base + entries_offset + i * sizeof(InputFunctionEntry));
- *entry = InputFunctionEntry {
- .insn_offset = static_cast<u32>(insn_cursor),
- .insn_count = static_cast<u32>(input.insns.size()),
- .result_arity = input.result_arity,
- .num_locals = input.num_locals,
- .locals_offset = static_cast<u32>(locals_cursor),
- .num_params = input.num_params,
- };
- __builtin_memcpy(base + insn_cursor, input.insns.data(), input.insns.size() * sizeof(CraneliftInsn));
- insn_cursor += input.insns.size() * sizeof(CraneliftInsn);
-
- auto const& local_types = input.target->cranelift_local_types;
- for (u32 l = 0; l < input.num_locals; ++l)
- base[locals_cursor + l] = l < local_types.size() ? local_types[l] : static_cast<u8>(ValueType::I64);
- locals_cursor += input.num_locals;
- }
-
- __builtin_memcpy(base + layout_offset, &layout, sizeof(layout));
-
- auto output_buffer = TRY([&]() -> ErrorOr<Core::AnonymousBuffer> {
- if (auto& callback = cranelift_compile_callback()) {
- auto output = callback(buffer);
- return output.snapshot();
- }
- return compile_cranelift_buffer(buffer);
- }());
- if (!output_buffer.is_valid() || output_buffer.size() < sizeof(OutputHeader))
- return Error::from_string_literal("Failed to compile a WebAssembly module");
-
- // Extract results for each function.
- auto const* output_base = output_buffer.data<u8>();
- auto const& output_header = *reinterpret_cast<OutputHeader const*>(output_base);
- auto const output_entries_offset = sizeof(OutputHeader);
- auto const output_entries_size = sizeof(OutputFunctionEntry) * function_count;
- auto const code_base_offset = static_cast<size_t>(output_header.code_base_offset);
- auto const reloc_region_start = static_cast<size_t>(output_header.reloc_region_start);
- auto const compact_output_size = static_cast<size_t>(output_header.total_size);
- if (output_header.function_count != function_count
- || compact_output_size != output_buffer.size()
- || code_base_offset < output_entries_offset + output_entries_size
- || code_base_offset % SERIALIZED_CODE_ALIGNMENT != 0
- || reloc_region_start < code_base_offset
- || reloc_region_start % alignof(HelperReloc) != 0
- || reloc_region_start > compact_output_size)
- return Error::from_string_literal("Cranelift compiler returned an invalid buffer");
-
- auto const code_region_size = reloc_region_start - code_base_offset;
- auto const reloc_region_size = compact_output_size - reloc_region_start;
-
- for (size_t i = 0; i < function_count; ++i) {
- auto const& output = *reinterpret_cast<OutputFunctionEntry const*>(output_base + output_entries_offset + i * sizeof(OutputFunctionEntry));
- if (!output.compiled)
- continue;
-
- auto code_offset = static_cast<size_t>(output.code_offset);
- auto code_size = static_cast<size_t>(output.code_size);
- if (code_offset > code_region_size || code_size > code_region_size - code_offset)
- continue;
- auto code_start = code_base_offset + code_offset;
- if (code_start + code_size > compact_output_size)
- continue;
-
- auto const reloc_offset = static_cast<size_t>(output.reloc_offset);
- auto const reloc_count = static_cast<size_t>(output.reloc_count);
- auto const reloc_bytes = reloc_count * sizeof(HelperReloc);
- if (reloc_count != 0 && reloc_bytes / sizeof(HelperReloc) != reloc_count)
- continue;
- if (reloc_offset % alignof(HelperReloc) != 0)
- continue;
- if (reloc_offset > reloc_region_size || reloc_bytes > reloc_region_size - reloc_offset)
- continue;
- if (reloc_region_start + reloc_offset + reloc_bytes > compact_output_size)
- continue;
-
- auto const trap_offset = static_cast<size_t>(output.trap_offset);
- auto const trap_count = static_cast<size_t>(output.trap_count);
- auto const trap_bytes = trap_count * sizeof(CraneliftTrap);
- if (trap_count != 0 && trap_bytes / sizeof(CraneliftTrap) != trap_count)
- continue;
- if (trap_offset % alignof(CraneliftTrap) != 0)
- continue;
- if (trap_offset > reloc_region_size || trap_bytes > reloc_region_size - trap_offset)
- continue;
- if (reloc_region_start + trap_offset + trap_bytes > compact_output_size)
- continue;
-
- auto code_bytes = ReadonlyBytes { output_base + code_start, code_size };
- auto const* relocs = reloc_count == 0
- ? nullptr
- : reinterpret_cast<HelperReloc const*>(output_base + reloc_region_start + reloc_offset);
- auto traps = trap_count == 0
- ? ReadonlySpan<CraneliftTrap> {}
- : ReadonlySpan<CraneliftTrap> { reinterpret_cast<CraneliftTrap const*>(output_base + reloc_region_start + trap_offset), trap_count };
-
- auto& capture = cranelift_cache_state().cache_capture;
- if (capture.capturing && batch[i].function_index != NumericLimits<u32>::max()) {
- if (auto copy = ByteBuffer::copy(code_bytes.data(), code_bytes.size()); !copy.is_error()) {
- CacheRecord rec;
- rec.function_index = batch[i].function_index;
- rec.unpatched_code = copy.release_value();
- rec.relocs.ensure_capacity(reloc_count);
- for (size_t j = 0; j < reloc_count; ++j)
- rec.relocs.unchecked_append(relocs[j]);
- rec.traps.ensure_capacity(trap_count);
- for (size_t j = 0; j < trap_count; ++j)
- rec.traps.unchecked_append(traps[j]);
- capture.records.append(move(rec));
- }
- }
-
- install_compiled_function(*batch[i].target, code_bytes, relocs, reloc_count, traps, helper_addresses);
- }
-
- return {};
-}
-
-bool try_cranelift_compile(CompiledInstructions& compiled, u32 result_arity)
-{
-#if !WASM_COMPILED_FAULT_RECOVERY_SUPPORTED
- (void)compiled;
- (void)result_arity;
- return false;
-#else
- auto const& dispatches = compiled.dispatches;
- auto const& addresses = compiled.src_dst_mappings;
-
- if (dispatches.is_empty())
- return false;
-
- // Already installed (either from a prior compile or a previous cache install in this
- // same validation pass) -- nothing to do.
- if (compiled.cranelift_compiled)
- return true;
-
- if (s_active_function_index == NumericLimits<u32>::max())
- return false;
-
- // Cache hit: install from the parsed blob instead of going through cranelift.
- // dispatches[] has just been populated by try_compile_instructions, so handler_ptr is ready to be set.
- if (cranelift_cache_state().pending_install.active && s_active_function_index != NumericLimits<u32>::max()) {
- auto record = cranelift_cache_state().pending_install.records.take(s_active_function_index);
- if (record.has_value()) {
- static auto cache_install_helper_addresses = make_runtime_helper_addresses();
- if (install_compiled_function(
- compiled,
- record->unpatched_code.bytes(),
- record->relocs.is_empty() ? nullptr : record->relocs.data(),
- record->relocs.size(),
- record->traps.span(),
- cache_install_helper_addresses)) {
- return true;
- }
- // Put it back so we can try later.
- cranelift_cache_state().pending_install.records.set(s_active_function_index, record.release_value());
- }
- }
-
- if constexpr (WASM_CRANELIFT_DEBUG) {
- // CRANELIFT_MAX_INSNS=N skip functions with more than N dispatches.
- // CRANELIFT_MIN_INSNS=N skip functions with fewer than N dispatches.
- // CRANELIFT_MIN_FN=N skip functions with id < N.
- // CRANELIFT_MAX_FN=N skip functions with id > N.
- // CRANELIFT_SKIP_FN=a,b,c skip listed function ids.
- // CRANELIFT_ONLY_FN=a,b,c only compile listed function ids.
- // CRANELIFT_TRACE=1 log a line per compiled function.
- static auto const read_size_env = [](char const* name, size_t fallback) {
- if (auto* env = getenv(name))
- return static_cast<size_t>(atol(env));
- return fallback;
- };
- static auto const read_set_env = [](char const* name) {
- HashTable<size_t> out;
- auto* env = getenv(name);
- if (!env || !*env)
- return out;
- StringView view { env, strlen(env) };
- view.for_each_split_view(',', SplitBehavior::Nothing, [&](auto part) {
- if (auto n = part.template to_number<size_t>(); n.has_value())
- out.set(n.value());
- });
- return out;
- };
- static size_t s_max_insns = read_size_env("CRANELIFT_MAX_INSNS", NumericLimits<size_t>::max());
- static size_t s_min_insns = read_size_env("CRANELIFT_MIN_INSNS", 0);
- static size_t s_min_fn = read_size_env("CRANELIFT_MIN_FN", 0);
- static size_t s_max_fn = read_size_env("CRANELIFT_MAX_FN", NumericLimits<size_t>::max());
- static auto& s_skip_fn = *new HashTable<size_t>(read_set_env("CRANELIFT_SKIP_FN"));
- static auto& s_only_fn = *new HashTable<size_t>(read_set_env("CRANELIFT_ONLY_FN"));
- static auto& s_dump_fn = *new HashTable<size_t>(read_set_env("CRANELIFT_DUMP_FN"));
- static bool s_trace = getenv("CRANELIFT_TRACE") != nullptr;
-
- static size_t s_func_counter = 0;
- size_t func_id = s_func_counter++;
-
- if (dispatches.size() > s_max_insns || dispatches.size() < s_min_insns)
- return false;
- if (func_id < s_min_fn || func_id > s_max_fn)
- return false;
- if (s_skip_fn.contains(func_id))
- return false;
- if (!s_only_fn.is_empty() && !s_only_fn.contains(func_id))
- return false;
- if (s_trace)
- warnln("cranelift: compiling fn#{} ({} dispatches)", func_id, dispatches.size());
-
- if (s_dump_fn.contains(func_id)) {
- warnln("cranelift: dump fn#{} ({} dispatches)", func_id, dispatches.size());
- auto reg_name = [](Dispatch::RegisterOrStack reg) -> ByteString {
- if (reg == Dispatch::RegisterOrStack::Stack)
- return "stack";
- if (reg >= Dispatch::RegisterOrStack::CallRecord)
- return ByteString::formatted("cr{}", to_underlying(reg) - to_underlying(Dispatch::RegisterOrStack::CallRecord));
- return ByteString::formatted("reg{}", to_underlying(reg));
- };
- for (size_t ip = 0; ip < dispatches.size(); ++ip) {
- auto const& dispatch = dispatches[ip];
- auto const& addr = addresses[ip];
- ssize_t in_count = 0;
- ssize_t out_count = 0;
-# define M(name, _, ins, outs) \
- case Instructions::name.value(): \
- in_count = ins; \
- out_count = outs; \
- break;
- switch (dispatch.instruction->opcode().value()) {
- ENUMERATE_WASM_OPCODES(M)
- }
-# undef M
- StringBuilder regs;
- regs.append('(');
- for (ssize_t j = 0; j < (in_count < 0 ? 3 : in_count); ++j) {
- if (j > 0)
- regs.append(", "sv);
- regs.append(reg_name(addr.sources[j]));
- }
- regs.append(')');
- if (out_count > 0) {
- regs.appendff(" -> {}", reg_name(addr.destination));
- }
- warnln(" [{:>03}] {} {} dst={}", ip, instruction_name(dispatch.instruction->opcode()), regs.to_byte_string(), reg_name(addr.destination));
- }
- }
- }
-
- Vector<CraneliftInsn> flat;
- flat.ensure_capacity(dispatches.size());
- for (size_t i = 0; i < dispatches.size(); ++i) {
- flat.append(serialize_insn(dispatches[i], addresses[i]));
-
- if (dispatches[i].instruction->opcode().value() == Instructions::synthetic_tier_up.value())
- flat.last().imm1 = static_cast<i64>(i);
-
- if (dispatches[i].instruction->opcode().value() == Instructions::br_table.value()) {
- auto const& table_args = dispatches[i].instruction->arguments().get<Instruction::TableBranchArgs>();
- auto const total = table_args.labels.size();
- for (size_t base = 8; base < total; base += 8) {
- CraneliftInsn cont {};
- cont.opcode = Instructions::synthetic_br_table_cont.value();
- auto const chunk = min(total - base, static_cast<size_t>(8));
- cont.imm3 = static_cast<u32>(chunk);
- for (size_t j = 0; j < chunk; ++j) {
- auto const encoded = static_cast<u64>(table_args.labels[base + j].value()) << ((j % 4) * 16);
- if (j < 4)
- cont.imm1 |= static_cast<i64>(encoded);
- else
- cont.imm2 |= static_cast<i64>(encoded);
- }
- flat.append(cont);
- }
- }
- }
-
- cranelift_cache_state().pending_batch.append({ move(flat), result_arity, s_active_function_index, &compiled, compiled.cranelift_local_count, compiled.cranelift_param_count });
- return false; // Not compiled yet, will be compiled in flush.
-#endif
-}
-
-void flush_cranelift_batch()
-{
- if (cranelift_cache_state().pending_batch.is_empty())
- return;
-
- auto result = try_cranelift_compile_batch(cranelift_cache_state().pending_batch);
- if (result.is_error())
- warnln("Cranelift compilation failed: {}", result.error());
-
- cranelift_cache_state().pending_batch.clear();
-}
-
-void discard_cranelift_batch()
-{
- cranelift_cache_state().pending_batch.clear();
-}
-
-void free_cranelift_code(void* handle)
-{
- if (handle) {
- auto* mapping = static_cast<CodeMapping*>(handle);
-#if defined(AK_OS_WINDOWS)
- VirtualFree(mapping->mapping, 0, MEM_RELEASE);
-#else
- munmap(mapping->mapping, mapping->size);
-#endif
- delete mapping;
- }
-}
-
-void set_cranelift_active_function_index(u32 function_index)
-{
- s_active_function_index = function_index;
-}
-
-void begin_cranelift_cache_capture()
-{
- cranelift_cache_state().cache_capture.capturing = true;
- cranelift_cache_state().cache_capture.records.clear();
-}
-
-void abort_cranelift_cache_capture()
-{
- cranelift_cache_state().cache_capture.capturing = false;
- cranelift_cache_state().cache_capture.records.clear();
-}
-
-void abort_cranelift_cache_install()
-{
- cranelift_cache_state().pending_install.active = false;
- cranelift_cache_state().pending_install.records.clear();
-}
-
-Optional<ByteBuffer> serialize_cranelift_cache_blob(ReadonlyBytes wasm_hash)
-{
- ScopeGuard reset = [] {
- cranelift_cache_state().cache_capture.capturing = false;
- cranelift_cache_state().cache_capture.records.clear();
- };
-
- auto const& capture = cranelift_cache_state().cache_capture;
-
- if (!capture.capturing || capture.records.is_empty())
- return {};
- if (wasm_hash.size() != 32)
- return {};
-
- size_t total_size = sizeof(CacheBlobHeader);
- for (auto const& r : capture.records) {
- total_size += sizeof(CacheBlobFunctionEntry);
- total_size += align_up(r.unpatched_code.size(), 16);
- total_size += r.relocs.size() * sizeof(HelperReloc);
- total_size += r.traps.size() * sizeof(CraneliftTrap);
- }
-
- auto blob_or_error = ByteBuffer::create_zeroed(total_size);
- if (blob_or_error.is_error())
- return {};
- auto blob = blob_or_error.release_value();
- auto* out = blob.data();
-
- auto* header = reinterpret_cast<CacheBlobHeader*>(out);
- header->magic = cache_blob_magic;
- header->format_version = cache_blob_format_version;
- header->helper_count = HELPER_COUNT;
- header->layout_hash = runtime_layout_hash();
- __builtin_memcpy(header->wasm_hash, wasm_hash.data(), 32);
- header->function_count = static_cast<u32>(capture.records.size());
-
- size_t offset = sizeof(CacheBlobHeader);
- for (auto const& r : capture.records) {
- auto* entry = reinterpret_cast<CacheBlobFunctionEntry*>(out + offset);
- entry->function_index = r.function_index;
- entry->code_size = static_cast<u32>(r.unpatched_code.size());
- entry->reloc_count = static_cast<u32>(r.relocs.size());
- entry->trap_count = static_cast<u32>(r.traps.size());
- offset += sizeof(CacheBlobFunctionEntry);
-
- __builtin_memcpy(out + offset, r.unpatched_code.data(), r.unpatched_code.size());
- offset += align_up(r.unpatched_code.size(), 16);
-
- auto reloc_bytes = r.relocs.size() * sizeof(HelperReloc);
- if (reloc_bytes > 0)
- __builtin_memcpy(out + offset, r.relocs.data(), reloc_bytes);
- offset += reloc_bytes;
-
- auto trap_bytes = r.traps.size() * sizeof(CraneliftTrap);
- if (trap_bytes > 0)
- __builtin_memcpy(out + offset, r.traps.data(), trap_bytes);
- offset += trap_bytes;
- }
-
- return blob;
-}
-
-bool try_install_cranelift_cache_blob(ReadonlyBytes expected_wasm_hash, ReadonlyBytes blob)
-{
- abort_cranelift_cache_install();
-
- if (expected_wasm_hash.size() != 32 || blob.size() < sizeof(CacheBlobHeader))
- return false;
-
- auto const* header = reinterpret_cast<CacheBlobHeader const*>(blob.data());
- if (header->magic != cache_blob_magic)
- return false;
- if (header->format_version != cache_blob_format_version)
- return false;
- if (header->helper_count != HELPER_COUNT)
- return false;
- if (__builtin_memcmp(header->wasm_hash, expected_wasm_hash.data(), 32) != 0)
- return false;
-
- if (header->layout_hash != runtime_layout_hash())
- return false;
-
- size_t offset = sizeof(CacheBlobHeader);
- for (u32 i = 0; i < header->function_count; ++i) {
- if (offset + sizeof(CacheBlobFunctionEntry) > blob.size())
- return false;
- auto const* entry = reinterpret_cast<CacheBlobFunctionEntry const*>(blob.data() + offset);
- offset += sizeof(CacheBlobFunctionEntry);
-
- auto code_off = offset;
- auto aligned_code_size = align_up(entry->code_size, 16);
- if (code_off + aligned_code_size > blob.size())
- return false;
- offset += aligned_code_size;
-
- auto reloc_off = offset;
- auto reloc_bytes = static_cast<size_t>(entry->reloc_count) * sizeof(HelperReloc);
- if (reloc_off + reloc_bytes > blob.size())
- return false;
- offset += reloc_bytes;
-
- auto trap_off = offset;
- auto trap_bytes = static_cast<size_t>(entry->trap_count) * sizeof(CraneliftTrap);
- if (trap_off + trap_bytes > blob.size())
- return false;
- offset += trap_bytes;
-
- auto code_copy = ByteBuffer::copy(blob.data() + code_off, entry->code_size);
- if (code_copy.is_error())
- return false;
-
- CacheRecord rec;
- rec.function_index = entry->function_index;
- rec.unpatched_code = code_copy.release_value();
- rec.relocs.ensure_capacity(entry->reloc_count);
- for (u32 j = 0; j < entry->reloc_count; ++j) {
- HelperReloc reloc;
- __builtin_memcpy(&reloc, blob.data() + reloc_off + j * sizeof(HelperReloc), sizeof(HelperReloc));
- rec.relocs.unchecked_append(reloc);
- }
- rec.traps.ensure_capacity(entry->trap_count);
- for (u32 j = 0; j < entry->trap_count; ++j) {
- CraneliftTrap trap;
- __builtin_memcpy(&trap, blob.data() + trap_off + j * sizeof(CraneliftTrap), sizeof(CraneliftTrap));
- rec.traps.unchecked_append(trap);
- }
- cranelift_cache_state().pending_install.records.set(entry->function_index, move(rec));
- }
-
- cranelift_cache_state().pending_install.active = true;
- return true;
-}
-
-void set_cranelift_compile_callback(CraneliftCompileCallback callback)
-{
- auto& installed_callback = cranelift_compile_callback();
- VERIFY(!installed_callback);
-
- installed_callback = move(callback);
-}
-
-}
diff --git a/Libraries/LibWasm/CraneliftStubs.cpp b/Libraries/LibWasm/CraneliftStubs.cpp
deleted file mode 100644
index 015ef7a91e9..00000000000
--- a/Libraries/LibWasm/CraneliftStubs.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2026-present, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NeverDestroyed.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-bool try_cranelift_compile(CompiledInstructions&, u32) { return false; }
-void flush_cranelift_batch() { }
-void discard_cranelift_batch() { }
-void free_cranelift_code(void*) { }
-void set_cranelift_active_function_index(u32) { }
-void begin_cranelift_cache_capture() { }
-void abort_cranelift_cache_capture() { }
-void abort_cranelift_cache_install() { }
-Optional<ByteBuffer> serialize_cranelift_cache_blob(ReadonlyBytes) { return {}; }
-bool try_install_cranelift_cache_blob(ReadonlyBytes, ReadonlyBytes) { return false; }
-void set_cranelift_compile_callback(CraneliftCompileCallback) { }
-
-ErrorOr<Core::AnonymousBuffer> compile_cranelift_buffer(Core::AnonymousBuffer const&)
-{
- return Error::from_string_literal("Cranelift is disabled");
-}
-
-ByteString const& cranelift_compiler_path()
-{
- static NeverDestroyed<ByteString> path;
- return *path;
-}
-
-}
diff --git a/Libraries/LibWasm/Forward.h b/Libraries/LibWasm/Forward.h
deleted file mode 100644
index 6dd4f7a4421..00000000000
--- a/Libraries/LibWasm/Forward.h
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-namespace Wasm {
-
-class AbstractMachine;
-class Validator;
-struct ValidationError;
-struct Interpreter;
-class MemoryBuffer;
-
-namespace Wasi {
-
-struct Implementation;
-
-}
-
-}
diff --git a/Libraries/LibWasm/Opcode.h b/Libraries/LibWasm/Opcode.h
deleted file mode 100644
index e19a56b7229..00000000000
--- a/Libraries/LibWasm/Opcode.h
+++ /dev/null
@@ -1,613 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/DistinctNumeric.h>
-
-namespace Wasm {
-
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, OpCode);
-
-namespace Instructions {
-
-// name, opcode, pops, pushes
-#define ENUMERATE_SINGLE_BYTE_WASM_OPCODES(M) \
- M(unreachable, 0x00, 0, 0) \
- M(nop, 0x01, 0, 0) \
- M(block, 0x02, 0, -1) \
- M(loop, 0x03, 0, -1) \
- M(if_, 0x04, 1, -1) \
- M(structured_else, 0x05, -1, -1) \
- M(throw_, 0x08, -1, -1) \
- M(throw_ref, 0x0a, 1, -1) \
- M(structured_end, 0x0b, -1, -1) \
- M(br, 0x0c, 0, -1) \
- M(br_if, 0x0d, 1, -1) \
- M(br_table, 0x0e, 1, -1) \
- M(return_, 0x0f, -1, -1) \
- M(call, 0x10, -1, -1) \
- M(call_indirect, 0x11, -1, -1) \
- M(return_call, 0x12, -1, -1) \
- M(return_call_indirect, 0x13, -1, -1) \
- M(call_ref, 0x14, -1, -1) \
- M(return_call_ref, 0x15, -1, -1) \
- M(drop, 0x1a, 1, 0) \
- M(select, 0x1b, 3, 1) \
- M(select_typed, 0x1c, 3, 1) \
- M(try_table, 0x1f, 0, -1) \
- M(local_get, 0x20, 0, 1) \
- M(local_set, 0x21, 1, 0) \
- M(local_tee, 0x22, 1, 1) \
- M(global_get, 0x23, 0, 1) \
- M(global_set, 0x24, 1, 0) \
- M(table_get, 0x25, 1, 1) \
- M(table_set, 0x26, 2, 0) \
- M(i32_load, 0x28, 1, 1) \
- M(i64_load, 0x29, 1, 1) \
- M(f32_load, 0x2a, 1, 1) \
- M(f64_load, 0x2b, 1, 1) \
- M(i32_load8_s, 0x2c, 1, 1) \
- M(i32_load8_u, 0x2d, 1, 1) \
- M(i32_load16_s, 0x2e, 1, 1) \
- M(i32_load16_u, 0x2f, 1, 1) \
- M(i64_load8_s, 0x30, 1, 1) \
- M(i64_load8_u, 0x31, 1, 1) \
- M(i64_load16_s, 0x32, 1, 1) \
- M(i64_load16_u, 0x33, 1, 1) \
- M(i64_load32_s, 0x34, 1, 1) \
- M(i64_load32_u, 0x35, 1, 1) \
- M(i32_store, 0x36, 2, 0) \
- M(i64_store, 0x37, 2, 0) \
- M(f32_store, 0x38, 2, 0) \
- M(f64_store, 0x39, 2, 0) \
- M(i32_store8, 0x3a, 2, 0) \
- M(i32_store16, 0x3b, 2, 0) \
- M(i64_store8, 0x3c, 2, 0) \
- M(i64_store16, 0x3d, 2, 0) \
- M(i64_store32, 0x3e, 2, 0) \
- M(memory_size, 0x3f, 0, 1) \
- M(memory_grow, 0x40, 1, 1) \
- M(i32_const, 0x41, 0, 1) \
- M(i64_const, 0x42, 0, 1) \
- M(f32_const, 0x43, 0, 1) \
- M(f64_const, 0x44, 0, 1) \
- M(i32_eqz, 0x45, 1, 1) \
- M(i32_eq, 0x46, 2, 1) \
- M(i32_ne, 0x47, 2, 1) \
- M(i32_lts, 0x48, 2, 1) \
- M(i32_ltu, 0x49, 2, 1) \
- M(i32_gts, 0x4a, 2, 1) \
- M(i32_gtu, 0x4b, 2, 1) \
- M(i32_les, 0x4c, 2, 1) \
- M(i32_leu, 0x4d, 2, 1) \
- M(i32_ges, 0x4e, 2, 1) \
- M(i32_geu, 0x4f, 2, 1) \
- M(i64_eqz, 0x50, 1, 1) \
- M(i64_eq, 0x51, 2, 1) \
- M(i64_ne, 0x52, 2, 1) \
- M(i64_lts, 0x53, 2, 1) \
- M(i64_ltu, 0x54, 2, 1) \
- M(i64_gts, 0x55, 2, 1) \
- M(i64_gtu, 0x56, 2, 1) \
- M(i64_les, 0x57, 2, 1) \
- M(i64_leu, 0x58, 2, 1) \
- M(i64_ges, 0x59, 2, 1) \
- M(i64_geu, 0x5a, 2, 1) \
- M(f32_eq, 0x5b, 2, 1) \
- M(f32_ne, 0x5c, 2, 1) \
- M(f32_lt, 0x5d, 2, 1) \
- M(f32_gt, 0x5e, 2, 1) \
- M(f32_le, 0x5f, 2, 1) \
- M(f32_ge, 0x60, 2, 1) \
- M(f64_eq, 0x61, 2, 1) \
- M(f64_ne, 0x62, 2, 1) \
- M(f64_lt, 0x63, 2, 1) \
- M(f64_gt, 0x64, 2, 1) \
- M(f64_le, 0x65, 2, 1) \
- M(f64_ge, 0x66, 2, 1) \
- M(i32_clz, 0x67, 1, 1) \
- M(i32_ctz, 0x68, 1, 1) \
- M(i32_popcnt, 0x69, 1, 1) \
- M(i32_add, 0x6a, 2, 1) \
- M(i32_sub, 0x6b, 2, 1) \
- M(i32_mul, 0x6c, 2, 1) \
- M(i32_divs, 0x6d, 2, 1) \
- M(i32_divu, 0x6e, 2, 1) \
- M(i32_rems, 0x6f, 2, 1) \
- M(i32_remu, 0x70, 2, 1) \
- M(i32_and, 0x71, 2, 1) \
- M(i32_or, 0x72, 2, 1) \
- M(i32_xor, 0x73, 2, 1) \
- M(i32_shl, 0x74, 2, 1) \
- M(i32_shrs, 0x75, 2, 1) \
- M(i32_shru, 0x76, 2, 1) \
- M(i32_rotl, 0x77, 2, 1) \
- M(i32_rotr, 0x78, 2, 1) \
- M(i64_clz, 0x79, 1, 1) \
- M(i64_ctz, 0x7a, 1, 1) \
- M(i64_popcnt, 0x7b, 1, 1) \
- M(i64_add, 0x7c, 2, 1) \
- M(i64_sub, 0x7d, 2, 1) \
- M(i64_mul, 0x7e, 2, 1) \
- M(i64_divs, 0x7f, 2, 1) \
- M(i64_divu, 0x80, 2, 1) \
- M(i64_rems, 0x81, 2, 1) \
- M(i64_remu, 0x82, 2, 1) \
- M(i64_and, 0x83, 2, 1) \
- M(i64_or, 0x84, 2, 1) \
- M(i64_xor, 0x85, 2, 1) \
- M(i64_shl, 0x86, 2, 1) \
- M(i64_shrs, 0x87, 2, 1) \
- M(i64_shru, 0x88, 2, 1) \
- M(i64_rotl, 0x89, 2, 1) \
- M(i64_rotr, 0x8a, 2, 1) \
- M(f32_abs, 0x8b, 1, 1) \
- M(f32_neg, 0x8c, 1, 1) \
- M(f32_ceil, 0x8d, 1, 1) \
- M(f32_floor, 0x8e, 1, 1) \
- M(f32_trunc, 0x8f, 1, 1) \
- M(f32_nearest, 0x90, 1, 1) \
- M(f32_sqrt, 0x91, 1, 1) \
- M(f32_add, 0x92, 2, 1) \
- M(f32_sub, 0x93, 2, 1) \
- M(f32_mul, 0x94, 2, 1) \
- M(f32_div, 0x95, 2, 1) \
- M(f32_min, 0x96, 2, 1) \
- M(f32_max, 0x97, 2, 1) \
- M(f32_copysign, 0x98, 2, 1) \
- M(f64_abs, 0x99, 1, 1) \
- M(f64_neg, 0x9a, 1, 1) \
- M(f64_ceil, 0x9b, 1, 1) \
- M(f64_floor, 0x9c, 1, 1) \
- M(f64_trunc, 0x9d, 1, 1) \
- M(f64_nearest, 0x9e, 1, 1) \
- M(f64_sqrt, 0x9f, 1, 1) \
- M(f64_add, 0xa0, 2, 1) \
- M(f64_sub, 0xa1, 2, 1) \
- M(f64_mul, 0xa2, 2, 1) \
- M(f64_div, 0xa3, 2, 1) \
- M(f64_min, 0xa4, 2, 1) \
- M(f64_max, 0xa5, 2, 1) \
- M(f64_copysign, 0xa6, 2, 1) \
- M(i32_wrap_i64, 0xa7, 1, 1) \
- M(i32_trunc_sf32, 0xa8, 1, 1) \
- M(i32_trunc_uf32, 0xa9, 1, 1) \
- M(i32_trunc_sf64, 0xaa, 1, 1) \
- M(i32_trunc_uf64, 0xab, 1, 1) \
- M(i64_extend_si32, 0xac, 1, 1) \
- M(i64_extend_ui32, 0xad, 1, 1) \
- M(i64_trunc_sf32, 0xae, 1, 1) \
- M(i64_trunc_uf32, 0xaf, 1, 1) \
- M(i64_trunc_sf64, 0xb0, 1, 1) \
- M(i64_trunc_uf64, 0xb1, 1, 1) \
- M(f32_convert_si32, 0xb2, 1, 1) \
- M(f32_convert_ui32, 0xb3, 1, 1) \
- M(f32_convert_si64, 0xb4, 1, 1) \
- M(f32_convert_ui64, 0xb5, 1, 1) \
- M(f32_demote_f64, 0xb6, 1, 1) \
- M(f64_convert_si32, 0xb7, 1, 1) \
- M(f64_convert_ui32, 0xb8, 1, 1) \
- M(f64_convert_si64, 0xb9, 1, 1) \
- M(f64_convert_ui64, 0xba, 1, 1) \
- M(f64_promote_f32, 0xbb, 1, 1) \
- M(i32_reinterpret_f32, 0xbc, 1, 1) \
- M(i64_reinterpret_f64, 0xbd, 1, 1) \
- M(f32_reinterpret_i32, 0xbe, 1, 1) \
- M(f64_reinterpret_i64, 0xbf, 1, 1) \
- M(i32_extend8_s, 0xc0, 1, 1) \
- M(i32_extend16_s, 0xc1, 1, 1) \
- M(i64_extend8_s, 0xc2, 1, 1) \
- M(i64_extend16_s, 0xc3, 1, 1) \
- M(i64_extend32_s, 0xc4, 1, 1) \
- M(ref_null, 0xd0, 0, 1) \
- M(ref_is_null, 0xd1, 1, 1) \
- M(ref_func, 0xd2, 0, 1) \
- M(ref_eq, 0xd3, 2, 1) \
- M(ref_as_non_null, 0xd4, 1, 1) \
- M(br_on_null, 0xd5, 1, -1) \
- M(br_on_non_null, 0xd6, 1, -1)
-
-// These are synthetic opcodes, they are _not_ seen in wasm with these values.
-#define ENUMERATE_MULTI_BYTE_WASM_OPCODES(M) \
- M(i32_trunc_sat_f32_s, 0xfc000000u, 1, 1) \
- M(i32_trunc_sat_f32_u, 0xfc000001u, 1, 1) \
- M(i32_trunc_sat_f64_s, 0xfc000002u, 1, 1) \
- M(i32_trunc_sat_f64_u, 0xfc000003u, 1, 1) \
- M(i64_trunc_sat_f32_s, 0xfc000004u, 1, 1) \
- M(i64_trunc_sat_f32_u, 0xfc000005u, 1, 1) \
- M(i64_trunc_sat_f64_s, 0xfc000006u, 1, 1) \
- M(i64_trunc_sat_f64_u, 0xfc000007u, 1, 1) \
- M(memory_init, 0xfc000008u, 3, 0) \
- M(data_drop, 0xfc000009u, 0, 0) \
- M(memory_copy, 0xfc00000au, 3, 0) \
- M(memory_fill, 0xfc00000bu, 3, 0) \
- M(table_init, 0xfc00000cu, 3, 0) \
- M(elem_drop, 0xfc00000du, 0, 0) \
- M(table_copy, 0xfc00000eu, 3, 0) \
- M(table_grow, 0xfc00000fu, 2, 1) \
- M(table_size, 0xfc000010u, 0, 1) \
- M(table_fill, 0xfc000011u, 3, 0) \
- M(v128_load, 0xfd000000u, 1, 1) \
- M(v128_load8x8_s, 0xfd000001u, 1, 1) \
- M(v128_load8x8_u, 0xfd000002u, 1, 1) \
- M(v128_load16x4_s, 0xfd000003u, 1, 1) \
- M(v128_load16x4_u, 0xfd000004u, 1, 1) \
- M(v128_load32x2_s, 0xfd000005u, 1, 1) \
- M(v128_load32x2_u, 0xfd000006u, 1, 1) \
- M(v128_load8_splat, 0xfd000007u, 1, 1) \
- M(v128_load16_splat, 0xfd000008u, 1, 1) \
- M(v128_load32_splat, 0xfd000009u, 1, 1) \
- M(v128_load64_splat, 0xfd00000au, 1, 1) \
- M(v128_store, 0xfd00000bu, 2, 0) \
- M(v128_const, 0xfd00000cu, 0, 1) \
- M(i8x16_shuffle, 0xfd00000du, 2, 1) \
- M(i8x16_swizzle, 0xfd00000eu, 2, 1) \
- M(i8x16_splat, 0xfd00000fu, 1, 1) \
- M(i16x8_splat, 0xfd000010u, 1, 1) \
- M(i32x4_splat, 0xfd000011u, 1, 1) \
- M(i64x2_splat, 0xfd000012u, 1, 1) \
- M(f32x4_splat, 0xfd000013u, 1, 1) \
- M(f64x2_splat, 0xfd000014u, 1, 1) \
- M(i8x16_extract_lane_s, 0xfd000015u, 1, 1) \
- M(i8x16_extract_lane_u, 0xfd000016u, 1, 1) \
- M(i8x16_replace_lane, 0xfd000017u, 2, 1) \
- M(i16x8_extract_lane_s, 0xfd000018u, 1, 1) \
- M(i16x8_extract_lane_u, 0xfd000019u, 1, 1) \
- M(i16x8_replace_lane, 0xfd00001au, 2, 1) \
- M(i32x4_extract_lane, 0xfd00001bu, 1, 1) \
- M(i32x4_replace_lane, 0xfd00001cu, 2, 1) \
- M(i64x2_extract_lane, 0xfd00001du, 1, 1) \
- M(i64x2_replace_lane, 0xfd00001eu, 2, 1) \
- M(f32x4_extract_lane, 0xfd00001fu, 1, 1) \
- M(f32x4_replace_lane, 0xfd000020u, 2, 1) \
- M(f64x2_extract_lane, 0xfd000021u, 1, 1) \
- M(f64x2_replace_lane, 0xfd000022u, 2, 1) \
- M(i8x16_eq, 0xfd000023u, 2, 1) \
- M(i8x16_ne, 0xfd000024u, 2, 1) \
- M(i8x16_lt_s, 0xfd000025u, 2, 1) \
- M(i8x16_lt_u, 0xfd000026u, 2, 1) \
- M(i8x16_gt_s, 0xfd000027u, 2, 1) \
- M(i8x16_gt_u, 0xfd000028u, 2, 1) \
- M(i8x16_le_s, 0xfd000029u, 2, 1) \
- M(i8x16_le_u, 0xfd00002au, 2, 1) \
- M(i8x16_ge_s, 0xfd00002bu, 2, 1) \
- M(i8x16_ge_u, 0xfd00002cu, 2, 1) \
- M(i16x8_eq, 0xfd00002du, 2, 1) \
- M(i16x8_ne, 0xfd00002eu, 2, 1) \
- M(i16x8_lt_s, 0xfd00002fu, 2, 1) \
- M(i16x8_lt_u, 0xfd000030u, 2, 1) \
- M(i16x8_gt_s, 0xfd000031u, 2, 1) \
- M(i16x8_gt_u, 0xfd000032u, 2, 1) \
- M(i16x8_le_s, 0xfd000033u, 2, 1) \
- M(i16x8_le_u, 0xfd000034u, 2, 1) \
- M(i16x8_ge_s, 0xfd000035u, 2, 1) \
- M(i16x8_ge_u, 0xfd000036u, 2, 1) \
- M(i32x4_eq, 0xfd000037u, 2, 1) \
- M(i32x4_ne, 0xfd000038u, 2, 1) \
- M(i32x4_lt_s, 0xfd000039u, 2, 1) \
- M(i32x4_lt_u, 0xfd00003au, 2, 1) \
- M(i32x4_gt_s, 0xfd00003bu, 2, 1) \
- M(i32x4_gt_u, 0xfd00003cu, 2, 1) \
- M(i32x4_le_s, 0xfd00003du, 2, 1) \
- M(i32x4_le_u, 0xfd00003eu, 2, 1) \
- M(i32x4_ge_s, 0xfd00003fu, 2, 1) \
- M(i32x4_ge_u, 0xfd000040u, 2, 1) \
- M(f32x4_eq, 0xfd000041u, 2, 1) \
- M(f32x4_ne, 0xfd000042u, 2, 1) \
- M(f32x4_lt, 0xfd000043u, 2, 1) \
- M(f32x4_gt, 0xfd000044u, 2, 1) \
- M(f32x4_le, 0xfd000045u, 2, 1) \
- M(f32x4_ge, 0xfd000046u, 2, 1) \
- M(f64x2_eq, 0xfd000047u, 2, 1) \
- M(f64x2_ne, 0xfd000048u, 2, 1) \
- M(f64x2_lt, 0xfd000049u, 2, 1) \
- M(f64x2_gt, 0xfd00004au, 2, 1) \
- M(f64x2_le, 0xfd00004bu, 2, 1) \
- M(f64x2_ge, 0xfd00004cu, 2, 1) \
- M(v128_not, 0xfd00004du, 1, 1) \
- M(v128_and, 0xfd00004eu, 2, 1) \
- M(v128_andnot, 0xfd00004fu, 2, 1) \
- M(v128_or, 0xfd000050u, 2, 1) \
- M(v128_xor, 0xfd000051u, 2, 1) \
- M(v128_bitselect, 0xfd000052u, 3, 1) \
- M(v128_any_true, 0xfd000053u, 1, 1) \
- M(v128_load8_lane, 0xfd000054u, 2, 1) \
- M(v128_load16_lane, 0xfd000055u, 2, 1) \
- M(v128_load32_lane, 0xfd000056u, 2, 1) \
- M(v128_load64_lane, 0xfd000057u, 2, 1) \
- M(v128_store8_lane, 0xfd000058u, 2, 0) \
- M(v128_store16_lane, 0xfd000059u, 2, 0) \
- M(v128_store32_lane, 0xfd00005au, 2, 0) \
- M(v128_store64_lane, 0xfd00005bu, 2, 0) \
- M(v128_load32_zero, 0xfd00005cu, 1, 1) \
- M(v128_load64_zero, 0xfd00005du, 1, 1) \
- M(f32x4_demote_f64x2_zero, 0xfd00005eu, 1, 1) \
- M(f64x2_promote_low_f32x4, 0xfd00005fu, 1, 1) \
- M(i8x16_abs, 0xfd000060u, 1, 1) \
- M(i8x16_neg, 0xfd000061u, 1, 1) \
- M(i8x16_popcnt, 0xfd000062u, 1, 1) \
- M(i8x16_all_true, 0xfd000063u, 1, 1) \
- M(i8x16_bitmask, 0xfd000064u, 1, 1) \
- M(i8x16_narrow_i16x8_s, 0xfd000065u, 2, 1) \
- M(i8x16_narrow_i16x8_u, 0xfd000066u, 2, 1) \
- M(f32x4_ceil, 0xfd000067u, 1, 1) \
- M(f32x4_floor, 0xfd000068u, 1, 1) \
- M(f32x4_trunc, 0xfd000069u, 1, 1) \
- M(f32x4_nearest, 0xfd00006au, 1, 1) \
- M(i8x16_shl, 0xfd00006bu, 2, 1) \
- M(i8x16_shr_s, 0xfd00006cu, 2, 1) \
- M(i8x16_shr_u, 0xfd00006du, 2, 1) \
- M(i8x16_add, 0xfd00006eu, 2, 1) \
- M(i8x16_add_sat_s, 0xfd00006fu, 2, 1) \
- M(i8x16_add_sat_u, 0xfd000070u, 2, 1) \
- M(i8x16_sub, 0xfd000071u, 2, 1) \
- M(i8x16_sub_sat_s, 0xfd000072u, 2, 1) \
- M(i8x16_sub_sat_u, 0xfd000073u, 2, 1) \
- M(f64x2_ceil, 0xfd000074u, 1, 1) \
- M(f64x2_floor, 0xfd000075u, 1, 1) \
- M(i8x16_min_s, 0xfd000076u, 2, 1) \
- M(i8x16_min_u, 0xfd000077u, 2, 1) \
- M(i8x16_max_s, 0xfd000078u, 2, 1) \
- M(i8x16_max_u, 0xfd000079u, 2, 1) \
- M(f64x2_trunc, 0xfd00007au, 1, 1) \
- M(i8x16_avgr_u, 0xfd00007bu, 2, 1) \
- M(i16x8_extadd_pairwise_i8x16_s, 0xfd00007cu, 1, 1) \
- M(i16x8_extadd_pairwise_i8x16_u, 0xfd00007du, 1, 1) \
- M(i32x4_extadd_pairwise_i16x8_s, 0xfd00007eu, 1, 1) \
- M(i32x4_extadd_pairwise_i16x8_u, 0xfd00007fu, 1, 1) \
- M(i16x8_abs, 0xfd000080u, 1, 1) \
- M(i16x8_neg, 0xfd000081u, 1, 1) \
- M(i16x8_q15mulr_sat_s, 0xfd000082u, 2, 1) \
- M(i16x8_all_true, 0xfd000083u, 1, 1) \
- M(i16x8_bitmask, 0xfd000084u, 1, 1) \
- M(i16x8_narrow_i32x4_s, 0xfd000085u, 2, 1) \
- M(i16x8_narrow_i32x4_u, 0xfd000086u, 2, 1) \
- M(i16x8_extend_low_i8x16_s, 0xfd000087u, 1, 1) \
- M(i16x8_extend_high_i8x16_s, 0xfd000088u, 1, 1) \
- M(i16x8_extend_low_i8x16_u, 0xfd000089u, 1, 1) \
- M(i16x8_extend_high_i8x16_u, 0xfd00008au, 1, 1) \
- M(i16x8_shl, 0xfd00008bu, 2, 1) \
- M(i16x8_shr_s, 0xfd00008cu, 2, 1) \
- M(i16x8_shr_u, 0xfd00008du, 2, 1) \
- M(i16x8_add, 0xfd00008eu, 2, 1) \
- M(i16x8_add_sat_s, 0xfd00008fu, 2, 1) \
- M(i16x8_add_sat_u, 0xfd000090u, 2, 1) \
- M(i16x8_sub, 0xfd000091u, 2, 1) \
- M(i16x8_sub_sat_s, 0xfd000092u, 2, 1) \
- M(i16x8_sub_sat_u, 0xfd000093u, 2, 1) \
- M(f64x2_nearest, 0xfd000094u, 1, 1) \
- M(i16x8_mul, 0xfd000095u, 2, 1) \
- M(i16x8_min_s, 0xfd000096u, 2, 1) \
- M(i16x8_min_u, 0xfd000097u, 2, 1) \
- M(i16x8_max_s, 0xfd000098u, 2, 1) \
- M(i16x8_max_u, 0xfd000099u, 2, 1) \
- M(i16x8_avgr_u, 0xfd00009bu, 2, 1) \
- M(i16x8_extmul_low_i8x16_s, 0xfd00009cu, 2, 1) \
- M(i16x8_extmul_high_i8x16_s, 0xfd00009du, 2, 1) \
- M(i16x8_extmul_low_i8x16_u, 0xfd00009eu, 2, 1) \
- M(i16x8_extmul_high_i8x16_u, 0xfd00009fu, 2, 1) \
- M(i32x4_abs, 0xfd0000a0u, 1, 1) \
- M(i32x4_neg, 0xfd0000a1u, 1, 1) \
- M(i32x4_all_true, 0xfd0000a3u, 1, 1) \
- M(i32x4_bitmask, 0xfd0000a4u, 1, 1) \
- M(i32x4_extend_low_i16x8_s, 0xfd0000a7u, 1, 1) \
- M(i32x4_extend_high_i16x8_s, 0xfd0000a8u, 1, 1) \
- M(i32x4_extend_low_i16x8_u, 0xfd0000a9u, 1, 1) \
- M(i32x4_extend_high_i16x8_u, 0xfd0000aau, 1, 1) \
- M(i32x4_shl, 0xfd0000abu, 2, 1) \
- M(i32x4_shr_s, 0xfd0000acu, 2, 1) \
- M(i32x4_shr_u, 0xfd0000adu, 2, 1) \
- M(i32x4_add, 0xfd0000aeu, 2, 1) \
- M(i32x4_sub, 0xfd0000b1u, 2, 1) \
- M(i32x4_mul, 0xfd0000b5u, 2, 1) \
- M(i32x4_min_s, 0xfd0000b6u, 2, 1) \
- M(i32x4_min_u, 0xfd0000b7u, 2, 1) \
- M(i32x4_max_s, 0xfd0000b8u, 2, 1) \
- M(i32x4_max_u, 0xfd0000b9u, 2, 1) \
- M(i32x4_dot_i16x8_s, 0xfd0000bau, 2, 1) \
- M(i32x4_extmul_low_i16x8_s, 0xfd0000bcu, 2, 1) \
- M(i32x4_extmul_high_i16x8_s, 0xfd0000bdu, 2, 1) \
- M(i32x4_extmul_low_i16x8_u, 0xfd0000beu, 2, 1) \
- M(i32x4_extmul_high_i16x8_u, 0xfd0000bfu, 2, 1) \
- M(i64x2_abs, 0xfd0000c0u, 1, 1) \
- M(i64x2_neg, 0xfd0000c1u, 1, 1) \
- M(i64x2_all_true, 0xfd0000c3u, 1, 1) \
- M(i64x2_bitmask, 0xfd0000c4u, 1, 1) \
- M(i64x2_extend_low_i32x4_s, 0xfd0000c7u, 1, 1) \
- M(i64x2_extend_high_i32x4_s, 0xfd0000c8u, 1, 1) \
- M(i64x2_extend_low_i32x4_u, 0xfd0000c9u, 1, 1) \
- M(i64x2_extend_high_i32x4_u, 0xfd0000cau, 1, 1) \
- M(i64x2_shl, 0xfd0000cbu, 2, 1) \
- M(i64x2_shr_s, 0xfd0000ccu, 2, 1) \
- M(i64x2_shr_u, 0xfd0000cdu, 2, 1) \
- M(i64x2_add, 0xfd0000ceu, 2, 1) \
- M(i64x2_sub, 0xfd0000d1u, 2, 1) \
- M(i64x2_mul, 0xfd0000d5u, 2, 1) \
- M(i64x2_eq, 0xfd0000d6u, 2, 1) \
- M(i64x2_ne, 0xfd0000d7u, 2, 1) \
- M(i64x2_lt_s, 0xfd0000d8u, 2, 1) \
- M(i64x2_gt_s, 0xfd0000d9u, 2, 1) \
- M(i64x2_le_s, 0xfd0000dau, 2, 1) \
- M(i64x2_ge_s, 0xfd0000dbu, 2, 1) \
- M(i64x2_extmul_low_i32x4_s, 0xfd0000dcu, 2, 1) \
- M(i64x2_extmul_high_i32x4_s, 0xfd0000ddu, 2, 1) \
- M(i64x2_extmul_low_i32x4_u, 0xfd0000deu, 2, 1) \
- M(i64x2_extmul_high_i32x4_u, 0xfd0000dfu, 2, 1) \
- M(f32x4_abs, 0xfd0000e0u, 1, 1) \
- M(f32x4_neg, 0xfd0000e1u, 1, 1) \
- M(f32x4_sqrt, 0xfd0000e3u, 1, 1) \
- M(f32x4_add, 0xfd0000e4u, 2, 1) \
- M(f32x4_sub, 0xfd0000e5u, 2, 1) \
- M(f32x4_mul, 0xfd0000e6u, 2, 1) \
- M(f32x4_div, 0xfd0000e7u, 2, 1) \
- M(f32x4_min, 0xfd0000e8u, 2, 1) \
- M(f32x4_max, 0xfd0000e9u, 2, 1) \
- M(f32x4_pmin, 0xfd0000eau, 2, 1) \
- M(f32x4_pmax, 0xfd0000ebu, 2, 1) \
- M(f64x2_abs, 0xfd0000ecu, 1, 1) \
- M(f64x2_neg, 0xfd0000edu, 1, 1) \
- M(f64x2_sqrt, 0xfd0000efu, 1, 1) \
- M(f64x2_add, 0xfd0000f0u, 2, 1) \
- M(f64x2_sub, 0xfd0000f1u, 2, 1) \
- M(f64x2_mul, 0xfd0000f2u, 2, 1) \
- M(f64x2_div, 0xfd0000f3u, 2, 1) \
- M(f64x2_min, 0xfd0000f4u, 2, 1) \
- M(f64x2_max, 0xfd0000f5u, 2, 1) \
- M(f64x2_pmin, 0xfd0000f6u, 2, 1) \
- M(f64x2_pmax, 0xfd0000f7u, 2, 1) \
- M(i32x4_trunc_sat_f32x4_s, 0xfd0000f8u, 1, 1) \
- M(i32x4_trunc_sat_f32x4_u, 0xfd0000f9u, 1, 1) \
- M(f32x4_convert_i32x4_s, 0xfd0000fau, 1, 1) \
- M(f32x4_convert_i32x4_u, 0xfd0000fbu, 1, 1) \
- M(i32x4_trunc_sat_f64x2_s_zero, 0xfd0000fcu, 1, 1) \
- M(i32x4_trunc_sat_f64x2_u_zero, 0xfd0000fdu, 1, 1) \
- M(f64x2_convert_low_i32x4_s, 0xfd0000feu, 1, 1) \
- M(f64x2_convert_low_i32x4_u, 0xfd0000ffu, 1, 1) \
- M(i8x16_relaxed_swizzle, 0xfd000100u, 2, 1) \
- M(i32x4_relaxed_trunc_f32x4_s, 0xfd000101u, 1, 1) \
- M(i32x4_relaxed_trunc_f32x4_u, 0xfd000102u, 1, 1) \
- M(i32x4_relaxed_trunc_f64x2_s_zero, 0xfd000103u, 1, 1) \
- M(i32x4_relaxed_trunc_f64x2_u_zero, 0xfd000104u, 1, 1) \
- M(f32x4_relaxed_madd, 0xfd000105u, 3, 1) \
- M(f32x4_relaxed_nmadd, 0xfd000106u, 3, 1) \
- M(f64x2_relaxed_madd, 0xfd000107u, 3, 1) \
- M(f64x2_relaxed_nmadd, 0xfd000108u, 3, 1) \
- M(i8x16_relaxed_laneselect, 0xfd000109u, 3, 1) \
- M(i16x8_relaxed_laneselect, 0xfd00010au, 3, 1) \
- M(i32x4_relaxed_laneselect, 0xfd00010bu, 3, 1) \
- M(i64x2_relaxed_laneselect, 0xfd00010cu, 3, 1) \
- M(f32x4_relaxed_min, 0xfd00010du, 2, 1) \
- M(f32x4_relaxed_max, 0xfd00010eu, 2, 1) \
- M(f64x2_relaxed_min, 0xfd00010fu, 2, 1) \
- M(f64x2_relaxed_max, 0xfd000110u, 2, 1) \
- M(i16x8_relaxed_q15mulr_s, 0xfd000111u, 2, 1) \
- M(i16x8_relaxed_dot_i8x16_i7x16_s, 0xfd000112u, 2, 1) \
- M(i32x4_relaxed_dot_i8x16_i7x16_add_s, 0xfd000113u, 3, 1) \
- M(struct_new, 0xfb000000u, -1, 1) \
- M(struct_new_default, 0xfb000001u, 0, 1) \
- M(struct_get, 0xfb000002u, 1, 1) \
- M(struct_get_s, 0xfb000003u, 1, 1) \
- M(struct_get_u, 0xfb000004u, 1, 1) \
- M(struct_set, 0xfb000005u, 2, 0) \
- M(array_new, 0xfb000006u, 2, 1) \
- M(array_new_default, 0xfb000007u, 1, 1) \
- M(array_new_fixed, 0xfb000008u, -1, 1) \
- M(array_new_data, 0xfb000009u, 2, 1) \
- M(array_new_elem, 0xfb00000au, 2, 1) \
- M(array_get, 0xfb00000bu, 2, 1) \
- M(array_get_s, 0xfb00000cu, 2, 1) \
- M(array_get_u, 0xfb00000du, 2, 1) \
- M(array_set, 0xfb00000eu, 3, 0) \
- M(array_len, 0xfb00000fu, 1, 1) \
- M(array_fill, 0xfb000010u, -1, 0) \
- M(array_copy, 0xfb000011u, -1, 0) \
- M(array_init_data, 0xfb000012u, -1, 0) \
- M(array_init_elem, 0xfb000013u, -1, 0) \
- M(ref_test, 0xfb000014u, 1, 1) \
- M(ref_test_null, 0xfb000015u, 1, 1) \
- M(ref_cast, 0xfb000016u, 1, 1) \
- M(ref_cast_null, 0xfb000017u, 1, 1) \
- M(br_on_cast, 0xfb000018u, 1, -1) \
- M(br_on_cast_fail, 0xfb000019u, 1, -1) \
- M(any_convert_extern, 0xfb00001au, 1, 1) \
- M(extern_convert_any, 0xfb00001bu, 1, 1) \
- M(ref_i31, 0xfb00001cu, 1, 1) \
- M(i31_get_s, 0xfb00001du, 1, 1) \
- M(i31_get_u, 0xfb00001eu, 1, 1) \
- /* Synthetic fused insns */ \
- ENUMERATE_SYNTHETIC_INSTRUCTION_OPCODES(M)
-
-#define ENUMERATE_SYNTHETIC_INSTRUCTION_OPCODES(M) \
- M(synthetic_i32_add2local, 0xfe000000u, 0, 1) \
- M(synthetic_i32_addconstlocal, 0xfe000001u, 0, 1) \
- M(synthetic_i32_andconstlocal, 0xfe000002u, 0, 1) \
- M(synthetic_i32_storelocal, 0xfe000003u, 1, 0) \
- M(synthetic_local_seti32_const, 0xfe000005u, 0, 0) \
- M(synthetic_call_00, 0xfe000006u, 0, 0) \
- M(synthetic_call_01, 0xfe000007u, 0, 1) \
- M(synthetic_call_10, 0xfe000008u, 1, 0) \
- M(synthetic_call_11, 0xfe000009u, 1, 1) \
- M(synthetic_call_20, 0xfe00000au, 2, 0) \
- M(synthetic_call_21, 0xfe00000bu, 2, 1) \
- M(synthetic_call_30, 0xfe00000cu, 3, 0) \
- M(synthetic_call_31, 0xfe00000du, 3, 1) \
- M(synthetic_end_expression, 0xfe00000eu, 0, 0) \
- M(synthetic_argument_get, 0xfe00000fu, 0, 1) \
- M(synthetic_argument_set, 0xfe000010u, 1, 0) \
- M(synthetic_argument_tee, 0xfe000011u, 1, 1) \
- M(synthetic_call_with_record_0, 0xfe000012u, 0, 0) \
- M(synthetic_call_with_record_1, 0xfe000013u, 0, 1) \
- M(synthetic_local_get_0, 0xfe000014u, 0, 1) \
- M(synthetic_local_get_1, 0xfe000015u, 0, 1) \
- M(synthetic_local_get_2, 0xfe000016u, 0, 1) \
- M(synthetic_local_get_3, 0xfe000017u, 0, 1) \
- M(synthetic_local_get_4, 0xfe000018u, 0, 1) \
- M(synthetic_local_get_5, 0xfe000019u, 0, 1) \
- M(synthetic_local_get_6, 0xfe00001au, 0, 1) \
- M(synthetic_local_get_7, 0xfe00001bu, 0, 1) \
- M(synthetic_br_nostack, 0xfe00001cu, 0, -1) \
- M(synthetic_br_if_nostack, 0xfe00001du, 1, -1) \
- M(synthetic_local_set_0, 0xfe00001eu, 1, 0) \
- M(synthetic_local_set_1, 0xfe00001fu, 1, 0) \
- M(synthetic_local_set_2, 0xfe000020u, 1, 0) \
- M(synthetic_local_set_3, 0xfe000021u, 1, 0) \
- M(synthetic_local_set_4, 0xfe000022u, 1, 0) \
- M(synthetic_local_set_5, 0xfe000023u, 1, 0) \
- M(synthetic_local_set_6, 0xfe000024u, 1, 0) \
- M(synthetic_local_set_7, 0xfe000025u, 1, 0) \
- M(synthetic_local_copy, 0xfe000026u, 0, 0) \
- M(synthetic_i32_sub2local, 0xfe000027u, 0, 1) \
- M(synthetic_i32_mul2local, 0xfe000028u, 0, 1) \
- M(synthetic_i32_and2local, 0xfe000029u, 0, 1) \
- M(synthetic_i32_or2local, 0xfe00002au, 0, 1) \
- M(synthetic_i32_xor2local, 0xfe00002bu, 0, 1) \
- M(synthetic_i32_shl2local, 0xfe00002cu, 0, 1) \
- M(synthetic_i32_shru2local, 0xfe00002du, 0, 1) \
- M(synthetic_i32_shrs2local, 0xfe00002eu, 0, 1) \
- M(synthetic_i64_add2local, 0xfe00002fu, 0, 1) \
- M(synthetic_i64_addconstlocal, 0xfe000030u, 0, 1) \
- M(synthetic_i64_andconstlocal, 0xfe000031u, 0, 1) \
- M(synthetic_i64_storelocal, 0xfe000032u, 1, 0) \
- M(synthetic_i64_sub2local, 0xfe000033u, 0, 1) \
- M(synthetic_i64_mul2local, 0xfe000034u, 0, 1) \
- M(synthetic_i64_and2local, 0xfe000035u, 0, 1) \
- M(synthetic_i64_or2local, 0xfe000036u, 0, 1) \
- M(synthetic_i64_xor2local, 0xfe000037u, 0, 1) \
- M(synthetic_i64_shl2local, 0xfe000038u, 0, 1) \
- M(synthetic_i64_shru2local, 0xfe000039u, 0, 1) \
- M(synthetic_i64_shrs2local, 0xfe00003au, 0, 1) \
- M(synthetic_local_seti64_const, 0xfe00003bu, 0, 0) \
- /* Continuation data for br_table with >8 labels. \
- * Only consumed by the Cranelift compiler; */ \
- M(synthetic_br_table_cont, 0xfe00003cu, 0, 0) \
- M(synthetic_tier_up, 0xfe00003du, 0, 0) \
- /* threads; we steal 0xfe for our own opcodes, \
- * so the atomic ops are rewritten as parameteric \
- * synthetic instructions to avoid collisions. */ \
- M(atomic_load, 0xfe00003eu, 1, 1) \
- M(atomic_store, 0xfe00003fu, 2, 0) \
- M(atomic_rmw, 0xfe000040u, 2, 1) \
- M(atomic_rmw_cmpxchg, 0xfe000041u, 3, 1) \
- M(memory_atomic_notify, 0xfe000042u, 2, 1) \
- M(memory_atomic_wait32, 0xfe000043u, 3, 1) \
- M(memory_atomic_wait64, 0xfe000044u, 3, 1) \
- M(atomic_fence, 0xfe000045u, 0, 0)
-
-#define ENUMERATE_WASM_OPCODES(M) \
- ENUMERATE_SINGLE_BYTE_WASM_OPCODES(M) \
- ENUMERATE_MULTI_BYTE_WASM_OPCODES(M)
-
-#define M(name, value, ...) static constexpr OpCode name = value;
-ENUMERATE_WASM_OPCODES(M)
-#undef M
-
-static constexpr inline OpCode SyntheticInstructionBase = 0xfe000000u;
-static constexpr inline size_t SyntheticInstructionCount = 70;
-
-}
-
-}
diff --git a/Libraries/LibWasm/Parser/Parser.cpp b/Libraries/LibWasm/Parser/Parser.cpp
deleted file mode 100644
index b9e4bb7a762..00000000000
--- a/Libraries/LibWasm/Parser/Parser.cpp
+++ /dev/null
@@ -1,1977 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Array.h>
-#include <AK/ConstrainedStream.h>
-#include <AK/Debug.h>
-#include <AK/Endian.h>
-#include <AK/Enumerate.h>
-#include <AK/LEB128.h>
-#include <AK/MemoryStream.h>
-#include <AK/ScopeLogger.h>
-#include <AK/UFixedBigInt.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-#define TRY_READ(stream, type, error) \
- ({ \
- /* Ignore -Wshadow to allow nesting the macro. */ \
- AK_IGNORE_DIAGNOSTIC("-Wshadow", \
- auto&& _temporary_result = stream.read_value<type>()); \
- static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
- "Do not return a reference from a fallible expression"); \
- if (_temporary_result.is_error()) [[unlikely]] \
- return with_eof_check(stream, error); \
- _temporary_result.release_value(); \
- })
-
-ParseError with_eof_check(Stream const& stream, ParseError error_if_not_eof)
-{
- if (stream.is_eof())
- return ParseError::UnexpectedEof;
- return error_if_not_eof;
-}
-
-template<typename T>
-static auto parse_vector(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger;
- if constexpr (requires { T::parse(stream); }) {
- using ResultT = typename decltype(T::parse(stream))::ResultType;
- auto count_or_error = stream.read_value<LEB128<u32>>();
- if (count_or_error.is_error())
- return ParseResult<Vector<ResultT>> { with_eof_check(stream, ParseError::ExpectedSize) };
- size_t count = count_or_error.release_value();
-
- Vector<ResultT> entries;
- entries.ensure_capacity(count);
- for (size_t i = 0; i < count; ++i) {
- auto result = T::parse(stream);
- if (result.is_error())
- return ParseResult<Vector<ResultT>> { result.error() };
- entries.append(result.release_value());
- }
- return ParseResult<Vector<ResultT>> { move(entries) };
- } else {
- auto count_or_error = stream.read_value<LEB128<u32>>();
- if (count_or_error.is_error())
- return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
- size_t count = count_or_error.release_value();
-
- Vector<T> entries;
- entries.ensure_capacity(count);
- for (size_t i = 0; i < count; ++i) {
- if constexpr (IsSame<T, u32>) {
- auto value_or_error = stream.read_value<LEB128<u32>>();
- if (value_or_error.is_error())
- return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
- size_t value = value_or_error.release_value();
- entries.append(value);
- } else if constexpr (IsSame<T, ssize_t>) {
- auto value_or_error = stream.read_value<LEB128<ssize_t>>();
- if (value_or_error.is_error())
- return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
- ssize_t value = value_or_error.release_value();
- entries.append(value);
- } else if constexpr (IsSame<T, u8>) {
- if (count > Constants::max_allowed_vector_size)
- return ParseResult<Vector<T>> { ParseError::HugeAllocationRequested };
- entries.resize(count);
- if (stream.read_until_filled({ entries.data(), entries.size() }).is_error())
- return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::InvalidInput) };
- break; // Note: We read this all in one go!
- }
- }
- return ParseResult<Vector<T>> { move(entries) };
- }
-}
-
-static ParseResult<ByteString> parse_name(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger;
- auto data = TRY(parse_vector<u8>(stream));
- auto string = ByteString::copy(data);
- if (!Utf8View(string).validate(AllowLonelySurrogates::No))
- return ParseError::InvalidUtf8;
- return string;
-}
-
-// https://webassembly.github.io/spec/core/binary/values.html#integers
-template<size_t N>
-static ParseResult<i64> parse_signed_integer_of_size(Stream& stream)
-{
- static_assert(N <= 64);
- constexpr size_t max_bytes = (N + 6) / 7;
- i64 result = 0;
- size_t shift = 0;
- for (size_t i = 0; i < max_bytes; ++i) {
- auto n = TRY_READ(stream, u8, ParseError::ExpectedSignedImmediate);
- if (0 == (n & 0x80)) {
- auto const remaining_bits = min(N - 7 * i, 7uz);
- u8 const sign_bit = 1u << (remaining_bits - 1);
- u8 const unused_mask = static_cast<u8>(0x7f & ~(static_cast<u8>(sign_bit << 1) - 1));
- if ((n & sign_bit) ? ((n & unused_mask) != unused_mask) : ((n & unused_mask) != 0))
- return with_eof_check(stream, ParseError::InvalidImmediate);
- result |= static_cast<i64>(n & 0x7f) << shift;
- shift += 7;
- if (shift < 64 && (n & 0x40))
- result |= ~static_cast<i64>(0) << shift;
- return result;
- }
- result |= static_cast<i64>(n & 0x7f) << shift;
- shift += 7;
- }
- return with_eof_check(stream, ParseError::InvalidImmediate);
-}
-
-// https://webassembly.github.io/spec/core/binary/types.html#heap-types
-static Optional<ValueType::Kind> abstract_heap_type_from_tag(u8 tag)
-{
- switch (tag) {
- case Constants::exn_reference_tag:
- return ValueType::ExceptionReference;
- case Constants::array_reference_tag:
- return ValueType::ArrayReference;
- case Constants::struct_reference_tag:
- return ValueType::StructReference;
- case Constants::i31_reference_tag:
- return ValueType::I31Reference;
- case Constants::eq_reference_tag:
- return ValueType::EqReference;
- case Constants::any_reference_tag:
- return ValueType::AnyReference;
- case Constants::extern_reference_tag:
- return ValueType::ExternReference;
- case Constants::function_reference_tag:
- return ValueType::FunctionReference;
- case Constants::none_reference_tag:
- return ValueType::NoneReference;
- case Constants::noextern_reference_tag:
- return ValueType::NoExternReference;
- case Constants::nofunc_reference_tag:
- return ValueType::NoFunctionReference;
- case Constants::noexn_reference_tag:
- return ValueType::NoExceptionReference;
- default:
- return {};
- }
-}
-
-// https://webassembly.github.io/spec/core/binary/types.html#heap-types
-// NOTE: Nullable by default, caller must explicitly set nullability if needed.
-static ParseResult<ValueType> parse_heap_type(Stream& stream)
-{
- auto tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- if (auto kind = abstract_heap_type_from_tag(tag); kind.has_value())
- return ValueType(*kind);
-
- ReconsumableStream new_stream { stream };
- new_stream.unread({ &tag, 1 });
- auto type_index = TRY(parse_signed_integer_of_size<33>(new_stream));
- if (type_index < 0)
- return with_eof_check(stream, ParseError::InvalidIndex);
- if (type_index > NumericLimits<u32>::max())
- return with_eof_check(stream, ParseError::InvalidIndex);
- return ValueType(ValueType::TypeUseReference, TypeIndex(static_cast<u32>(type_index)));
-}
-
-// https://webassembly.github.io/spec/core/binary/types.html#reference-types
-static ParseResult<ValueType> parse_reference_type(Stream& stream, u8 tag)
-{
- switch (tag) {
- case Constants::nullable_reference_tag_tag:
- case Constants::non_nullable_reference_tag_tag: {
- bool nullable = tag == Constants::nullable_reference_tag_tag;
- auto type = TRY(parse_heap_type(stream));
- type.set_nullable(nullable);
- return type;
- }
- default:
- if (auto kind = abstract_heap_type_from_tag(tag); kind.has_value())
- return ValueType(*kind);
- return with_eof_check(stream, ParseError::InvalidType);
- }
-}
-
-// https://webassembly.github.io/spec/core/binary/types.html#value-types
-ParseResult<ValueType> ValueType::parse(Stream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("ValueType"sv);
- auto tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- switch (tag) {
- case Constants::i32_tag:
- return ValueType(I32);
- case Constants::i64_tag:
- return ValueType(I64);
- case Constants::f32_tag:
- return ValueType(F32);
- case Constants::f64_tag:
- return ValueType(F64);
- case Constants::v128_tag:
- return ValueType(V128);
- default:
- return parse_reference_type(stream, tag);
- }
-}
-
-// https://webassembly.github.io/spec/core/binary/types.html#composite-types
-static ParseResult<ValueType> parse_storage_type(Stream& stream)
-{
- auto tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- switch (tag) {
- case Constants::i16_tag:
- return ValueType(ValueType::I16);
- case Constants::i8_tag:
- return ValueType(ValueType::I8);
- default: {
- ReconsumableStream new_stream { stream };
- new_stream.unread({ &tag, 1 });
- return ValueType::parse(new_stream);
- }
- }
-}
-
-ParseResult<ResultType> ResultType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("ResultType"sv);
- auto types = TRY(parse_vector<ValueType>(stream));
- return ResultType { types };
-}
-
-ParseResult<FunctionType> FunctionType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionType"sv);
-
- auto parameters_result = TRY(parse_vector<ValueType>(stream));
- auto results_result = TRY(parse_vector<ValueType>(stream));
-
- return FunctionType { parameters_result, results_result };
-}
-
-// https://webassembly.github.io/spec/core/binary/types.html#composite-types
-ParseResult<FieldType> FieldType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("FieldType"sv);
-
- auto type_ = TRY(parse_storage_type(stream));
-
- auto mutable_ = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- if (mutable_ > 1)
- return with_eof_check(stream, ParseError::InvalidTag);
-
- return FieldType { mutable_ == 0x01, type_ };
-}
-
-ParseResult<StructType> StructType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("StructType"sv);
-
- auto fields = TRY(parse_vector<FieldType>(stream));
-
- return StructType { fields };
-}
-
-ParseResult<ArrayType> ArrayType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("ArrayType"sv);
-
- auto type = TRY(FieldType::parse(stream));
-
- return ArrayType { type };
-}
-
-ParseResult<Limits> Limits::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Limits"sv);
- auto flag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- // Proposal 'memory64': flags 0/1 refer to 32-bit limits, flags 4/5 refer to 64-bit limits.
- if (flag & ~0b00000101)
- return with_eof_check(stream, ParseError::InvalidTag);
-
- auto address_type = (flag & 0b00000100) ? AddressType::I64 : AddressType::I32;
-
- auto min_or_error = stream.read_value<LEB128<u64>>();
- if (min_or_error.is_error())
- return with_eof_check(stream, ParseError::ExpectedSize);
- u64 min = min_or_error.release_value();
-
- Optional<u64> max;
- if (flag & 1) {
- auto value_or_error = stream.read_value<LEB128<u64>>();
- if (value_or_error.is_error())
- return with_eof_check(stream, ParseError::ExpectedSize);
- max = value_or_error.release_value();
- }
-
- return Limits { address_type, min, move(max) };
-}
-
-ParseResult<MemoryType> MemoryType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemoryType"sv);
- auto limits_result = TRY(Limits::parse(stream));
- return MemoryType { limits_result };
-}
-
-ParseResult<TableType> TableType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableType"sv);
- auto type_result = TRY(ValueType::parse(stream));
- if (!type_result.is_reference())
- return ParseError::InvalidType;
- auto limits_result = TRY(Limits::parse(stream));
- return TableType { type_result, limits_result };
-}
-
-ParseResult<GlobalType> GlobalType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalType"sv);
- auto type_result = TRY(ValueType::parse(stream));
- auto mutable_ = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- if (mutable_ > 1)
- return with_eof_check(stream, ParseError::InvalidTag);
-
- return GlobalType { type_result, mutable_ == 0x01 };
-}
-
-ParseResult<TagType> TagType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("TagType"sv);
- auto flags = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- if (flags != 0)
- return ParseError::InvalidTag;
- auto index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- return TagType { index, static_cast<TagType::Flags>(flags) };
-}
-
-// https://webassembly.github.io/spec/core/binary/instructions.html#control-instructions
-ParseResult<BlockType> BlockType::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("BlockType"sv);
- auto kind = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- if (kind == Constants::empty_block_tag)
- return BlockType {};
-
- switch (kind) {
- case Constants::i32_tag:
- case Constants::i64_tag:
- case Constants::f32_tag:
- case Constants::f64_tag:
- case Constants::v128_tag:
- case Constants::nullable_reference_tag_tag:
- case Constants::non_nullable_reference_tag_tag: {
- ReconsumableStream value_stream { stream };
- value_stream.unread({ &kind, 1 });
- return BlockType { TRY(ValueType::parse(value_stream)) };
- }
- default:
- break;
- }
-
- if (auto abstract_kind = abstract_heap_type_from_tag(kind); abstract_kind.has_value())
- return BlockType { ValueType(*abstract_kind) };
-
- ReconsumableStream index_stream { stream };
- index_stream.unread({ &kind, 1 });
- auto type_index = TRY(parse_signed_integer_of_size<33>(index_stream));
- if (type_index < 0 || type_index > NumericLimits<u32>::max())
- return with_eof_check(stream, ParseError::InvalidIndex);
- return BlockType { TypeIndex(static_cast<u32>(type_index)) };
-}
-
-ParseResult<Catch> Catch::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Catch"sv);
- auto kind = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- switch (kind) {
- case 0: {
- // catch x l
- auto tag_index = TRY(GenericIndexParser<TagIndex>::parse(stream));
- auto label_index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- return Catch { false, tag_index, label_index };
- }
- case 1: {
- // catch_ref x l
- auto tag_index = TRY(GenericIndexParser<TagIndex>::parse(stream));
- auto label_index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- return Catch { true, tag_index, label_index };
- }
- case 2: {
- // catch_all l
- auto label_index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- return Catch { false, label_index };
- }
- case 3: {
- // catch_all_ref l
- auto label_index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- return Catch { true, label_index };
- }
- default:
- return ParseError::InvalidTag;
- }
-}
-
-ParseResult<Instruction> Instruction::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Instruction"sv);
- u8 byte;
- if (auto result = stream.read_some({ &byte, 1 }); result.is_error() || result.value().size() != 1)
- return ParseError::ExpectedKindTag;
-
- OpCode opcode { byte };
-
- switch (opcode.value()) {
- case Instructions::block.value():
- case Instructions::loop.value():
- case Instructions::if_.value(): {
- auto block_type = TRY(BlockType::parse(stream));
- return Instruction {
- opcode, StructuredInstructionArgs { block_type, {}, {} }
- };
- }
- case Instructions::try_table.value(): {
- // try_table block_type (catch*) (instruction*) end
- auto block_type = TRY(BlockType::parse(stream));
- auto catch_types = TRY(parse_vector<Catch>(stream));
- return Instruction {
- opcode, TryTableArgs { block_type, {}, catch_types.span() }
- };
- }
- case Instructions::throw_.value(): {
- auto tag_index = TRY(GenericIndexParser<TagIndex>::parse(stream));
- return Instruction { opcode, tag_index };
- }
- case Instructions::br.value():
- case Instructions::br_if.value(): {
- // branches with a single label immediate
- auto index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- return Instruction { opcode, BranchArgs { index } };
- }
- // https://webassembly.github.io/spec/core/binary/instructions.html#control-instructions
- // 0xD5 l:labelidx => br_on_null l
- // 0xD6 l:labelidx => br_on_non_null l
- case Instructions::br_on_null.value():
- case Instructions::br_on_non_null.value(): {
- auto index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- return Instruction { opcode, BranchArgs { index } };
- }
- case Instructions::br_table.value(): {
- // br_table label* label
- auto labels = TRY(parse_vector<GenericIndexParser<LabelIndex>>(stream));
- auto default_label = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- return Instruction { opcode, TableBranchArgs { labels, default_label } };
- }
- case Instructions::call.value(): {
- // call function
- auto function_index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
- return Instruction { opcode, function_index };
- }
- case Instructions::call_indirect.value(): {
- // call_indirect type table
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- auto table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
- return Instruction { opcode, IndirectCallArgs { type_index, table_index } };
- }
- case Instructions::return_call.value(): {
- // return_call function
- auto function_index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
- return Instruction { opcode, function_index };
- }
- case Instructions::return_call_indirect.value(): {
- // return_call_indirect type table
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- auto table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
- return Instruction { opcode, IndirectCallArgs { type_index, table_index } };
- }
- case Instructions::call_ref.value():
- case Instructions::return_call_ref.value(): {
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- return Instruction { opcode, type_index };
- }
- case Instructions::i32_load.value():
- case Instructions::i64_load.value():
- case Instructions::f32_load.value():
- case Instructions::f64_load.value():
- case Instructions::i32_load8_s.value():
- case Instructions::i32_load8_u.value():
- case Instructions::i32_load16_s.value():
- case Instructions::i32_load16_u.value():
- case Instructions::i64_load8_s.value():
- case Instructions::i64_load8_u.value():
- case Instructions::i64_load16_s.value():
- case Instructions::i64_load16_u.value():
- case Instructions::i64_load32_s.value():
- case Instructions::i64_load32_u.value():
- case Instructions::i32_store.value():
- case Instructions::i64_store.value():
- case Instructions::f32_store.value():
- case Instructions::f64_store.value():
- case Instructions::i32_store8.value():
- case Instructions::i32_store16.value():
- case Instructions::i64_store8.value():
- case Instructions::i64_store16.value():
- case Instructions::i64_store32.value(): {
- // op (align [multi-memory: memindex] offset)
- u32 align = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
-
- // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
- auto memory_index = 0;
- if ((align & 0x40) != 0) {
- align &= ~0x40;
- memory_index = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
- }
-
- // Proposal 'memory64': memarg offsets are u64 instead of u32.
- auto offset = TRY_READ(stream, LEB128<u64>, ParseError::InvalidInput);
-
- return Instruction { opcode, MemoryArgument { align, offset, MemoryIndex(memory_index) } };
- }
- case Instructions::local_get.value():
- case Instructions::local_set.value():
- case Instructions::local_tee.value(): {
- auto index = TRY(GenericIndexParser<LocalIndex>::parse(stream));
- return Instruction { opcode, index };
- }
- case Instructions::global_get.value():
- case Instructions::global_set.value(): {
- auto index = TRY(GenericIndexParser<GlobalIndex>::parse(stream));
- return Instruction { opcode, index };
- }
- case Instructions::memory_size.value():
- case Instructions::memory_grow.value(): {
- // op [multi-memory: memindex]|0x00
- u32 memory_index = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedKindTag);
-
- return Instruction { opcode, MemoryIndexArgument { MemoryIndex(memory_index) } };
- }
- case Instructions::i32_const.value(): {
- auto value = TRY_READ(stream, LEB128<i32>, ParseError::ExpectedSignedImmediate);
-
- return Instruction { opcode, value };
- }
- case Instructions::i64_const.value(): {
- // op literal
- auto value = TRY_READ(stream, LEB128<i64>, ParseError::ExpectedSignedImmediate);
-
- return Instruction { opcode, value };
- }
- case Instructions::f32_const.value(): {
- // op literal
- auto value = TRY_READ(stream, LittleEndian<u32>, ParseError::ExpectedFloatingImmediate);
-
- auto floating = bit_cast<float>(static_cast<u32>(value));
- return Instruction { opcode, floating };
- }
- case Instructions::f64_const.value(): {
- // op literal
- auto value = TRY_READ(stream, LittleEndian<u64>, ParseError::ExpectedFloatingImmediate);
-
- auto floating = bit_cast<double>(static_cast<u64>(value));
- return Instruction { opcode, floating };
- }
- case Instructions::table_get.value():
- case Instructions::table_set.value(): {
- auto index = TRY(GenericIndexParser<TableIndex>::parse(stream));
- return Instruction { opcode, index };
- }
- case Instructions::select_typed.value(): {
- auto types = TRY(parse_vector<ValueType>(stream));
- return Instruction { opcode, types };
- }
- case Instructions::ref_null.value(): {
- // https://webassembly.github.io/spec/core/binary/instructions.html#reference-instructions
- auto type = TRY(parse_heap_type(stream));
- return Instruction { opcode, type };
- }
- case Instructions::ref_func.value(): {
- auto index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
- return Instruction { opcode, index };
- }
- case Instructions::throw_ref.value():
- case Instructions::structured_end.value():
- case Instructions::structured_else.value():
- case Instructions::ref_is_null.value():
- // https://webassembly.github.io/spec/core/binary/instructions.html#reference-instructions
- // 0xD3 => ref.eq
- // 0xD4 => ref.as_non_null
- case Instructions::ref_eq.value():
- case Instructions::ref_as_non_null.value():
- case Instructions::unreachable.value():
- case Instructions::nop.value():
- case Instructions::return_.value():
- case Instructions::drop.value():
- case Instructions::select.value():
- case Instructions::i32_eqz.value():
- case Instructions::i32_eq.value():
- case Instructions::i32_ne.value():
- case Instructions::i32_lts.value():
- case Instructions::i32_ltu.value():
- case Instructions::i32_gts.value():
- case Instructions::i32_gtu.value():
- case Instructions::i32_les.value():
- case Instructions::i32_leu.value():
- case Instructions::i32_ges.value():
- case Instructions::i32_geu.value():
- case Instructions::i64_eqz.value():
- case Instructions::i64_eq.value():
- case Instructions::i64_ne.value():
- case Instructions::i64_lts.value():
- case Instructions::i64_ltu.value():
- case Instructions::i64_gts.value():
- case Instructions::i64_gtu.value():
- case Instructions::i64_les.value():
- case Instructions::i64_leu.value():
- case Instructions::i64_ges.value():
- case Instructions::i64_geu.value():
- case Instructions::f32_eq.value():
- case Instructions::f32_ne.value():
- case Instructions::f32_lt.value():
- case Instructions::f32_gt.value():
- case Instructions::f32_le.value():
- case Instructions::f32_ge.value():
- case Instructions::f64_eq.value():
- case Instructions::f64_ne.value():
- case Instructions::f64_lt.value():
- case Instructions::f64_gt.value():
- case Instructions::f64_le.value():
- case Instructions::f64_ge.value():
- case Instructions::i32_clz.value():
- case Instructions::i32_ctz.value():
- case Instructions::i32_popcnt.value():
- case Instructions::i32_add.value():
- case Instructions::i32_sub.value():
- case Instructions::i32_mul.value():
- case Instructions::i32_divs.value():
- case Instructions::i32_divu.value():
- case Instructions::i32_rems.value():
- case Instructions::i32_remu.value():
- case Instructions::i32_and.value():
- case Instructions::i32_or.value():
- case Instructions::i32_xor.value():
- case Instructions::i32_shl.value():
- case Instructions::i32_shrs.value():
- case Instructions::i32_shru.value():
- case Instructions::i32_rotl.value():
- case Instructions::i32_rotr.value():
- case Instructions::i64_clz.value():
- case Instructions::i64_ctz.value():
- case Instructions::i64_popcnt.value():
- case Instructions::i64_add.value():
- case Instructions::i64_sub.value():
- case Instructions::i64_mul.value():
- case Instructions::i64_divs.value():
- case Instructions::i64_divu.value():
- case Instructions::i64_rems.value():
- case Instructions::i64_remu.value():
- case Instructions::i64_and.value():
- case Instructions::i64_or.value():
- case Instructions::i64_xor.value():
- case Instructions::i64_shl.value():
- case Instructions::i64_shrs.value():
- case Instructions::i64_shru.value():
- case Instructions::i64_rotl.value():
- case Instructions::i64_rotr.value():
- case Instructions::f32_abs.value():
- case Instructions::f32_neg.value():
- case Instructions::f32_ceil.value():
- case Instructions::f32_floor.value():
- case Instructions::f32_trunc.value():
- case Instructions::f32_nearest.value():
- case Instructions::f32_sqrt.value():
- case Instructions::f32_add.value():
- case Instructions::f32_sub.value():
- case Instructions::f32_mul.value():
- case Instructions::f32_div.value():
- case Instructions::f32_min.value():
- case Instructions::f32_max.value():
- case Instructions::f32_copysign.value():
- case Instructions::f64_abs.value():
- case Instructions::f64_neg.value():
- case Instructions::f64_ceil.value():
- case Instructions::f64_floor.value():
- case Instructions::f64_trunc.value():
- case Instructions::f64_nearest.value():
- case Instructions::f64_sqrt.value():
- case Instructions::f64_add.value():
- case Instructions::f64_sub.value():
- case Instructions::f64_mul.value():
- case Instructions::f64_div.value():
- case Instructions::f64_min.value():
- case Instructions::f64_max.value():
- case Instructions::f64_copysign.value():
- case Instructions::i32_wrap_i64.value():
- case Instructions::i32_trunc_sf32.value():
- case Instructions::i32_trunc_uf32.value():
- case Instructions::i32_trunc_sf64.value():
- case Instructions::i32_trunc_uf64.value():
- case Instructions::i64_extend_si32.value():
- case Instructions::i64_extend_ui32.value():
- case Instructions::i64_trunc_sf32.value():
- case Instructions::i64_trunc_uf32.value():
- case Instructions::i64_trunc_sf64.value():
- case Instructions::i64_trunc_uf64.value():
- case Instructions::f32_convert_si32.value():
- case Instructions::f32_convert_ui32.value():
- case Instructions::f32_convert_si64.value():
- case Instructions::f32_convert_ui64.value():
- case Instructions::f32_demote_f64.value():
- case Instructions::f64_convert_si32.value():
- case Instructions::f64_convert_ui32.value():
- case Instructions::f64_convert_si64.value():
- case Instructions::f64_convert_ui64.value():
- case Instructions::f64_promote_f32.value():
- case Instructions::i32_reinterpret_f32.value():
- case Instructions::i64_reinterpret_f64.value():
- case Instructions::f32_reinterpret_i32.value():
- case Instructions::f64_reinterpret_i64.value():
- case Instructions::i32_extend8_s.value():
- case Instructions::i32_extend16_s.value():
- case Instructions::i64_extend8_s.value():
- case Instructions::i64_extend16_s.value():
- case Instructions::i64_extend32_s.value():
- return Instruction { opcode };
- case 0xfe: {
- // Proposal "threads": atomic memory instructions.
- auto selector = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
-
- auto parse_memory_argument = [&]() -> ParseResult<MemoryArgument> {
- // (align [multi-memory: memindex] offset)
- u32 align = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
-
- // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
- auto memory_index = 0;
- if ((align & 0x40) != 0) {
- align &= ~0x40;
- memory_index = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
- }
-
- // Proposal 'memory64': memarg offsets are u64 instead of u32.
- auto offset = TRY_READ(stream, LEB128<u64>, ParseError::InvalidInput);
-
- return MemoryArgument { align, offset, MemoryIndex(memory_index) };
- };
-
- switch (selector) {
- case 0x00:
- return Instruction { Instructions::memory_atomic_notify, TRY(parse_memory_argument()) };
- case 0x01:
- return Instruction { Instructions::memory_atomic_wait32, TRY(parse_memory_argument()) };
- case 0x02:
- return Instruction { Instructions::memory_atomic_wait64, TRY(parse_memory_argument()) };
- case 0x03: {
- // atomic.fence is followed by a reserved zero byte.
- auto reserved = TRY_READ(stream, u8, ParseError::InvalidInput);
- if (reserved != 0)
- return ParseError::InvalidInput;
- return Instruction { Instructions::atomic_fence };
- }
- default:
- break;
- }
-
- // The remaining instructions come in groups of seven, one per access width.
- // in the order i32, i64, i32 8u, i32 16u, i64 8u, i64 16u, i64 32u.
- // The groups are loads, stores and then read-modify-write x { add, sub, and, or, xor, xchg, cmpxchg }.
- using Width = Instruction::AtomicMemoryArgument::Width;
- using Op = Instruction::AtomicMemoryArgument::Op;
- static constexpr Array widths { Width::I32, Width::I64, Width::I8As32, Width::I16As32, Width::I8As64, Width::I16As64, Width::I32As64 };
- static constexpr u32 first_selector = 0x10;
- static constexpr u32 last_selector = 0x4e;
- if (selector < first_selector || selector > last_selector)
- return ParseError::UnknownInstruction;
-
- auto group = (selector - first_selector) / widths.size();
- auto width = widths[(selector - first_selector) % widths.size()];
- auto memory = TRY(parse_memory_argument());
- switch (group) {
- case 0:
- return Instruction { Instructions::atomic_load, Instruction::AtomicMemoryArgument { memory, width } };
- case 1:
- return Instruction { Instructions::atomic_store, Instruction::AtomicMemoryArgument { memory, width } };
- case 2:
- return Instruction { Instructions::atomic_rmw, Instruction::AtomicMemoryArgument { memory, width, Op::Add } };
- case 3:
- return Instruction { Instructions::atomic_rmw, Instruction::AtomicMemoryArgument { memory, width, Op::Sub } };
- case 4:
- return Instruction { Instructions::atomic_rmw, Instruction::AtomicMemoryArgument { memory, width, Op::And } };
- case 5:
- return Instruction { Instructions::atomic_rmw, Instruction::AtomicMemoryArgument { memory, width, Op::Or } };
- case 6:
- return Instruction { Instructions::atomic_rmw, Instruction::AtomicMemoryArgument { memory, width, Op::Xor } };
- case 7:
- return Instruction { Instructions::atomic_rmw, Instruction::AtomicMemoryArgument { memory, width, Op::Xchg } };
- case 8:
- return Instruction { Instructions::atomic_rmw_cmpxchg, Instruction::AtomicMemoryArgument { memory, width } };
- }
- VERIFY_NOT_REACHED();
- }
- case 0xfb:
- case 0xfc:
- case 0xfd: {
- // These are multibyte instructions.
- auto selector = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
- if (selector > 0xffffff)
- return ParseError::UnknownInstruction;
-
- OpCode full_opcode = static_cast<u32>(opcode.value()) << 24 | selector;
-
- switch (full_opcode.value()) {
- case Instructions::i32_trunc_sat_f32_s.value():
- case Instructions::i32_trunc_sat_f32_u.value():
- case Instructions::i32_trunc_sat_f64_s.value():
- case Instructions::i32_trunc_sat_f64_u.value():
- case Instructions::i64_trunc_sat_f32_s.value():
- case Instructions::i64_trunc_sat_f32_u.value():
- case Instructions::i64_trunc_sat_f64_s.value():
- case Instructions::i64_trunc_sat_f64_u.value():
- return Instruction { full_opcode };
- case Instructions::memory_init.value(): {
- auto index = TRY(GenericIndexParser<DataIndex>::parse(stream));
-
- // Proposal "multi-memory", literal 0x00 is replaced with a memory index (LEB-128).
- u32 memory_index = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
-
- return Instruction { full_opcode, MemoryInitArgs { index, MemoryIndex(memory_index) } };
- }
- case Instructions::data_drop.value(): {
- auto index = TRY(GenericIndexParser<DataIndex>::parse(stream));
- return Instruction { full_opcode, index };
- }
- case Instructions::memory_copy.value(): {
- // Proposal "multi-memory", literal 0x00 is replaced with two memory indices (LEB-128), destination and source, respectively.
- MemoryIndex indices[] = { 0, 0 };
-
- for (size_t i = 0; i < 2; ++i) {
- u32 memory_index = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
- indices[i] = memory_index;
- }
- return Instruction { full_opcode, MemoryCopyArgs { indices[1], indices[0] } };
- }
- case Instructions::memory_fill.value(): {
- // Proposal "multi-memory", literal 0x00 is replaced with a memory index (LEB-128).
- u32 memory_index = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
- return Instruction { full_opcode, MemoryIndexArgument { MemoryIndex { memory_index } } };
- }
- case Instructions::table_init.value(): {
- auto element_index = TRY(GenericIndexParser<ElementIndex>::parse(stream));
- auto table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
- return Instruction { full_opcode, TableElementArgs { element_index, table_index } };
- }
- case Instructions::elem_drop.value(): {
- auto element_index = TRY(GenericIndexParser<ElementIndex>::parse(stream));
- return Instruction { full_opcode, element_index };
- }
- case Instructions::table_copy.value(): {
- auto lhs = TRY(GenericIndexParser<TableIndex>::parse(stream));
- auto rhs = TRY(GenericIndexParser<TableIndex>::parse(stream));
- return Instruction { full_opcode, TableTableArgs { lhs, rhs } };
- }
- case Instructions::table_grow.value():
- case Instructions::table_size.value():
- case Instructions::table_fill.value(): {
- auto index = TRY(GenericIndexParser<TableIndex>::parse(stream));
- return Instruction { full_opcode, index };
- }
- // https://webassembly.github.io/spec/core/binary/instructions.html#aggregate-instructions
- // instr ::= ...
- // | 0xFB 0:u32 x:typeidx => struct.new x
- // | 0xFB 1:u32 x:typeidx => struct.new_default x
- case Instructions::struct_new.value():
- case Instructions::struct_new_default.value(): {
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- return Instruction { full_opcode, type_index };
- }
- // | 0xFB 2:u32 x:typeidx i:fieldidx => struct.get x i
- // | 0xFB 3:u32 x:typeidx i:fieldidx => struct.get_s x i
- // | 0xFB 4:u32 x:typeidx i:fieldidx => struct.get_u x i
- // | 0xFB 5:u32 x:typeidx i:fieldidx => struct.set x i
- case Instructions::struct_get.value():
- case Instructions::struct_get_s.value():
- case Instructions::struct_get_u.value():
- case Instructions::struct_set.value(): {
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- u32 field_index = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedIndex);
- return Instruction { full_opcode, StructFieldArgs { type_index, field_index } };
- }
- // | 0xFB 6:u32 x:typeidx => array.new x
- // | 0xFB 7:u32 x:typeidx => array.new_default x
- // | 0xFB 11:u32 x:typeidx => array.get x
- // | 0xFB 12:u32 x:typeidx => array.get_s x
- // | 0xFB 13:u32 x:typeidx => array.get_u x
- // | 0xFB 14:u32 x:typeidx => array.set x
- // | 0xFB 16:u32 x:typeidx => array.fill x
- case Instructions::array_new.value():
- case Instructions::array_new_default.value():
- case Instructions::array_get.value():
- case Instructions::array_get_s.value():
- case Instructions::array_get_u.value():
- case Instructions::array_set.value():
- case Instructions::array_fill.value(): {
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- return Instruction { full_opcode, type_index };
- }
- // | 0xFB 8:u32 x:typeidx n:u32 => array.new_fixed x n
- case Instructions::array_new_fixed.value(): {
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- u32 count = TRY_READ(stream, LEB128<u32>, ParseError::InvalidImmediate);
- return Instruction { full_opcode, ArrayNewFixedArgs { type_index, count } };
- }
- // | 0xFB 9:u32 x:typeidx y:dataidx => array.new_data x y
- // | 0xFB 18:u32 x:typeidx y:dataidx => array.init_data x y
- case Instructions::array_new_data.value():
- case Instructions::array_init_data.value(): {
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- auto data_index = TRY(GenericIndexParser<DataIndex>::parse(stream));
- return Instruction { full_opcode, ArrayDataArgs { type_index, data_index } };
- }
- // | 0xFB 10:u32 x:typeidx y:elemidx => array.new_elem x y
- // | 0xFB 19:u32 x:typeidx y:elemidx => array.init_elem x y
- case Instructions::array_new_elem.value():
- case Instructions::array_init_elem.value(): {
- auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- auto element_index = TRY(GenericIndexParser<ElementIndex>::parse(stream));
- return Instruction { full_opcode, ArrayElemArgs { type_index, element_index } };
- }
- // | 0xFB 17:u32 x_1:typeidx x_2:typeidx => array.copy x_1 x_2
- case Instructions::array_copy.value(): {
- auto destination_type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- auto source_type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- return Instruction { full_opcode, ArrayCopyArgs { destination_type_index, source_type_index } };
- }
- // https://webassembly.github.io/spec/core/binary/instructions.html#reference-instructions
- // instr ::= ...
- // | 0xFB 20:u32 ht:heaptype => ref.test (ref ht)
- // | 0xFB 21:u32 ht:heaptype => ref.test (ref null ht)
- // | 0xFB 22:u32 ht:heaptype => ref.cast (ref ht)
- // | 0xFB 23:u32 ht:heaptype => ref.cast (ref null ht)
- case Instructions::ref_test.value():
- case Instructions::ref_test_null.value():
- case Instructions::ref_cast.value():
- case Instructions::ref_cast_null.value(): {
- auto type = TRY(parse_heap_type(stream));
- type.set_nullable(full_opcode == Instructions::ref_test_null || full_opcode == Instructions::ref_cast_null);
- return Instruction { full_opcode, type };
- }
- // https://webassembly.github.io/spec/core/binary/instructions.html#control-instructions
- // instr ::= ...
- // | 0xFB 24:u32 (null_1?, null_2?):castop l:labelidx ht_1:heaptype ht_2:heaptype
- // => br_on_cast l (ref null_1? ht_1) (ref null_2? ht_2)
- // | 0xFB 25:u32 (null_1?, null_2?):castop l:labelidx ht_1:heaptype ht_2:heaptype
- // => br_on_cast_fail l (ref null_1? ht_1) (ref null_2? ht_2)
- // castop ::= 0x00 => (ε, ε)
- // | 0x01 => (null, ε)
- // | 0x02 => (ε, null)
- // | 0x03 => (null, null)
- case Instructions::br_on_cast.value():
- case Instructions::br_on_cast_fail.value(): {
- auto cast_op = TRY_READ(stream, u8, ParseError::InvalidImmediate);
- if (cast_op > 3)
- return ParseError::InvalidImmediate;
- auto label = TRY(GenericIndexParser<LabelIndex>::parse(stream));
- auto source_type = TRY(parse_heap_type(stream));
- source_type.set_nullable((cast_op & 0b01) != 0);
- auto target_type = TRY(parse_heap_type(stream));
- target_type.set_nullable((cast_op & 0b10) != 0);
- return Instruction { full_opcode, BranchOnCastArgs { BranchArgs { label }, source_type, target_type } };
- }
- // https://webassembly.github.io/spec/core/binary/instructions.html#aggregate-instructions
- // instr ::= ...
- // | 0xFB 15:u32 => array.len
- // | 0xFB 26:u32 => any.convert_extern
- // | 0xFB 27:u32 => extern.convert_any
- // | 0xFB 28:u32 => ref.i31
- // | 0xFB 29:u32 => i31.get_s
- // | 0xFB 30:u32 => i31.get_u
- case Instructions::array_len.value():
- case Instructions::any_convert_extern.value():
- case Instructions::extern_convert_any.value():
- case Instructions::ref_i31.value():
- case Instructions::i31_get_s.value():
- case Instructions::i31_get_u.value():
- return Instruction { full_opcode };
- case Instructions::v128_load.value():
- case Instructions::v128_load8x8_s.value():
- case Instructions::v128_load8x8_u.value():
- case Instructions::v128_load16x4_s.value():
- case Instructions::v128_load16x4_u.value():
- case Instructions::v128_load32x2_s.value():
- case Instructions::v128_load32x2_u.value():
- case Instructions::v128_load8_splat.value():
- case Instructions::v128_load16_splat.value():
- case Instructions::v128_load32_splat.value():
- case Instructions::v128_load64_splat.value():
- case Instructions::v128_load32_zero.value():
- case Instructions::v128_load64_zero.value():
- case Instructions::v128_store.value(): {
- // op (align [multi-memory memindex] offset)
- u32 align = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedIndex);
-
- // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
- auto memory_index = 0;
- if ((align & 0x40) != 0) {
- align &= ~0x40;
- memory_index = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
- }
-
- // Proposal 'memory64': memarg offsets are u64 instead of u32.
- auto offset = TRY_READ(stream, LEB128<u64>, ParseError::ExpectedIndex);
-
- return Instruction { full_opcode, MemoryArgument { align, offset, MemoryIndex(memory_index) } };
- }
- case Instructions::v128_load8_lane.value():
- case Instructions::v128_load16_lane.value():
- case Instructions::v128_load32_lane.value():
- case Instructions::v128_load64_lane.value():
- case Instructions::v128_store8_lane.value():
- case Instructions::v128_store16_lane.value():
- case Instructions::v128_store32_lane.value():
- case Instructions::v128_store64_lane.value(): {
- // op (align [multi-memory: memindex] offset) (index)
- u32 align = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedIndex);
-
- // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
- auto memory_index = 0;
- if ((align & 0x40) != 0) {
- align &= ~0x40;
- memory_index = TRY_READ(stream, LEB128<u32>, ParseError::InvalidInput);
- }
-
- // Proposal 'memory64': memarg offsets are u64 instead of u32.
- auto offset = TRY_READ(stream, LEB128<u64>, ParseError::ExpectedIndex);
- auto index = TRY_READ(stream, u8, ParseError::InvalidInput);
-
- return Instruction { full_opcode, MemoryAndLaneArgument { { align, offset, MemoryIndex(memory_index) }, index } };
- }
- case Instructions::v128_const.value(): {
- // op (literal:16)
- auto value = TRY_READ(stream, LittleEndian<u128>, ParseError::InvalidImmediate);
- return Instruction { full_opcode, value };
- }
- case Instructions::i8x16_shuffle.value(): {
- // op 16x(lane)
- u8 lanes[16];
- for (size_t i = 0; i < 16; ++i) {
- auto value = TRY_READ(stream, u8, ParseError::InvalidInput);
- lanes[i] = value;
- }
- return Instruction { full_opcode, ShuffleArgument(lanes) };
- }
- case Instructions::i8x16_extract_lane_s.value():
- case Instructions::i8x16_extract_lane_u.value():
- case Instructions::i8x16_replace_lane.value():
- case Instructions::i16x8_extract_lane_s.value():
- case Instructions::i16x8_extract_lane_u.value():
- case Instructions::i16x8_replace_lane.value():
- case Instructions::i32x4_extract_lane.value():
- case Instructions::i32x4_replace_lane.value():
- case Instructions::i64x2_extract_lane.value():
- case Instructions::i64x2_replace_lane.value():
- case Instructions::f32x4_extract_lane.value():
- case Instructions::f32x4_replace_lane.value():
- case Instructions::f64x2_extract_lane.value():
- case Instructions::f64x2_replace_lane.value(): {
- // op (lane)
- auto lane = TRY_READ(stream, u8, ParseError::InvalidInput);
- return Instruction { full_opcode, LaneIndex { lane } };
- }
- case Instructions::i8x16_swizzle.value():
- case Instructions::i8x16_splat.value():
- case Instructions::i16x8_splat.value():
- case Instructions::i32x4_splat.value():
- case Instructions::i64x2_splat.value():
- case Instructions::f32x4_splat.value():
- case Instructions::f64x2_splat.value():
- case Instructions::i8x16_eq.value():
- case Instructions::i8x16_ne.value():
- case Instructions::i8x16_lt_s.value():
- case Instructions::i8x16_lt_u.value():
- case Instructions::i8x16_gt_s.value():
- case Instructions::i8x16_gt_u.value():
- case Instructions::i8x16_le_s.value():
- case Instructions::i8x16_le_u.value():
- case Instructions::i8x16_ge_s.value():
- case Instructions::i8x16_ge_u.value():
- case Instructions::i16x8_eq.value():
- case Instructions::i16x8_ne.value():
- case Instructions::i16x8_lt_s.value():
- case Instructions::i16x8_lt_u.value():
- case Instructions::i16x8_gt_s.value():
- case Instructions::i16x8_gt_u.value():
- case Instructions::i16x8_le_s.value():
- case Instructions::i16x8_le_u.value():
- case Instructions::i16x8_ge_s.value():
- case Instructions::i16x8_ge_u.value():
- case Instructions::i32x4_eq.value():
- case Instructions::i32x4_ne.value():
- case Instructions::i32x4_lt_s.value():
- case Instructions::i32x4_lt_u.value():
- case Instructions::i32x4_gt_s.value():
- case Instructions::i32x4_gt_u.value():
- case Instructions::i32x4_le_s.value():
- case Instructions::i32x4_le_u.value():
- case Instructions::i32x4_ge_s.value():
- case Instructions::i32x4_ge_u.value():
- case Instructions::f32x4_eq.value():
- case Instructions::f32x4_ne.value():
- case Instructions::f32x4_lt.value():
- case Instructions::f32x4_gt.value():
- case Instructions::f32x4_le.value():
- case Instructions::f32x4_ge.value():
- case Instructions::f64x2_eq.value():
- case Instructions::f64x2_ne.value():
- case Instructions::f64x2_lt.value():
- case Instructions::f64x2_gt.value():
- case Instructions::f64x2_le.value():
- case Instructions::f64x2_ge.value():
- case Instructions::v128_not.value():
- case Instructions::v128_and.value():
- case Instructions::v128_andnot.value():
- case Instructions::v128_or.value():
- case Instructions::v128_xor.value():
- case Instructions::v128_bitselect.value():
- case Instructions::v128_any_true.value():
- case Instructions::f32x4_demote_f64x2_zero.value():
- case Instructions::f64x2_promote_low_f32x4.value():
- case Instructions::i8x16_abs.value():
- case Instructions::i8x16_neg.value():
- case Instructions::i8x16_popcnt.value():
- case Instructions::i8x16_all_true.value():
- case Instructions::i8x16_bitmask.value():
- case Instructions::i8x16_narrow_i16x8_s.value():
- case Instructions::i8x16_narrow_i16x8_u.value():
- case Instructions::f32x4_ceil.value():
- case Instructions::f32x4_floor.value():
- case Instructions::f32x4_trunc.value():
- case Instructions::f32x4_nearest.value():
- case Instructions::i8x16_shl.value():
- case Instructions::i8x16_shr_s.value():
- case Instructions::i8x16_shr_u.value():
- case Instructions::i8x16_add.value():
- case Instructions::i8x16_add_sat_s.value():
- case Instructions::i8x16_add_sat_u.value():
- case Instructions::i8x16_sub.value():
- case Instructions::i8x16_sub_sat_s.value():
- case Instructions::i8x16_sub_sat_u.value():
- case Instructions::f64x2_ceil.value():
- case Instructions::f64x2_floor.value():
- case Instructions::i8x16_min_s.value():
- case Instructions::i8x16_min_u.value():
- case Instructions::i8x16_max_s.value():
- case Instructions::i8x16_max_u.value():
- case Instructions::f64x2_trunc.value():
- case Instructions::i8x16_avgr_u.value():
- case Instructions::i16x8_extadd_pairwise_i8x16_s.value():
- case Instructions::i16x8_extadd_pairwise_i8x16_u.value():
- case Instructions::i32x4_extadd_pairwise_i16x8_s.value():
- case Instructions::i32x4_extadd_pairwise_i16x8_u.value():
- case Instructions::i16x8_abs.value():
- case Instructions::i16x8_neg.value():
- case Instructions::i16x8_q15mulr_sat_s.value():
- case Instructions::i16x8_all_true.value():
- case Instructions::i16x8_bitmask.value():
- case Instructions::i16x8_narrow_i32x4_s.value():
- case Instructions::i16x8_narrow_i32x4_u.value():
- case Instructions::i16x8_extend_low_i8x16_s.value():
- case Instructions::i16x8_extend_high_i8x16_s.value():
- case Instructions::i16x8_extend_low_i8x16_u.value():
- case Instructions::i16x8_extend_high_i8x16_u.value():
- case Instructions::i16x8_shl.value():
- case Instructions::i16x8_shr_s.value():
- case Instructions::i16x8_shr_u.value():
- case Instructions::i16x8_add.value():
- case Instructions::i16x8_add_sat_s.value():
- case Instructions::i16x8_add_sat_u.value():
- case Instructions::i16x8_sub.value():
- case Instructions::i16x8_sub_sat_s.value():
- case Instructions::i16x8_sub_sat_u.value():
- case Instructions::f64x2_nearest.value():
- case Instructions::i16x8_mul.value():
- case Instructions::i16x8_min_s.value():
- case Instructions::i16x8_min_u.value():
- case Instructions::i16x8_max_s.value():
- case Instructions::i16x8_max_u.value():
- case Instructions::i16x8_avgr_u.value():
- case Instructions::i16x8_extmul_low_i8x16_s.value():
- case Instructions::i16x8_extmul_high_i8x16_s.value():
- case Instructions::i16x8_extmul_low_i8x16_u.value():
- case Instructions::i16x8_extmul_high_i8x16_u.value():
- case Instructions::i32x4_abs.value():
- case Instructions::i32x4_neg.value():
- case Instructions::i32x4_all_true.value():
- case Instructions::i32x4_bitmask.value():
- case Instructions::i32x4_extend_low_i16x8_s.value():
- case Instructions::i32x4_extend_high_i16x8_s.value():
- case Instructions::i32x4_extend_low_i16x8_u.value():
- case Instructions::i32x4_extend_high_i16x8_u.value():
- case Instructions::i32x4_shl.value():
- case Instructions::i32x4_shr_s.value():
- case Instructions::i32x4_shr_u.value():
- case Instructions::i32x4_add.value():
- case Instructions::i32x4_sub.value():
- case Instructions::i32x4_mul.value():
- case Instructions::i32x4_min_s.value():
- case Instructions::i32x4_min_u.value():
- case Instructions::i32x4_max_s.value():
- case Instructions::i32x4_max_u.value():
- case Instructions::i32x4_dot_i16x8_s.value():
- case Instructions::i32x4_extmul_low_i16x8_s.value():
- case Instructions::i32x4_extmul_high_i16x8_s.value():
- case Instructions::i32x4_extmul_low_i16x8_u.value():
- case Instructions::i32x4_extmul_high_i16x8_u.value():
- case Instructions::i64x2_abs.value():
- case Instructions::i64x2_neg.value():
- case Instructions::i64x2_all_true.value():
- case Instructions::i64x2_bitmask.value():
- case Instructions::i64x2_extend_low_i32x4_s.value():
- case Instructions::i64x2_extend_high_i32x4_s.value():
- case Instructions::i64x2_extend_low_i32x4_u.value():
- case Instructions::i64x2_extend_high_i32x4_u.value():
- case Instructions::i64x2_shl.value():
- case Instructions::i64x2_shr_s.value():
- case Instructions::i64x2_shr_u.value():
- case Instructions::i64x2_add.value():
- case Instructions::i64x2_sub.value():
- case Instructions::i64x2_mul.value():
- case Instructions::i64x2_eq.value():
- case Instructions::i64x2_ne.value():
- case Instructions::i64x2_lt_s.value():
- case Instructions::i64x2_gt_s.value():
- case Instructions::i64x2_le_s.value():
- case Instructions::i64x2_ge_s.value():
- case Instructions::i64x2_extmul_low_i32x4_s.value():
- case Instructions::i64x2_extmul_high_i32x4_s.value():
- case Instructions::i64x2_extmul_low_i32x4_u.value():
- case Instructions::i64x2_extmul_high_i32x4_u.value():
- case Instructions::f32x4_abs.value():
- case Instructions::f32x4_neg.value():
- case Instructions::f32x4_sqrt.value():
- case Instructions::f32x4_add.value():
- case Instructions::f32x4_sub.value():
- case Instructions::f32x4_mul.value():
- case Instructions::f32x4_div.value():
- case Instructions::f32x4_min.value():
- case Instructions::f32x4_max.value():
- case Instructions::f32x4_pmin.value():
- case Instructions::f32x4_pmax.value():
- case Instructions::f64x2_abs.value():
- case Instructions::f64x2_neg.value():
- case Instructions::f64x2_sqrt.value():
- case Instructions::f64x2_add.value():
- case Instructions::f64x2_sub.value():
- case Instructions::f64x2_mul.value():
- case Instructions::f64x2_div.value():
- case Instructions::f64x2_min.value():
- case Instructions::f64x2_max.value():
- case Instructions::f64x2_pmin.value():
- case Instructions::f64x2_pmax.value():
- case Instructions::i32x4_trunc_sat_f32x4_s.value():
- case Instructions::i32x4_trunc_sat_f32x4_u.value():
- case Instructions::f32x4_convert_i32x4_s.value():
- case Instructions::f32x4_convert_i32x4_u.value():
- case Instructions::i32x4_trunc_sat_f64x2_s_zero.value():
- case Instructions::i32x4_trunc_sat_f64x2_u_zero.value():
- case Instructions::f64x2_convert_low_i32x4_s.value():
- case Instructions::f64x2_convert_low_i32x4_u.value():
- case Instructions::i8x16_relaxed_swizzle.value():
- case Instructions::i32x4_relaxed_trunc_f32x4_s.value():
- case Instructions::i32x4_relaxed_trunc_f32x4_u.value():
- case Instructions::i32x4_relaxed_trunc_f64x2_s_zero.value():
- case Instructions::i32x4_relaxed_trunc_f64x2_u_zero.value():
- case Instructions::f32x4_relaxed_madd.value():
- case Instructions::f32x4_relaxed_nmadd.value():
- case Instructions::f64x2_relaxed_madd.value():
- case Instructions::f64x2_relaxed_nmadd.value():
- case Instructions::i8x16_relaxed_laneselect.value():
- case Instructions::i16x8_relaxed_laneselect.value():
- case Instructions::i32x4_relaxed_laneselect.value():
- case Instructions::i64x2_relaxed_laneselect.value():
- case Instructions::f32x4_relaxed_min.value():
- case Instructions::f32x4_relaxed_max.value():
- case Instructions::f64x2_relaxed_min.value():
- case Instructions::f64x2_relaxed_max.value():
- case Instructions::i16x8_relaxed_q15mulr_s.value():
- case Instructions::i16x8_relaxed_dot_i8x16_i7x16_s.value():
- case Instructions::i32x4_relaxed_dot_i8x16_i7x16_add_s.value():
- // op
- return Instruction { full_opcode };
- default:
- return ParseError::UnknownInstruction;
- }
- }
- }
- return ParseError::UnknownInstruction;
-}
-
-ParseResult<CustomSection> CustomSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("CustomSection"sv);
- auto name = TRY(parse_name(stream));
- auto remaining = stream.remaining();
- auto maybe_data_buffer = ByteBuffer::create_uninitialized(remaining);
- if (maybe_data_buffer.is_error())
- return ParseError::OutOfMemory;
- auto data_buffer = maybe_data_buffer.release_value();
-
- size_t nread = 0;
- do {
- auto read = MUST(stream.read_some(data_buffer.bytes().slice(nread)));
- nread += read.size();
- } while (nread != remaining && !stream.is_eof());
-
- if (nread != remaining)
- return ParseError::UnexpectedEof;
-
- return CustomSection(name, move(data_buffer));
-}
-
-// https://webassembly.github.io/spec/core/binary/types.html#recursive-types
-ParseResult<TypeSection::Type> TypeSection::Type::parse(ConstrainedStream& stream, Optional<u8> leading_tag)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Type"sv);
- u8 tag;
- if (leading_tag.has_value())
- tag = *leading_tag;
- else
- tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- bool is_final = true;
- Vector<TypeIndex> supertypes;
- if (tag == Constants::sub_type_tag || tag == Constants::sub_final_type_tag) {
- is_final = tag == Constants::sub_final_type_tag;
- supertypes = TRY(parse_vector<GenericIndexParser<TypeIndex>>(stream));
- tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- }
-
- switch (tag) {
- case Constants::function_signature_tag:
- return Type { TRY(FunctionType::parse(stream)), move(supertypes), is_final };
- case Constants::struct_tag:
- return Type { TRY(StructType::parse(stream)), move(supertypes), is_final };
- case Constants::array_tag:
- return Type { TRY(ArrayType::parse(stream)), move(supertypes), is_final };
- default:
- return ParseError::InvalidTag;
- }
-}
-
-// https://webassembly.github.io/spec/core/binary/modules.html#type-section
-// https://webassembly.github.io/spec/core/binary/types.html#recursive-types
-ParseResult<TypeSection> TypeSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("TypeSection"sv);
-
- auto rec_type_count_or_error = stream.read_value<LEB128<u32>>();
- if (rec_type_count_or_error.is_error())
- return with_eof_check(stream, ParseError::ExpectedSize);
- size_t rec_type_count = rec_type_count_or_error.release_value();
-
- Vector<Type> types;
- types.ensure_capacity(rec_type_count);
- for (size_t rec_type_index = 0; rec_type_index < rec_type_count; ++rec_type_index) {
- auto tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- auto first_type_index = types.size();
- if (tag == Constants::rec_group_tag) {
- auto sub_type_count_or_error = stream.read_value<LEB128<u32>>();
- if (sub_type_count_or_error.is_error())
- return with_eof_check(stream, ParseError::ExpectedSize);
- size_t sub_type_count = sub_type_count_or_error.release_value();
- for (size_t i = 0; i < sub_type_count; ++i)
- types.append(TRY(Type::parse(stream)));
- } else {
- types.append(TRY(Type::parse(stream, tag)));
- }
-
- Type::RecGroupSpan const span {
- static_cast<u32>(first_type_index),
- static_cast<u32>(types.size() - first_type_index),
- };
- for (size_t i = first_type_index; i < types.size(); ++i)
- types[i].set_rec_group(span);
- }
-
- return TypeSection { types };
-}
-
-ParseResult<ImportSection::Import> ImportSection::Import::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Import"sv);
- auto module = TRY(parse_name(stream));
- auto name = TRY(parse_name(stream));
- auto tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- switch (tag) {
- case Constants::extern_function_tag: {
- auto index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
- return Import { module, name, index };
- }
- case Constants::extern_table_tag:
- return parse_with_type<TableType>(stream, module, name);
- case Constants::extern_memory_tag:
- return parse_with_type<MemoryType>(stream, module, name);
- case Constants::extern_global_tag:
- return parse_with_type<GlobalType>(stream, module, name);
- case Constants::extern_tag_tag:
- return parse_with_type<TagType>(stream, module, name);
- default:
- return ParseError::InvalidTag;
- }
-}
-
-ParseResult<ImportSection> ImportSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("ImportSection"sv);
- auto imports = TRY(parse_vector<Import>(stream));
- return ImportSection { imports };
-}
-
-ParseResult<FunctionSection> FunctionSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionSection"sv);
- auto indices = TRY(parse_vector<u32>(stream));
-
- Vector<TypeIndex> typed_indices;
- typed_indices.ensure_capacity(indices.size());
- for (auto entry : indices)
- typed_indices.append(entry);
-
- return FunctionSection { move(typed_indices) };
-}
-
-// https://webassembly.github.io/spec/core/binary/modules.html#table-section
-// table ::= tt:tabletype => table tt (ref.null ht) (if tt = at lim (ref null? ht))
-// | 0x40 0x00 tt:tabletype e:expr => table tt e
-ParseResult<TableSection::Table> TableSection::Table::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Table"sv);
-
- auto tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- if (tag == 0x40) {
- auto reserved = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
- if (reserved != 0x00)
- return ParseError::InvalidTag;
- auto type = TRY(TableType::parse(stream));
- auto initializer = TRY(Expression::parse(stream));
- return Table { type, move(initializer) };
- }
-
- auto element_type = TRY(parse_reference_type(stream, tag));
- auto limits = TRY(Limits::parse(stream));
- auto type = TableType { element_type, limits };
-
- // Synthesize the implicit initializer (ref.null ht).
- auto null_element = element_type;
- null_element.set_nullable(true);
- Vector<Instruction> instructions {
- Instruction(Instructions::ref_null, null_element),
- Instruction(Instructions::synthetic_end_expression),
- };
- return Table { type, Expression { move(instructions) } };
-}
-
-ParseResult<TableSection> TableSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableSection"sv);
- auto tables = TRY(parse_vector<Table>(stream));
- return TableSection { move(tables) };
-}
-
-ParseResult<MemorySection::Memory> MemorySection::Memory::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Memory"sv);
- auto type = TRY(MemoryType::parse(stream));
- return Memory { type };
-}
-
-ParseResult<MemorySection> MemorySection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemorySection"sv);
- auto memories = TRY(parse_vector<Memory>(stream));
- return MemorySection { memories };
-}
-
-ParseResult<Expression> Expression::parse(ConstrainedStream& stream, Optional<size_t> size_hint)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Expression"sv);
-
- InstructionPointer ip { 0 };
- Vector<InstructionPointer> stack;
- Vector<Instruction> instructions;
- if (size_hint.has_value())
- instructions.ensure_capacity(size_hint.release_value());
- while (true) {
- auto instruction = TRY(Instruction::parse(stream));
- switch (instruction.opcode().value()) {
- case Instructions::block.value():
- case Instructions::loop.value():
- case Instructions::if_.value():
- case Instructions::try_table.value():
- stack.append(ip);
- break;
- case Instructions::structured_end.value(): {
- if (stack.is_empty()) {
- instructions.empend(Instructions::synthetic_end_expression); // Synthetic noop to mark the end of the expression.
- return Expression { move(instructions) };
- }
- // Patch the end_ip of the last structured instruction
- auto entry = stack.take_last();
- bool valid_type = instructions[entry.value()].arguments().visit(
- [&](Instruction::StructuredInstructionArgs& args) {
- args.end_ip = ip + (args.else_ip().has_value() ? 1 : 0);
- return true;
- },
- [&](Instruction::TryTableArgs& args) {
- args.end_ip = ip;
- return true;
- },
- [](auto&) { return false; });
-
- if (!valid_type)
- return ParseError::InvalidType;
-
- break;
- }
- case Instructions::structured_else.value(): {
- if (stack.is_empty())
- return ParseError::UnknownInstruction;
- auto entry = stack.last();
- auto* args = instructions[entry.value()].arguments().get_pointer<Instruction::StructuredInstructionArgs>();
- if (!args)
- return ParseError::InvalidType;
-
- args->else_ip() = ip + 1;
- break;
- }
- }
- instructions.append(move(instruction));
- ++ip;
- }
-
- instructions.empend(Instructions::synthetic_end_expression); // Synthetic noop to mark the end of the expression.
-
- return Expression { move(instructions) };
-}
-
-ParseResult<GlobalSection::Global> GlobalSection::Global::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Global"sv);
- auto type = TRY(GlobalType::parse(stream));
- auto exprs = TRY(Expression::parse(stream));
- return Global { type, move(exprs) };
-}
-
-ParseResult<GlobalSection> GlobalSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalSection"sv);
- auto result = TRY(parse_vector<Global>(stream));
- return GlobalSection { move(result) };
-}
-
-ParseResult<ExportSection::Export> ExportSection::Export::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Export"sv);
- auto name = TRY(parse_name(stream));
- auto tag = TRY_READ(stream, u8, ParseError::ExpectedKindTag);
-
- auto index = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedIndex);
-
- switch (tag) {
- case Constants::extern_function_tag:
- return Export { name, ExportDesc { FunctionIndex { index } } };
- case Constants::extern_table_tag:
- return Export { name, ExportDesc { TableIndex { index } } };
- case Constants::extern_memory_tag:
- return Export { name, ExportDesc { MemoryIndex { index } } };
- case Constants::extern_global_tag:
- return Export { name, ExportDesc { GlobalIndex { index } } };
- case Constants::extern_tag_tag:
- return Export { name, ExportDesc { TagIndex { index } } };
- default:
- return ParseError::InvalidTag;
- }
-}
-
-ParseResult<ExportSection> ExportSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("ExportSection"sv);
- auto result = TRY(parse_vector<Export>(stream));
- return ExportSection { result };
-}
-
-ParseResult<StartSection::StartFunction> StartSection::StartFunction::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartFunction"sv);
- auto index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
- return StartFunction { index };
-}
-
-ParseResult<StartSection> StartSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartSection"sv);
- auto result = TRY(StartFunction::parse(stream));
- return StartSection { result };
-}
-
-ParseResult<ElementSection::Element> ElementSection::Element::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Element"sv);
- auto tag = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedKindTag);
-
- if (tag > 0x07)
- return ParseError::InvalidTag;
-
- auto has_passive = (tag & 0x01) != 0;
- auto has_explicit_index = (tag & 0x02) != 0;
- auto has_exprs = (tag & 0x04) != 0;
-
- Variant<Active, Passive, Declarative> mode = Passive {};
- if (has_passive) {
- if (has_explicit_index) {
- mode = Declarative {};
- } else {
- mode = Passive {};
- }
- } else {
- TableIndex table_index = 0;
- if (has_explicit_index)
- table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
- auto expression = TRY(Expression::parse(stream));
- mode = Active { table_index, move(expression) };
- }
-
- // https://webassembly.github.io/spec/core/binary/modules.html#element-section
- // elemkind ::= 0x00 => (ref func)
- auto type = has_exprs ? ValueType(ValueType::FunctionReference) : ValueType(ValueType::FunctionReference, false);
- if (has_passive || has_explicit_index) {
- if (has_exprs) {
- type = TRY(ValueType::parse(stream));
- } else {
- auto extern_ = TRY_READ(stream, u8, ParseError::InvalidType);
- // Make sure that this is a function, as it's technically only the
- // allowed one.
- if (extern_ != 0x00) {
- return ParseError::InvalidType;
- }
- type = ValueType(ValueType::FunctionReference, false);
- }
- }
-
- Vector<Expression> items;
- if (!has_exprs) {
- auto indices = TRY(parse_vector<GenericIndexParser<FunctionIndex>>(stream));
- for (auto& index : indices) {
- Vector<Instruction> instructions {
- Instruction(Instructions::ref_func, index),
- Instruction(Instructions::synthetic_end_expression),
- };
- items.empend(move(instructions));
- }
- } else {
- items = TRY(parse_vector<Expression>(stream));
- }
-
- return Element { type, move(items), move(mode) };
-}
-
-ParseResult<ElementSection> ElementSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("ElementSection"sv);
- auto result = TRY(parse_vector<Element>(stream));
- return ElementSection { move(result) };
-}
-
-ParseResult<Locals> Locals::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Locals"sv);
- auto count = TRY_READ(stream, LEB128<u32>, ParseError::InvalidSize);
-
- if (count > Constants::max_allowed_function_locals_per_type)
- return ParseError::HugeAllocationRequested;
-
- auto type = TRY(ValueType::parse(stream));
-
- return Locals { count, type };
-}
-
-ParseResult<CodeSection::Func> CodeSection::Func::parse(ConstrainedStream& stream, size_t size_hint)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Func"sv);
- auto locals = TRY(parse_vector<Locals>(stream));
- auto body = TRY(Expression::parse(stream, size_hint));
- return Func { move(locals), move(body) };
-}
-
-ParseResult<CodeSection::Code> CodeSection::Code::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Code"sv);
- auto size = TRY_READ(stream, LEB128<u32>, ParseError::InvalidSize);
-
- // Constrain to the declared size so an invalid entry fails here instead of desyncing the remaining entries in the section.
- auto code_stream = ConstrainedStream { MaybeOwned<Stream>(stream), size };
-
- // Empirically, if there are `size` bytes to be read, then there's around
- // `size / 2` instructions, so we pass that as our size hint.
- auto func = TRY(Func::parse(code_stream, size / 2));
-
- if (code_stream.remaining() != 0)
- return ParseError::SectionSizeMismatch;
-
- return Code { size, move(func) };
-}
-
-ParseResult<CodeSection> CodeSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("CodeSection"sv);
- auto result = TRY(parse_vector<Code>(stream));
- return CodeSection { move(result) };
-}
-
-ParseResult<DataSection::Data> DataSection::Data::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Data"sv);
- auto tag = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedKindTag);
-
- if (tag > 0x02)
- return ParseError::InvalidTag;
-
- if (tag == 0x00) {
- auto expr = TRY(Expression::parse(stream));
- auto init = TRY(parse_vector<u8>(stream));
- return Data { Active { move(init), { 0 }, move(expr) } };
- }
- if (tag == 0x01) {
- auto init = TRY(parse_vector<u8>(stream));
- return Data { Passive { move(init) } };
- }
- if (tag == 0x02) {
- auto index = TRY(GenericIndexParser<MemoryIndex>::parse(stream));
- auto expr = TRY(Expression::parse(stream));
- auto init = TRY(parse_vector<u8>(stream));
- return Data { Active { move(init), index, move(expr) } };
- }
- VERIFY_NOT_REACHED();
-}
-
-ParseResult<DataSection> DataSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataSection"sv);
- auto data = TRY(parse_vector<Data>(stream));
- return DataSection { move(data) };
-}
-
-ParseResult<DataCountSection> DataCountSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataCountSection"sv);
- auto value_or_error = stream.read_value<LEB128<u32>>();
- if (value_or_error.is_error()) {
- if (stream.is_eof()) {
- // The section simply didn't contain anything.
- return DataCountSection { {} };
- }
- return ParseError::ExpectedSize;
- }
- u32 value = value_or_error.release_value();
-
- return DataCountSection { value };
-}
-
-ParseResult<TagSection> TagSection::parse(ConstrainedStream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("TagSection"sv);
- // https://webassembly.github.io/exception-handling/core/binary/modules.html#binary-tagsec
- auto tags = TRY(parse_vector<TagType>(stream));
- return TagSection { move(tags) };
-}
-
-ParseResult<SectionId> SectionId::parse(Stream& stream)
-{
- u8 id = TRY_READ(stream, u8, ParseError::ExpectedIndex);
- switch (id) {
- case 0x00:
- return SectionId(SectionIdKind::Custom);
- case 0x01:
- return SectionId(SectionIdKind::Type);
- case 0x02:
- return SectionId(SectionIdKind::Import);
- case 0x03:
- return SectionId(SectionIdKind::Function);
- case 0x04:
- return SectionId(SectionIdKind::Table);
- case 0x05:
- return SectionId(SectionIdKind::Memory);
- case 0x06:
- return SectionId(SectionIdKind::Global);
- case 0x07:
- return SectionId(SectionIdKind::Export);
- case 0x08:
- return SectionId(SectionIdKind::Start);
- case 0x09:
- return SectionId(SectionIdKind::Element);
- case 0x0a:
- return SectionId(SectionIdKind::Code);
- case 0x0b:
- return SectionId(SectionIdKind::Data);
- case 0x0c:
- return SectionId(SectionIdKind::DataCount);
- case 0x0d:
- return SectionId(SectionIdKind::Tag);
- default:
- return ParseError::InvalidIndex;
- }
-}
-
-ParseResult<NonnullRefPtr<Module>> Module::parse(Stream& stream)
-{
- ScopeLogger<WASM_BINPARSER_DEBUG> logger("Module"sv);
- u8 buf[4];
- if (stream.read_until_filled({ buf, 4 }).is_error())
- return with_eof_check(stream, ParseError::InvalidInput);
- if (Bytes { buf, 4 } != wasm_magic.span())
- return with_eof_check(stream, ParseError::InvalidModuleMagic);
-
- if (stream.read_until_filled({ buf, 4 }).is_error())
- return with_eof_check(stream, ParseError::InvalidInput);
- if (Bytes { buf, 4 } != wasm_version.span())
- return with_eof_check(stream, ParseError::InvalidModuleVersion);
-
- auto last_section_id = SectionId::SectionIdKind::Custom;
- u32 seen_section_kinds = 0;
- auto module_ptr = make_ref_counted<Module>();
- auto& module = *module_ptr;
-
- while (!stream.is_eof()) {
- auto section_id = TRY(SectionId::parse(stream));
- size_t section_size = TRY_READ(stream, LEB128<u32>, ParseError::ExpectedSize);
- auto section_stream = ConstrainedStream { MaybeOwned<Stream>(stream), section_size };
-
- if (section_id.kind() != SectionId::SectionIdKind::Custom) {
- auto kind_bit = 1u << to_underlying(section_id.kind());
- if (seen_section_kinds & kind_bit)
- return ParseError::DuplicateSection;
- seen_section_kinds |= kind_bit;
- }
-
- switch (section_id.kind()) {
- case SectionId::SectionIdKind::Custom:
- module.custom_sections().append(TRY(CustomSection::parse(section_stream)));
- break;
- case SectionId::SectionIdKind::Type:
- module.type_section() = TRY(TypeSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Import:
- module.import_section() = TRY(ImportSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Function:
- module.function_section() = TRY(FunctionSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Table:
- module.table_section() = TRY(TableSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Memory:
- module.memory_section() = TRY(MemorySection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Global:
- module.global_section() = TRY(GlobalSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Export:
- module.export_section() = TRY(ExportSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Start:
- module.start_section() = TRY(StartSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Element:
- module.element_section() = TRY(ElementSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Code:
- module.code_section() = TRY(CodeSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Data:
- module.data_section() = TRY(DataSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::DataCount:
- module.data_count_section() = TRY(DataCountSection::parse(section_stream));
- break;
- case SectionId::SectionIdKind::Tag:
- module.tag_section() = TRY(TagSection::parse(section_stream));
- break;
- default:
- return ParseError::InvalidIndex;
- }
- if (!section_id.can_appear_after(last_section_id))
- return ParseError::SectionOutOfOrder;
- // Custom sections don't participate in ordering.
- if (section_id.kind() != SectionId::SectionIdKind::Custom)
- last_section_id = section_id.kind();
- if (section_stream.remaining() != 0)
- return ParseError::SectionSizeMismatch;
- }
-
- module_ptr->preprocess();
-
- return module_ptr;
-}
-
-void Module::preprocess()
-{
-}
-
-ByteString parse_error_to_byte_string(ParseError error)
-{
- switch (error) {
- case ParseError::UnexpectedEof:
- return "Unexpected end-of-file";
- case ParseError::ExpectedIndex:
- return "Expected a valid index value";
- case ParseError::ExpectedKindTag:
- return "Expected a valid kind tag";
- case ParseError::ExpectedSize:
- return "Expected a valid LEB128-encoded size";
- case ParseError::ExpectedValueOrTerminator:
- return "Expected either a terminator or a value";
- case ParseError::InvalidIndex:
- return "An index parsed was semantically invalid";
- case ParseError::InvalidInput:
- return "Input data contained invalid bytes";
- case ParseError::InvalidModuleMagic:
- return "Incorrect module magic (did not match \\0asm)";
- case ParseError::InvalidModuleVersion:
- return "Incorrect module version";
- case ParseError::InvalidSize:
- return "A parsed size did not make sense in context";
- case ParseError::InvalidTag:
- return "A parsed tag did not make sense in context";
- case ParseError::InvalidType:
- return "A parsed type did not make sense in context";
- case ParseError::HugeAllocationRequested:
- return "Parsing caused an attempt to allocate a very big chunk of memory, likely malformed data";
- case ParseError::OutOfMemory:
- return "The parser hit an OOM condition";
- case ParseError::ExpectedFloatingImmediate:
- return "Expected a floating point immediate";
- case ParseError::ExpectedSignedImmediate:
- return "Expected a signed integer immediate";
- case ParseError::InvalidImmediate:
- return "A parsed instruction immediate was invalid for the instruction it was used for";
- case ParseError::SectionSizeMismatch:
- return "A parsed section did not fulfill its expected size";
- case ParseError::InvalidUtf8:
- return "A parsed string was not valid UTF-8";
- case ParseError::UnknownInstruction:
- return "A parsed instruction was not known to this parser";
- case ParseError::DuplicateSection:
- return "Two sections of the same type were encountered";
- case ParseError::SectionOutOfOrder:
- return "A section encountered was not in the correct ordering";
- }
- return "Unknown error";
-}
-
-}
diff --git a/Libraries/LibWasm/Printer/Printer.cpp b/Libraries/LibWasm/Printer/Printer.cpp
deleted file mode 100644
index a7f63d7186a..00000000000
--- a/Libraries/LibWasm/Printer/Printer.cpp
+++ /dev/null
@@ -1,1486 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/GenericShorthands.h>
-#include <AK/HashMap.h>
-#include <AK/TemporaryChange.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/Printer/Printer.h>
-
-namespace Wasm {
-
-struct Names {
- static HashMap<OpCode, ByteString>& instruction_names;
- static HashMap<ByteString, OpCode>& instructions_by_name;
-};
-
-ByteString instruction_name(OpCode const& opcode)
-{
- return Names::instruction_names.get(opcode).value_or(ByteString::formatted("<unknown {:#x}>", opcode.value()));
-}
-
-Optional<OpCode> instruction_from_name(StringView name)
-{
- if (Names::instructions_by_name.is_empty()) {
- for (auto& entry : Names::instruction_names)
- Names::instructions_by_name.set(entry.value, entry.key);
- }
-
- return Names::instructions_by_name.get(name);
-}
-
-void Printer::print_indent()
-{
- for (size_t i = 0; i < m_indent; ++i)
- m_stream.write_until_depleted(" "sv.bytes()).release_value_but_fixme_should_propagate_errors();
-}
-
-void Printer::print(Wasm::BlockType const& type)
-{
- print_indent();
- print("(type block ");
- switch (type.kind()) {
- case Wasm::BlockType::Kind::Index:
- print("index {})\n", type.type_index().value());
- return;
- case Wasm::BlockType::Kind::Type: {
- print("type\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(type.value_type());
- }
- print_indent();
- print(")\n");
- return;
- }
- case Wasm::BlockType::Kind ::Empty:
- print("empty)\n");
- return;
- }
- VERIFY_NOT_REACHED();
-}
-
-void Printer::print(Wasm::CodeSection const& section)
-{
- if (section.functions().is_empty())
- return;
- print_indent();
- print("(section code\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& code : section.functions())
- print(code);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::CodeSection::Code const& code)
-{
- print(code.func());
-}
-
-void Printer::print(Wasm::CustomSection const& section)
-{
- print_indent();
- print("(section custom\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(name `{}')\n", section.name());
- print_indent();
- print("(contents {} bytes)\n", section.contents().size());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::DataCountSection const& section)
-{
- if (!section.count().has_value())
- return;
- print_indent();
- print("(section data count\n");
- if (section.count().has_value()) {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(count `{}')\n", *section.count());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::DataSection const& section)
-{
- if (section.data().is_empty())
- return;
- print_indent();
- print("(section data\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& entry : section.data())
- print(entry);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::DataSection::Data const& data)
-{
- print_indent();
- print("(data with value\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- data.value().visit(
- [this](DataSection::Data::Passive const& value) {
- print_indent();
- print("(passive init {}xu8 (", value.init.size());
- print("{}", ByteString::join(' ', value.init, "{:x}"sv));
- print(")\n");
- },
- [this](DataSection::Data::Active const& value) {
- print_indent();
- print("(active init {}xu8 (", value.init.size());
- print("{}", ByteString::join(' ', value.init, "{:x}"sv));
- print(")\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(offset\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(value.offset);
- }
- print_indent();
- print(")\n");
- }
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(index {})\n", value.index.value());
- }
- print_indent();
- print(")\n");
- });
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::ElementSection const& section)
-{
- if (section.segments().is_empty())
- return;
- print_indent();
- print("(section element\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& entry : section.segments())
- print(entry);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::ElementSection::Element const& element)
-{
- print_indent();
- print("(element ");
- {
- TemporaryChange<size_t> change { m_indent, 0 };
- print(element.type);
- }
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(init\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& entry : element.init)
- print(entry);
- }
- print_indent();
- print(")\n");
- print_indent();
- print("(mode ");
- element.mode.visit(
- [this](ElementSection::Active const& active) {
- print("\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(active index {}\n", active.index.value());
- {
- print(active.expression);
- }
- print_indent();
- print(")\n");
- }
- print_indent();
- },
- [this](ElementSection::Passive const&) { print("passive"); },
- [this](ElementSection::Declarative const&) { print("declarative"); });
- print(")\n");
- }
-}
-
-void Printer::print(Wasm::ExportSection const& section)
-{
- if (section.entries().is_empty())
- return;
- print_indent();
- print("(section export\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& entry : section.entries())
- print(entry);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::ExportSection::Export const& entry)
-{
- print_indent();
- print("(export `{}' as\n", entry.name());
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- entry.description().visit(
- [this](FunctionIndex const& index) { print("(function index {})\n", index.value()); },
- [this](TableIndex const& index) { print("(table index {})\n", index.value()); },
- [this](MemoryIndex const& index) { print("(memory index {})\n", index.value()); },
- [this](GlobalIndex const& index) { print("(global index {})\n", index.value()); },
- [this](TagIndex const& index) { print("(tag index {})\n", index.value()); });
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::Expression const& expression)
-{
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& instr : expression.instructions())
- print(instr);
-}
-
-void Printer::print(Wasm::CodeSection::Func const& func)
-{
- print_indent();
- print("(function\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- {
- print_indent();
- print("(locals\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& locals : func.locals())
- print(locals);
- }
- print_indent();
- print(")\n");
- }
- print_indent();
- print("(body\n");
- print(func.body());
- print_indent();
- print(")\n");
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::FunctionSection const& section)
-{
- if (section.types().is_empty())
- return;
- print_indent();
- print("(section function\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& index : section.types()) {
- print_indent();
- print("(type index {})\n", index.value());
- }
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::FunctionType const& type)
-{
- print_indent();
- print("(type function\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(parameters\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& param : type.parameters())
- print(param);
- }
- print_indent();
- print(")\n");
- }
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(results\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& type : type.results())
- print(type);
- }
- print_indent();
- print(")\n");
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::GlobalSection const& section)
-{
- if (section.entries().is_empty())
- return;
- print_indent();
- print("(section global\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& entry : section.entries())
- print(entry);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::GlobalSection::Global const& entry)
-{
- print_indent();
- print("(global\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(type\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(entry.type());
- }
- print_indent();
- print(")\n");
- }
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(init\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(entry.expression());
- }
- print_indent();
- print(")\n");
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::GlobalType const& type)
-{
- print_indent();
- print("(type global {}mutable\n", type.is_mutable() ? "" : "im");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(type.type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::TagType const& type)
-{
- print_indent();
- print("(type tag\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(type.type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::ImportSection const& section)
-{
- if (section.imports().is_empty())
- return;
- print_indent();
- print("(section import\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& import : section.imports())
- print(import);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::ImportSection::Import const& import)
-{
- print_indent();
- print("(import `{}' from `{}' as\n", import.name(), import.module());
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- import.description().visit(
- [this](auto const& type) {
- print(type);
- },
- [this](TypeIndex const& index) {
- print_indent();
- print("(type index {})\n", index.value());
- });
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::TagSection const& section)
-{
- // (section tag\n[ ](tag type)*)
- if (section.tags().is_empty())
- return;
-
- print_indent();
- print("(section tag\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& tag : section.tags())
- print(tag);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::TypeIndex const& index)
-{
- print_indent();
- print("(type index {})\n", index.value());
-}
-
-void Printer::print(Wasm::Instruction const& instruction)
-{
- print_indent();
- print("({}", instruction_name(instruction.opcode()));
- if (instruction.arguments().has<u8>()) {
- if (first_is_one_of(instruction.opcode(), Instructions::local_get, Instructions::local_set, Instructions::local_tee, Instructions::synthetic_argument_get)) {
- print(" (local index {})", instruction.local_index().value());
- }
- print(")\n");
- } else {
- print(" ");
- instruction.arguments().visit(
- [&](Instruction::BranchArgs const& branch) { print("(label index {})", branch.label.value()); },
- [&](BlockType const& type) { print(type); },
- [&](DataIndex const& index) { print("(data index {})", index.value()); },
- [&](ElementIndex const& index) { print("(element index {})", index.value()); },
- [&](FunctionIndex const& index) { print("(function index {})", index.value()); },
- [&](GlobalIndex const& index) { print("(global index {})", index.value()); },
- [&](LabelIndex const& index) { print("(label index {})", index.value()); },
- [&](LocalIndex const& index) { print("(local index {})", index.value()); },
- [&](TableIndex const& index) { print("(table index {})", index.value()); },
- [&](TypeIndex const& index) { print("(type index {})", index.value()); },
- [&](Instruction::IndirectCallArgs const& args) { print("(indirect (type index {}) (table index {}))", args.type.value(), args.table.value()); },
- [&](Instruction::MemoryArgument const& args) { print("(memory index {} (align {}) (offset {}))", args.memory_index.value(), args.align, args.offset); },
- [&](Instruction::AtomicMemoryArgument const& args) {
- using Width = Instruction::AtomicMemoryArgument::Width;
- using Op = Instruction::AtomicMemoryArgument::Op;
- auto width_name = [&] {
- switch (args.width) {
- case Width::I32:
- return "i32"sv;
- case Width::I64:
- return "i64"sv;
- case Width::I8As32:
- return "i32 8u"sv;
- case Width::I16As32:
- return "i32 16u"sv;
- case Width::I8As64:
- return "i64 8u"sv;
- case Width::I16As64:
- return "i64 16u"sv;
- case Width::I32As64:
- return "i64 32u"sv;
- }
- VERIFY_NOT_REACHED();
- }();
- auto op_name = [&] {
- switch (args.op) {
- case Op::None:
- return ""sv;
- case Op::Add:
- return "add"sv;
- case Op::Sub:
- return "sub"sv;
- case Op::And:
- return "and"sv;
- case Op::Or:
- return "or"sv;
- case Op::Xor:
- return "xor"sv;
- case Op::Xchg:
- return "xchg"sv;
- }
- VERIFY_NOT_REACHED();
- }();
- print("(memory index {} (align {}) (offset {})) (width {})", args.memory.memory_index.value(), args.memory.align, args.memory.offset, width_name);
- if (!op_name.is_empty())
- print(" (op {})", op_name);
- },
- [&](Instruction::MemoryAndLaneArgument const& args) { print("(memory index {} (align {}) (offset {})) (lane {})", args.memory.memory_index.value(), args.memory.align, args.memory.offset, args.lane); },
- [&](Instruction::MemoryInitArgs const& args) { print("(memory index {}) (data index {})", args.memory_index.value(), args.data_index.value()); },
- [&](Instruction::MemoryCopyArgs const& args) { print("(from (memory index {}) to (memory index {}))", args.src_index.value(), args.dst_index.value()); },
- [&](Instruction::MemoryIndexArgument const& args) { print("(memory index {})", args.memory_index.value()); },
- [&](Instruction::LaneIndex const& args) { print("(lane {})", args.lane); },
- [&](Instruction::ShuffleArgument const& args) {
- print("{{ {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} }}",
- args.lanes[0], args.lanes[1], args.lanes[2], args.lanes[3],
- args.lanes[4], args.lanes[5], args.lanes[6], args.lanes[7],
- args.lanes[8], args.lanes[9], args.lanes[10], args.lanes[11],
- args.lanes[12], args.lanes[13], args.lanes[14], args.lanes[15]);
- },
- [&](Instruction::StructuredInstructionArgs const& args) {
- print("(structured\n");
- TemporaryChange change { m_indent, m_indent + 1 };
- print(args.block_type);
- print_indent();
- print("(else {}) (end {})", args.else_ip().has_value() ? ByteString::number(args.else_ip()->value()) : "(none)", args.end_ip.value());
- if (args.meta.arity != 0 || args.meta.parameter_count != 0)
- print(" (meta arity {} params {})", args.meta.arity, args.meta.parameter_count);
- else
- print(" (meta none)");
- print(")");
- },
- [&](Instruction::TryTableArgs const& args) {
- print("(try_table ");
- print(args.block_type);
- print(" (catches\n");
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& catch_ : args.catches())
- print(catch_);
- print_indent();
- print(") (end {}))", args.end_ip.value());
- },
- [&](Instruction::TableBranchArgs const& args) {
- print("(table_branch");
- for (auto& label : args.labels)
- print(" (label {})", label.value());
- print(" (label {}))", args.default_.value());
- },
- [&](Instruction::TableElementArgs const& args) { print("(table_element (table index {}) (element index {}))", args.table_index.value(), args.element_index.value()); },
- [&](Instruction::TableTableArgs const& args) { print("(table_table (table index {}) (table index {}))", args.lhs.value(), args.rhs.value()); },
- [&](Instruction::StructFieldArgs const& args) { print("(type index {}) (field index {})", args.type_index.value(), args.field_index); },
- [&](Instruction::ArrayNewFixedArgs const& args) { print("(type index {}) (count {})", args.type_index.value(), args.count); },
- [&](Instruction::ArrayDataArgs const& args) { print("(type index {}) (data index {})", args.type_index.value(), args.data_index.value()); },
- [&](Instruction::ArrayElemArgs const& args) { print("(type index {}) (element index {})", args.type_index.value(), args.element_index.value()); },
- [&](Instruction::ArrayCopyArgs const& args) { print("(to (type index {}) from (type index {}))", args.destination_type_index.value(), args.source_type_index.value()); },
- [&](Instruction::BranchOnCastArgs const& args) {
- print("(label index {}) (source (type {}{})) (target (type {}{}))",
- args.branch.label.value(),
- args.source_type.kind_name(), args.source_type.is_nullable() ? " nullable"sv : ""sv,
- args.target_type.kind_name(), args.target_type.is_nullable() ? " nullable"sv : ""sv);
- },
- [&](ValueType const& type) { print(type); },
- [&](Vector<ValueType> const&) { print("(types...)"); },
- [&](auto const& value) { print("(const {})", value); });
-
- if (first_is_one_of(instruction.opcode(), Instructions::local_get, Instructions::local_set, Instructions::local_tee, Instructions::synthetic_argument_get, Instructions::synthetic_local_seti32_const, Instructions::synthetic_i32_storelocal))
- print(" (local index {})", instruction.local_index().value());
-
- print(")\n");
- }
-}
-
-void Printer::print(Catch const& catch_)
-{
- print_indent();
- StringBuilder name_builder;
- name_builder.appendff("catch{}{}", catch_.matching_tag_index().has_value() ? ""sv : "_all"sv, catch_.is_ref() ? "_ref"sv : ""sv);
- print("({} ", name_builder.string_view());
- if (auto index = catch_.matching_tag_index(); index.has_value())
- print("(tag index {})", index.value());
- print("\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(label index {})\n", catch_.target_label().value());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::Limits const& limits)
-{
- print_indent();
- print("(limits min={}", limits.min());
- if (limits.max().has_value())
- print(" max={}", limits.max().value());
- else
- print(" unbounded");
- print(")\n");
-}
-
-void Printer::print(Wasm::Locals const& local)
-{
- print_indent();
- print("(local x{} of type\n", local.n());
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(local.type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::MemorySection const& section)
-{
- if (section.memories().is_empty())
- return;
- print_indent();
- print("(section memory\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& memory : section.memories())
- print(memory);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::MemorySection::Memory const& memory)
-{
- print_indent();
- print("(memory\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(memory.type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::MemoryType const& type)
-{
- print_indent();
- print("(type memory\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(type.limits());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::Module const& module)
-{
- print_indent();
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print("(module\n");
- for (auto& custom_section : module.custom_sections())
- print(custom_section);
- print(module.type_section());
- print(module.import_section());
- print(module.function_section());
- print(module.table_section());
- print(module.memory_section());
- print(module.tag_section());
- print(module.global_section());
- print(module.export_section());
- print(module.start_section());
- print(module.element_section());
- print(module.code_section());
- print(module.data_section());
- print(module.data_count_section());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::StartSection const& section)
-{
- if (!section.function().has_value())
- return;
- print_indent();
- print("(section start\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(*section.function());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::StartSection::StartFunction const& function)
-{
- print_indent();
- print("(start function index {})\n", function.index().value());
-}
-
-void Printer::print(Wasm::TableSection const& section)
-{
- if (section.tables().is_empty())
- return;
- print_indent();
- print("(section table\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& table : section.tables())
- print(table);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::TableSection::Table const& table)
-{
- print_indent();
- print("(table\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(table.type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::TableType const& type)
-{
- print_indent();
- print("(type table min:{}", type.limits().min());
- if (type.limits().max().has_value())
- print(" max:{}", type.limits().max().value());
- print("\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(type.element_type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::TypeSection const& section)
-{
- if (section.types().is_empty())
- return;
- print_indent();
- print("(section type\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& type : section.types())
- print(type);
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::TypeSection::Type const& type)
-{
- type.description().visit(
- [&](Wasm::FunctionType const& func) { print(func); },
- [&](Wasm::StructType const& struct_) { print(struct_); },
- [&](Wasm::ArrayType const& array) { print(array); });
-}
-
-void Printer::print(Wasm::StructType const& struct_)
-{
- print_indent();
- print("(type struct\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print_indent();
- print("(fields\n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- for (auto& field : struct_.fields())
- print(field);
- }
- print_indent();
- print(")\n");
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::ArrayType const& array)
-{
- print_indent();
- print("(type array \n");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(array.type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::FieldType const& type)
-{
- print_indent();
- print("({}mutable\n", type.is_mutable() ? "" : "im");
- {
- TemporaryChange change { m_indent, m_indent + 1 };
- print(type.type());
- }
- print_indent();
- print(")\n");
-}
-
-void Printer::print(Wasm::ValueType const& type)
-{
- print_indent();
- print("(type {})\n", type.kind_name());
-}
-
-void Printer::print(Wasm::Value const& value, Wasm::ValueType const& type)
-{
- print_indent();
- switch (type.kind()) {
- case ValueType::I32:
- print("{}", value.to<i32>());
- break;
- case ValueType::I64:
- print("{}", value.to<i64>());
- break;
- case ValueType::F32:
- print("{}", value.to<f32>());
- break;
- case ValueType::F64:
- print("{}", value.to<f64>());
- break;
- case ValueType::V128:
- print("v128({:x})", value.value());
- break;
- case ValueType::I8:
- print("{}", value.to<i8>());
- break;
- case ValueType::I16:
- print("{}", value.to<i16>());
- break;
- case ValueType::FunctionReference:
- case ValueType::NoFunctionReference:
- case ValueType::ExternReference:
- case ValueType::NoExternReference:
- case ValueType::ExceptionReference:
- case ValueType::NoExceptionReference:
- case ValueType::AnyReference:
- case ValueType::EqReference:
- case ValueType::I31Reference:
- case ValueType::StructReference:
- case ValueType::ArrayReference:
- case ValueType::NoneReference:
- print("addr({})",
- value.to<Reference>().ref().visit(
- [](Wasm::Reference::Null const&) { return ByteString("null"); },
- [](Wasm::Reference::Exception const&) { return ByteString("exception"); },
- [](Wasm::Reference::I31 const& ref) { return ByteString::formatted("i31({})", ref.value); },
- [](Wasm::Reference::GcObject const& ref) { return ByteString::formatted("gc-object({:p})", ref.ptr); },
- [](auto const& ref) { return ByteString::number(ref.address.value()); }));
- break;
- case ValueType::TypeUseReference:
- print("typed-ref({})", type.unsafe_typeindex());
- break;
- }
- TemporaryChange<size_t> change { m_indent, 0 };
-}
-
-void Printer::print(Wasm::Value const& value)
-{
- print_indent();
- print("{:x}", value.value());
- TemporaryChange<size_t> change { m_indent, 0 };
-}
-
-void Printer::print(Wasm::Reference const& value)
-{
- print_indent();
- print(
- "addr({})\n",
- value.ref().visit(
- [](Wasm::Reference::Null const&) { return ByteString("null"); },
- [](Wasm::Reference::Exception const&) { return ByteString("exception"); },
- [](Wasm::Reference::I31 const& ref) { return ByteString::formatted("i31({})", ref.value); },
- [](Wasm::Reference::GcObject const& ref) { return ByteString::formatted("gc-object({:p})", ref.ptr); },
- [](auto const& ref) { return ByteString::number(ref.address.value()); }));
-}
-
-}
-
-HashMap<Wasm::OpCode, ByteString>& Wasm::Names::instruction_names = *new HashMap<Wasm::OpCode, ByteString> {
- { Instructions::unreachable, "unreachable" },
- { Instructions::nop, "nop" },
- { Instructions::block, "block" },
- { Instructions::loop, "loop" },
- { Instructions::if_, "if" },
- { Instructions::try_table, "try_table" },
- { Instructions::throw_, "throw" },
- { Instructions::throw_ref, "throw_ref" },
- { Instructions::br, "br" },
- { Instructions::br_if, "br.if" },
- { Instructions::br_table, "br.table" },
- { Instructions::return_, "return" },
- { Instructions::call, "call" },
- { Instructions::return_call, "return_call" },
- { Instructions::call_indirect, "call.indirect" },
- { Instructions::return_call_indirect, "return_call.indirect" },
- { Instructions::call_ref, "call_ref" },
- { Instructions::return_call_ref, "return_call_ref" },
- { Instructions::drop, "drop" },
- { Instructions::select, "select" },
- { Instructions::select_typed, "select.typed" },
- { Instructions::local_get, "local.get" },
- { Instructions::local_set, "local.set" },
- { Instructions::local_tee, "local.tee" },
- { Instructions::global_get, "global.get" },
- { Instructions::global_set, "global.set" },
- { Instructions::table_get, "table.get" },
- { Instructions::table_set, "table.set" },
- { Instructions::i32_load, "i32.load" },
- { Instructions::i64_load, "i64.load" },
- { Instructions::f32_load, "f32.load" },
- { Instructions::f64_load, "f64.load" },
- { Instructions::i32_load8_s, "i32.load8_s" },
- { Instructions::i32_load8_u, "i32.load8_u" },
- { Instructions::i32_load16_s, "i32.load16_s" },
- { Instructions::i32_load16_u, "i32.load16_u" },
- { Instructions::i64_load8_s, "i64.load8_s" },
- { Instructions::i64_load8_u, "i64.load8_u" },
- { Instructions::i64_load16_s, "i64.load16_s" },
- { Instructions::i64_load16_u, "i64.load16_u" },
- { Instructions::i64_load32_s, "i64.load32_s" },
- { Instructions::i64_load32_u, "i64.load32_u" },
- { Instructions::i32_store, "i32.store" },
- { Instructions::i64_store, "i64.store" },
- { Instructions::f32_store, "f32.store" },
- { Instructions::f64_store, "f64.store" },
- { Instructions::i32_store8, "i32.store8" },
- { Instructions::i32_store16, "i32.store16" },
- { Instructions::i64_store8, "i64.store8" },
- { Instructions::i64_store16, "i64.store16" },
- { Instructions::i64_store32, "i64.store32" },
- { Instructions::memory_size, "memory.size" },
- { Instructions::memory_grow, "memory.grow" },
- { Instructions::i32_const, "i32.const" },
- { Instructions::i64_const, "i64.const" },
- { Instructions::f32_const, "f32.const" },
- { Instructions::f64_const, "f64.const" },
- { Instructions::i32_eqz, "i32.eqz" },
- { Instructions::i32_eq, "i32.eq" },
- { Instructions::i32_ne, "i32.ne" },
- { Instructions::i32_lts, "i32.lts" },
- { Instructions::i32_ltu, "i32.ltu" },
- { Instructions::i32_gts, "i32.gts" },
- { Instructions::i32_gtu, "i32.gtu" },
- { Instructions::i32_les, "i32.les" },
- { Instructions::i32_leu, "i32.leu" },
- { Instructions::i32_ges, "i32.ges" },
- { Instructions::i32_geu, "i32.geu" },
- { Instructions::i64_eqz, "i64.eqz" },
- { Instructions::i64_eq, "i64.eq" },
- { Instructions::i64_ne, "i64.ne" },
- { Instructions::i64_lts, "i64.lts" },
- { Instructions::i64_ltu, "i64.ltu" },
- { Instructions::i64_gts, "i64.gts" },
- { Instructions::i64_gtu, "i64.gtu" },
- { Instructions::i64_les, "i64.les" },
- { Instructions::i64_leu, "i64.leu" },
- { Instructions::i64_ges, "i64.ges" },
- { Instructions::i64_geu, "i64.geu" },
- { Instructions::f32_eq, "f32.eq" },
- { Instructions::f32_ne, "f32.ne" },
- { Instructions::f32_lt, "f32.lt" },
- { Instructions::f32_gt, "f32.gt" },
- { Instructions::f32_le, "f32.le" },
- { Instructions::f32_ge, "f32.ge" },
- { Instructions::f64_eq, "f64.eq" },
- { Instructions::f64_ne, "f64.ne" },
- { Instructions::f64_lt, "f64.lt" },
- { Instructions::f64_gt, "f64.gt" },
- { Instructions::f64_le, "f64.le" },
- { Instructions::f64_ge, "f64.ge" },
- { Instructions::i32_clz, "i32.clz" },
- { Instructions::i32_ctz, "i32.ctz" },
- { Instructions::i32_popcnt, "i32.popcnt" },
- { Instructions::i32_add, "i32.add" },
- { Instructions::i32_sub, "i32.sub" },
- { Instructions::i32_mul, "i32.mul" },
- { Instructions::i32_divs, "i32.divs" },
- { Instructions::i32_divu, "i32.divu" },
- { Instructions::i32_rems, "i32.rems" },
- { Instructions::i32_remu, "i32.remu" },
- { Instructions::i32_and, "i32.and" },
- { Instructions::i32_or, "i32.or" },
- { Instructions::i32_xor, "i32.xor" },
- { Instructions::i32_shl, "i32.shl" },
- { Instructions::i32_shrs, "i32.shrs" },
- { Instructions::i32_shru, "i32.shru" },
- { Instructions::i32_rotl, "i32.rotl" },
- { Instructions::i32_rotr, "i32.rotr" },
- { Instructions::i64_clz, "i64.clz" },
- { Instructions::i64_ctz, "i64.ctz" },
- { Instructions::i64_popcnt, "i64.popcnt" },
- { Instructions::i64_add, "i64.add" },
- { Instructions::i64_sub, "i64.sub" },
- { Instructions::i64_mul, "i64.mul" },
- { Instructions::i64_divs, "i64.divs" },
- { Instructions::i64_divu, "i64.divu" },
- { Instructions::i64_rems, "i64.rems" },
- { Instructions::i64_remu, "i64.remu" },
- { Instructions::i64_and, "i64.and" },
- { Instructions::i64_or, "i64.or" },
- { Instructions::i64_xor, "i64.xor" },
- { Instructions::i64_shl, "i64.shl" },
- { Instructions::i64_shrs, "i64.shrs" },
- { Instructions::i64_shru, "i64.shru" },
- { Instructions::i64_rotl, "i64.rotl" },
- { Instructions::i64_rotr, "i64.rotr" },
- { Instructions::f32_abs, "f32.abs" },
- { Instructions::f32_neg, "f32.neg" },
- { Instructions::f32_ceil, "f32.ceil" },
- { Instructions::f32_floor, "f32.floor" },
- { Instructions::f32_trunc, "f32.trunc" },
- { Instructions::f32_nearest, "f32.nearest" },
- { Instructions::f32_sqrt, "f32.sqrt" },
- { Instructions::f32_add, "f32.add" },
- { Instructions::f32_sub, "f32.sub" },
- { Instructions::f32_mul, "f32.mul" },
- { Instructions::f32_div, "f32.div" },
- { Instructions::f32_min, "f32.min" },
- { Instructions::f32_max, "f32.max" },
- { Instructions::f32_copysign, "f32.copysign" },
- { Instructions::f64_abs, "f64.abs" },
- { Instructions::f64_neg, "f64.neg" },
- { Instructions::f64_ceil, "f64.ceil" },
- { Instructions::f64_floor, "f64.floor" },
- { Instructions::f64_trunc, "f64.trunc" },
- { Instructions::f64_nearest, "f64.nearest" },
- { Instructions::f64_sqrt, "f64.sqrt" },
- { Instructions::f64_add, "f64.add" },
- { Instructions::f64_sub, "f64.sub" },
- { Instructions::f64_mul, "f64.mul" },
- { Instructions::f64_div, "f64.div" },
- { Instructions::f64_min, "f64.min" },
- { Instructions::f64_max, "f64.max" },
- { Instructions::f64_copysign, "f64.copysign" },
- { Instructions::i32_wrap_i64, "i32.wrap_i64" },
- { Instructions::i32_trunc_sf32, "i32.trunc_sf32" },
- { Instructions::i32_trunc_uf32, "i32.trunc_uf32" },
- { Instructions::i32_trunc_sf64, "i32.trunc_sf64" },
- { Instructions::i32_trunc_uf64, "i32.trunc_uf64" },
- { Instructions::i64_extend_si32, "i64.extend_si32" },
- { Instructions::i64_extend_ui32, "i64.extend_ui32" },
- { Instructions::i64_trunc_sf32, "i64.trunc_sf32" },
- { Instructions::i64_trunc_uf32, "i64.trunc_uf32" },
- { Instructions::i64_trunc_sf64, "i64.trunc_sf64" },
- { Instructions::i64_trunc_uf64, "i64.trunc_uf64" },
- { Instructions::f32_convert_si32, "f32.convert_si32" },
- { Instructions::f32_convert_ui32, "f32.convert_ui32" },
- { Instructions::f32_convert_si64, "f32.convert_si64" },
- { Instructions::f32_convert_ui64, "f32.convert_ui64" },
- { Instructions::f32_demote_f64, "f32.demote_f64" },
- { Instructions::f64_convert_si32, "f64.convert_si32" },
- { Instructions::f64_convert_ui32, "f64.convert_ui32" },
- { Instructions::f64_convert_si64, "f64.convert_si64" },
- { Instructions::f64_convert_ui64, "f64.convert_ui64" },
- { Instructions::f64_promote_f32, "f64.promote_f32" },
- { Instructions::i32_reinterpret_f32, "i32.reinterpret_f32" },
- { Instructions::i64_reinterpret_f64, "i64.reinterpret_f64" },
- { Instructions::f32_reinterpret_i32, "f32.reinterpret_i32" },
- { Instructions::f64_reinterpret_i64, "f64.reinterpret_i64" },
- { Instructions::i32_extend8_s, "i32.extend8_s" },
- { Instructions::i32_extend16_s, "i32.extend16_s" },
- { Instructions::i64_extend8_s, "i64.extend8_s" },
- { Instructions::i64_extend16_s, "i64.extend16_s" },
- { Instructions::i64_extend32_s, "i64.extend32_s" },
- { Instructions::ref_null, "ref.null" },
- { Instructions::ref_is_null, "ref.is.null" },
- { Instructions::ref_func, "ref.func" },
- { Instructions::ref_eq, "ref.eq" },
- { Instructions::ref_as_non_null, "ref.as_non_null" },
- { Instructions::br_on_null, "br_on_null" },
- { Instructions::br_on_non_null, "br_on_non_null" },
- { Instructions::i32_trunc_sat_f32_s, "i32.trunc_sat_f32_s" },
- { Instructions::i32_trunc_sat_f32_u, "i32.trunc_sat_f32_u" },
- { Instructions::i32_trunc_sat_f64_s, "i32.trunc_sat_f64_s" },
- { Instructions::i32_trunc_sat_f64_u, "i32.trunc_sat_f64_u" },
- { Instructions::i64_trunc_sat_f32_s, "i64.trunc_sat_f32_s" },
- { Instructions::i64_trunc_sat_f32_u, "i64.trunc_sat_f32_u" },
- { Instructions::i64_trunc_sat_f64_s, "i64.trunc_sat_f64_s" },
- { Instructions::i64_trunc_sat_f64_u, "i64.trunc_sat_f64_u" },
- { Instructions::memory_init, "memory.init" },
- { Instructions::data_drop, "data.drop" },
- { Instructions::memory_copy, "memory.copy" },
- { Instructions::memory_fill, "memory.fill" },
- { Instructions::table_init, "table.init" },
- { Instructions::elem_drop, "elem.drop" },
- { Instructions::table_copy, "table.copy" },
- { Instructions::table_grow, "table.grow" },
- { Instructions::table_size, "table.size" },
- { Instructions::table_fill, "table.fill" },
- { Instructions::v128_load, "v128.load" },
- { Instructions::v128_load8x8_s, "v128.load8x8_s" },
- { Instructions::v128_load8x8_u, "v128.load8x8_u" },
- { Instructions::v128_load16x4_s, "v128.load16x4_s" },
- { Instructions::v128_load16x4_u, "v128.load16x4_u" },
- { Instructions::v128_load32x2_s, "v128.load32x2_s" },
- { Instructions::v128_load32x2_u, "v128.load32x2_u" },
- { Instructions::v128_load8_splat, "v128.load8_splat" },
- { Instructions::v128_load16_splat, "v128.load16_splat" },
- { Instructions::v128_load32_splat, "v128.load32_splat" },
- { Instructions::v128_load64_splat, "v128.load64_splat" },
- { Instructions::v128_store, "v128.store" },
- { Instructions::v128_const, "v128.const" },
- { Instructions::i8x16_shuffle, "i8x16.shuffle" },
- { Instructions::i8x16_swizzle, "i8x16.swizzle" },
- { Instructions::i8x16_splat, "i8x16.splat" },
- { Instructions::i16x8_splat, "i16x8.splat" },
- { Instructions::i32x4_splat, "i32x4.splat" },
- { Instructions::i64x2_splat, "i64x2.splat" },
- { Instructions::f32x4_splat, "f32x4.splat" },
- { Instructions::f64x2_splat, "f64x2.splat" },
- { Instructions::i8x16_extract_lane_s, "i8x16.extract_lane_s" },
- { Instructions::i8x16_extract_lane_u, "i8x16.extract_lane_u" },
- { Instructions::i8x16_replace_lane, "i8x16.replace_lane" },
- { Instructions::i16x8_extract_lane_s, "i16x8.extract_lane_s" },
- { Instructions::i16x8_extract_lane_u, "i16x8.extract_lane_u" },
- { Instructions::i16x8_replace_lane, "i16x8.replace_lane" },
- { Instructions::i32x4_extract_lane, "i32x4.extract_lane" },
- { Instructions::i32x4_replace_lane, "i32x4.replace_lane" },
- { Instructions::i64x2_extract_lane, "i64x2.extract_lane" },
- { Instructions::i64x2_replace_lane, "i64x2.replace_lane" },
- { Instructions::f32x4_extract_lane, "f32x4.extract_lane" },
- { Instructions::f32x4_replace_lane, "f32x4.replace_lane" },
- { Instructions::f64x2_extract_lane, "f64x2.extract_lane" },
- { Instructions::f64x2_replace_lane, "f64x2.replace_lane" },
- { Instructions::i8x16_eq, "i8x16.eq" },
- { Instructions::i8x16_ne, "i8x16.ne" },
- { Instructions::i8x16_lt_s, "i8x16.lt_s" },
- { Instructions::i8x16_lt_u, "i8x16.lt_u" },
- { Instructions::i8x16_gt_s, "i8x16.gt_s" },
- { Instructions::i8x16_gt_u, "i8x16.gt_u" },
- { Instructions::i8x16_le_s, "i8x16.le_s" },
- { Instructions::i8x16_le_u, "i8x16.le_u" },
- { Instructions::i8x16_ge_s, "i8x16.ge_s" },
- { Instructions::i8x16_ge_u, "i8x16.ge_u" },
- { Instructions::i16x8_eq, "i16x8.eq" },
- { Instructions::i16x8_ne, "i16x8.ne" },
- { Instructions::i16x8_lt_s, "i16x8.lt_s" },
- { Instructions::i16x8_lt_u, "i16x8.lt_u" },
- { Instructions::i16x8_gt_s, "i16x8.gt_s" },
- { Instructions::i16x8_gt_u, "i16x8.gt_u" },
- { Instructions::i16x8_le_s, "i16x8.le_s" },
- { Instructions::i16x8_le_u, "i16x8.le_u" },
- { Instructions::i16x8_ge_s, "i16x8.ge_s" },
- { Instructions::i16x8_ge_u, "i16x8.ge_u" },
- { Instructions::i32x4_eq, "i32x4.eq" },
- { Instructions::i32x4_ne, "i32x4.ne" },
- { Instructions::i32x4_lt_s, "i32x4.lt_s" },
- { Instructions::i32x4_lt_u, "i32x4.lt_u" },
- { Instructions::i32x4_gt_s, "i32x4.gt_s" },
- { Instructions::i32x4_gt_u, "i32x4.gt_u" },
- { Instructions::i32x4_le_s, "i32x4.le_s" },
- { Instructions::i32x4_le_u, "i32x4.le_u" },
- { Instructions::i32x4_ge_s, "i32x4.ge_s" },
- { Instructions::i32x4_ge_u, "i32x4.ge_u" },
- { Instructions::f32x4_eq, "f32x4.eq" },
- { Instructions::f32x4_ne, "f32x4.ne" },
- { Instructions::f32x4_lt, "f32x4.lt" },
- { Instructions::f32x4_gt, "f32x4.gt" },
- { Instructions::f32x4_le, "f32x4.le" },
- { Instructions::f32x4_ge, "f32x4.ge" },
- { Instructions::f64x2_eq, "f64x2.eq" },
- { Instructions::f64x2_ne, "f64x2.ne" },
- { Instructions::f64x2_lt, "f64x2.lt" },
- { Instructions::f64x2_gt, "f64x2.gt" },
- { Instructions::f64x2_le, "f64x2.le" },
- { Instructions::f64x2_ge, "f64x2.ge" },
- { Instructions::v128_not, "v128.not" },
- { Instructions::v128_and, "v128.and" },
- { Instructions::v128_andnot, "v128.andnot" },
- { Instructions::v128_or, "v128.or" },
- { Instructions::v128_xor, "v128.xor" },
- { Instructions::v128_bitselect, "v128.bitselect" },
- { Instructions::v128_any_true, "v128.any_true" },
- { Instructions::v128_load8_lane, "v128.load8_lane" },
- { Instructions::v128_load16_lane, "v128.load16_lane" },
- { Instructions::v128_load32_lane, "v128.load32_lane" },
- { Instructions::v128_load64_lane, "v128.load64_lane" },
- { Instructions::v128_store8_lane, "v128.store8_lane" },
- { Instructions::v128_store16_lane, "v128.store16_lane" },
- { Instructions::v128_store32_lane, "v128.store32_lane" },
- { Instructions::v128_store64_lane, "v128.store64_lane" },
- { Instructions::v128_load32_zero, "v128.load32_zero" },
- { Instructions::v128_load64_zero, "v128.load64_zero" },
- { Instructions::f32x4_demote_f64x2_zero, "f32x4.demote_f64x2_zero" },
- { Instructions::f64x2_promote_low_f32x4, "f64x2.promote_low_f32x4" },
- { Instructions::i8x16_abs, "i8x16.abs" },
- { Instructions::i8x16_neg, "i8x16.neg" },
- { Instructions::i8x16_popcnt, "i8x16.popcnt" },
- { Instructions::i8x16_all_true, "i8x16.all_true" },
- { Instructions::i8x16_bitmask, "i8x16.bitmask" },
- { Instructions::i8x16_narrow_i16x8_s, "i8x16.narrow_i16x8_s" },
- { Instructions::i8x16_narrow_i16x8_u, "i8x16.narrow_i16x8_u" },
- { Instructions::f32x4_ceil, "f32x4.ceil" },
- { Instructions::f32x4_floor, "f32x4.floor" },
- { Instructions::f32x4_trunc, "f32x4.trunc" },
- { Instructions::f32x4_nearest, "f32x4.nearest" },
- { Instructions::i8x16_shl, "i8x16.shl" },
- { Instructions::i8x16_shr_s, "i8x16.shr_s" },
- { Instructions::i8x16_shr_u, "i8x16.shr_u" },
- { Instructions::i8x16_add, "i8x16.add" },
- { Instructions::i8x16_add_sat_s, "i8x16.add_sat_s" },
- { Instructions::i8x16_add_sat_u, "i8x16.add_sat_u" },
- { Instructions::i8x16_sub, "i8x16.sub" },
- { Instructions::i8x16_sub_sat_s, "i8x16.sub_sat_s" },
- { Instructions::i8x16_sub_sat_u, "i8x16.sub_sat_u" },
- { Instructions::f64x2_ceil, "f64x2.ceil" },
- { Instructions::f64x2_floor, "f64x2.floor" },
- { Instructions::i8x16_min_s, "i8x16.min_s" },
- { Instructions::i8x16_min_u, "i8x16.min_u" },
- { Instructions::i8x16_max_s, "i8x16.max_s" },
- { Instructions::i8x16_max_u, "i8x16.max_u" },
- { Instructions::f64x2_trunc, "f64x2.trunc" },
- { Instructions::i8x16_avgr_u, "i8x16.avgr_u" },
- { Instructions::i16x8_extadd_pairwise_i8x16_s, "i16x8.extadd_pairwise_i8x16_s" },
- { Instructions::i16x8_extadd_pairwise_i8x16_u, "i16x8.extadd_pairwise_i8x16_u" },
- { Instructions::i32x4_extadd_pairwise_i16x8_s, "i32x4.extadd_pairwise_i16x8_s" },
- { Instructions::i32x4_extadd_pairwise_i16x8_u, "i32x4.extadd_pairwise_i16x8_u" },
- { Instructions::i16x8_abs, "i16x8.abs" },
- { Instructions::i16x8_neg, "i16x8.neg" },
- { Instructions::i16x8_q15mulr_sat_s, "i16x8.q15mulr_sat_s" },
- { Instructions::i16x8_all_true, "i16x8.all_true" },
- { Instructions::i16x8_bitmask, "i16x8.bitmask" },
- { Instructions::i16x8_narrow_i32x4_s, "i16x8.narrow_i32x4_s" },
- { Instructions::i16x8_narrow_i32x4_u, "i16x8.narrow_i32x4_u" },
- { Instructions::i16x8_extend_low_i8x16_s, "i16x8.extend_low_i8x16_s" },
- { Instructions::i16x8_extend_high_i8x16_s, "i16x8.extend_high_i8x16_s" },
- { Instructions::i16x8_extend_low_i8x16_u, "i16x8.extend_low_i8x16_u" },
- { Instructions::i16x8_extend_high_i8x16_u, "i16x8.extend_high_i8x16_u" },
- { Instructions::i16x8_shl, "i16x8.shl" },
- { Instructions::i16x8_shr_s, "i16x8.shr_s" },
- { Instructions::i16x8_shr_u, "i16x8.shr_u" },
- { Instructions::i16x8_add, "i16x8.add" },
- { Instructions::i16x8_add_sat_s, "i16x8.add_sat_s" },
- { Instructions::i16x8_add_sat_u, "i16x8.add_sat_u" },
- { Instructions::i16x8_sub, "i16x8.sub" },
- { Instructions::i16x8_sub_sat_s, "i16x8.sub_sat_s" },
- { Instructions::i16x8_sub_sat_u, "i16x8.sub_sat_u" },
- { Instructions::f64x2_nearest, "f64x2.nearest" },
- { Instructions::i16x8_mul, "i16x8.mul" },
- { Instructions::i16x8_min_s, "i16x8.min_s" },
- { Instructions::i16x8_min_u, "i16x8.min_u" },
- { Instructions::i16x8_max_s, "i16x8.max_s" },
- { Instructions::i16x8_max_u, "i16x8.max_u" },
- { Instructions::i16x8_avgr_u, "i16x8.avgr_u" },
- { Instructions::i16x8_extmul_low_i8x16_s, "i16x8.extmul_low_i8x16_s" },
- { Instructions::i16x8_extmul_high_i8x16_s, "i16x8.extmul_high_i8x16_s" },
- { Instructions::i16x8_extmul_low_i8x16_u, "i16x8.extmul_low_i8x16_u" },
- { Instructions::i16x8_extmul_high_i8x16_u, "i16x8.extmul_high_i8x16_u" },
- { Instructions::i32x4_abs, "i32x4.abs" },
- { Instructions::i32x4_neg, "i32x4.neg" },
- { Instructions::i32x4_all_true, "i32x4.all_true" },
- { Instructions::i32x4_bitmask, "i32x4.bitmask" },
- { Instructions::i32x4_extend_low_i16x8_s, "i32x4.extend_low_i16x8_s" },
- { Instructions::i32x4_extend_high_i16x8_s, "i32x4.extend_high_i16x8_s" },
- { Instructions::i32x4_extend_low_i16x8_u, "i32x4.extend_low_i16x8_u" },
- { Instructions::i32x4_extend_high_i16x8_u, "i32x4.extend_high_i16x8_u" },
- { Instructions::i32x4_shl, "i32x4.shl" },
- { Instructions::i32x4_shr_s, "i32x4.shr_s" },
- { Instructions::i32x4_shr_u, "i32x4.shr_u" },
- { Instructions::i32x4_add, "i32x4.add" },
- { Instructions::i32x4_sub, "i32x4.sub" },
- { Instructions::i32x4_mul, "i32x4.mul" },
- { Instructions::i32x4_min_s, "i32x4.min_s" },
- { Instructions::i32x4_min_u, "i32x4.min_u" },
- { Instructions::i32x4_max_s, "i32x4.max_s" },
- { Instructions::i32x4_max_u, "i32x4.max_u" },
- { Instructions::i32x4_dot_i16x8_s, "i32x4.dot_i16x8_s" },
- { Instructions::i32x4_extmul_low_i16x8_s, "i32x4.extmul_low_i16x8_s" },
- { Instructions::i32x4_extmul_high_i16x8_s, "i32x4.extmul_high_i16x8_s" },
- { Instructions::i32x4_extmul_low_i16x8_u, "i32x4.extmul_low_i16x8_u" },
- { Instructions::i32x4_extmul_high_i16x8_u, "i32x4.extmul_high_i16x8_u" },
- { Instructions::i64x2_abs, "i64x2.abs" },
- { Instructions::i64x2_neg, "i64x2.neg" },
- { Instructions::i64x2_all_true, "i64x2.all_true" },
- { Instructions::i64x2_bitmask, "i64x2.bitmask" },
- { Instructions::i64x2_extend_low_i32x4_s, "i64x2.extend_low_i32x4_s" },
- { Instructions::i64x2_extend_high_i32x4_s, "i64x2.extend_high_i32x4_s" },
- { Instructions::i64x2_extend_low_i32x4_u, "i64x2.extend_low_i32x4_u" },
- { Instructions::i64x2_extend_high_i32x4_u, "i64x2.extend_high_i32x4_u" },
- { Instructions::i64x2_shl, "i64x2.shl" },
- { Instructions::i64x2_shr_s, "i64x2.shr_s" },
- { Instructions::i64x2_shr_u, "i64x2.shr_u" },
- { Instructions::i64x2_add, "i64x2.add" },
- { Instructions::i64x2_sub, "i64x2.sub" },
- { Instructions::i64x2_mul, "i64x2.mul" },
- { Instructions::i64x2_eq, "i64x2.eq" },
- { Instructions::i64x2_ne, "i64x2.ne" },
- { Instructions::i64x2_lt_s, "i64x2.lt_s" },
- { Instructions::i64x2_gt_s, "i64x2.gt_s" },
- { Instructions::i64x2_le_s, "i64x2.le_s" },
- { Instructions::i64x2_ge_s, "i64x2.ge_s" },
- { Instructions::i64x2_extmul_low_i32x4_s, "i64x2.extmul_low_i32x4_s" },
- { Instructions::i64x2_extmul_high_i32x4_s, "i64x2.extmul_high_i32x4_s" },
- { Instructions::i64x2_extmul_low_i32x4_u, "i64x2.extmul_low_i32x4_u" },
- { Instructions::i64x2_extmul_high_i32x4_u, "i64x2.extmul_high_i32x4_u" },
- { Instructions::f32x4_abs, "f32x4.abs" },
- { Instructions::f32x4_neg, "f32x4.neg" },
- { Instructions::f32x4_sqrt, "f32x4.sqrt" },
- { Instructions::f32x4_add, "f32x4.add" },
- { Instructions::f32x4_sub, "f32x4.sub" },
- { Instructions::f32x4_mul, "f32x4.mul" },
- { Instructions::f32x4_div, "f32x4.div" },
- { Instructions::f32x4_min, "f32x4.min" },
- { Instructions::f32x4_max, "f32x4.max" },
- { Instructions::f32x4_pmin, "f32x4.pmin" },
- { Instructions::f32x4_pmax, "f32x4.pmax" },
- { Instructions::f64x2_abs, "f64x2.abs" },
- { Instructions::f64x2_neg, "f64x2.neg" },
- { Instructions::f64x2_sqrt, "f64x2.sqrt" },
- { Instructions::f64x2_add, "f64x2.add" },
- { Instructions::f64x2_sub, "f64x2.sub" },
- { Instructions::f64x2_mul, "f64x2.mul" },
- { Instructions::f64x2_div, "f64x2.div" },
- { Instructions::f64x2_min, "f64x2.min" },
- { Instructions::f64x2_max, "f64x2.max" },
- { Instructions::f64x2_pmin, "f64x2.pmin" },
- { Instructions::f64x2_pmax, "f64x2.pmax" },
- { Instructions::i32x4_trunc_sat_f32x4_s, "i32x4.trunc_sat_f32x4_s" },
- { Instructions::i32x4_trunc_sat_f32x4_u, "i32x4.trunc_sat_f32x4_u" },
- { Instructions::f32x4_convert_i32x4_s, "f32x4.convert_i32x4_s" },
- { Instructions::f32x4_convert_i32x4_u, "f32x4.convert_i32x4_u" },
- { Instructions::i32x4_trunc_sat_f64x2_s_zero, "i32x4.trunc_sat_f64x2_s_zero" },
- { Instructions::i32x4_trunc_sat_f64x2_u_zero, "i32x4.trunc_sat_f64x2_u_zero" },
- { Instructions::f64x2_convert_low_i32x4_s, "f64x2.convert_low_i32x4_s" },
- { Instructions::f64x2_convert_low_i32x4_u, "f64x2.convert_low_i32x4_u" },
- { Instructions::i8x16_relaxed_swizzle, "i8x16.relaxed_swizzle" },
- { Instructions::i32x4_relaxed_trunc_f32x4_s, "i32x4.relaxed_trunc_f32x4_s" },
- { Instructions::i32x4_relaxed_trunc_f32x4_u, "i32x4.relaxed_trunc_f32x4_u" },
- { Instructions::i32x4_relaxed_trunc_f64x2_s_zero, "i32x4.relaxed_trunc_f64x2_s_zero" },
- { Instructions::i32x4_relaxed_trunc_f64x2_u_zero, "i32x4.relaxed_trunc_f64x2_u_zero" },
- { Instructions::f32x4_relaxed_madd, "f32x4.relaxed_madd" },
- { Instructions::f32x4_relaxed_nmadd, "f32x4.relaxed_nmadd" },
- { Instructions::f64x2_relaxed_madd, "f64x2.relaxed_madd" },
- { Instructions::f64x2_relaxed_nmadd, "f64x2.relaxed_nmadd" },
- { Instructions::i8x16_relaxed_laneselect, "i8x16.relaxed_laneselect" },
- { Instructions::i16x8_relaxed_laneselect, "i16x8.relaxed_laneselect" },
- { Instructions::i32x4_relaxed_laneselect, "i32x4.relaxed_laneselect" },
- { Instructions::i64x2_relaxed_laneselect, "i64x2.relaxed_laneselect" },
- { Instructions::f32x4_relaxed_min, "f32x4.relaxed_min" },
- { Instructions::f32x4_relaxed_max, "f32x4.relaxed_max" },
- { Instructions::f64x2_relaxed_min, "f64x2.relaxed_min" },
- { Instructions::f64x2_relaxed_max, "f64x2.relaxed_max" },
- { Instructions::i16x8_relaxed_q15mulr_s, "i16x8.relaxed_q15mulr_s" },
- { Instructions::i16x8_relaxed_dot_i8x16_i7x16_s, "i16x8.relaxed_dot_i8x16_i7x16_s" },
- { Instructions::i32x4_relaxed_dot_i8x16_i7x16_add_s, "i32x4.relaxed_dot_i8x16_i7x16_add_s" },
- { Instructions::struct_new, "struct.new" },
- { Instructions::struct_new_default, "struct.new_default" },
- { Instructions::struct_get, "struct.get" },
- { Instructions::struct_get_s, "struct.get_s" },
- { Instructions::struct_get_u, "struct.get_u" },
- { Instructions::struct_set, "struct.set" },
- { Instructions::array_new, "array.new" },
- { Instructions::array_new_default, "array.new_default" },
- { Instructions::array_new_fixed, "array.new_fixed" },
- { Instructions::array_new_data, "array.new_data" },
- { Instructions::array_new_elem, "array.new_elem" },
- { Instructions::array_get, "array.get" },
- { Instructions::array_get_s, "array.get_s" },
- { Instructions::array_get_u, "array.get_u" },
- { Instructions::array_set, "array.set" },
- { Instructions::array_len, "array.len" },
- { Instructions::array_fill, "array.fill" },
- { Instructions::array_copy, "array.copy" },
- { Instructions::array_init_data, "array.init_data" },
- { Instructions::array_init_elem, "array.init_elem" },
- { Instructions::ref_test, "ref.test" },
- { Instructions::ref_test_null, "ref.test null" },
- { Instructions::ref_cast, "ref.cast" },
- { Instructions::ref_cast_null, "ref.cast null" },
- { Instructions::br_on_cast, "br_on_cast" },
- { Instructions::br_on_cast_fail, "br_on_cast_fail" },
- { Instructions::any_convert_extern, "any.convert_extern" },
- { Instructions::extern_convert_any, "extern.convert_any" },
- { Instructions::ref_i31, "ref.i31" },
- { Instructions::i31_get_s, "i31.get_s" },
- { Instructions::i31_get_u, "i31.get_u" },
- { Instructions::structured_else, "synthetic:else" },
- { Instructions::structured_end, "synthetic:end" },
- { Instructions::synthetic_i32_add2local, "synthetic:i32.add2local" },
- { Instructions::synthetic_i32_addconstlocal, "synthetic:i32.add_const_local" },
- { Instructions::synthetic_i32_andconstlocal, "synthetic:i32.and_const_local" },
- { Instructions::synthetic_i32_storelocal, "synthetic:i32.store_local" },
- { Instructions::synthetic_i64_storelocal, "synthetic:i64.store_local" },
- { Instructions::synthetic_local_seti32_const, "synthetic:local.set_i32_const" },
- { Instructions::synthetic_call_00, "synthetic:call.00" },
- { Instructions::synthetic_call_01, "synthetic:call.01" },
- { Instructions::synthetic_call_10, "synthetic:call.10" },
- { Instructions::synthetic_call_11, "synthetic:call.11" },
- { Instructions::synthetic_call_20, "synthetic:call.20" },
- { Instructions::synthetic_call_21, "synthetic:call.21" },
- { Instructions::synthetic_call_30, "synthetic:call.30" },
- { Instructions::synthetic_call_31, "synthetic:call.31" },
- { Instructions::synthetic_end_expression, "synthetic:expression.end" },
- { Instructions::synthetic_call_with_record_0, "synthetic:call.with_record.0" },
- { Instructions::synthetic_call_with_record_1, "synthetic:call.with_record.1" },
- { Instructions::synthetic_local_get_0, "synthetic:local.get.0" },
- { Instructions::synthetic_local_get_1, "synthetic:local.get.1" },
- { Instructions::synthetic_local_get_2, "synthetic:local.get.2" },
- { Instructions::synthetic_local_get_3, "synthetic:local.get.3" },
- { Instructions::synthetic_local_get_4, "synthetic:local.get.4" },
- { Instructions::synthetic_local_get_5, "synthetic:local.get.5" },
- { Instructions::synthetic_local_get_6, "synthetic:local.get.6" },
- { Instructions::synthetic_local_get_7, "synthetic:local.get.7" },
- { Instructions::synthetic_br_nostack, "synthetic:br.nostack" },
- { Instructions::synthetic_br_if_nostack, "synthetic:br.if.nostack" },
- { Instructions::synthetic_local_set_0, "synthetic:local.set.0" },
- { Instructions::synthetic_local_set_1, "synthetic:local.set.1" },
- { Instructions::synthetic_local_set_2, "synthetic:local.set.2" },
- { Instructions::synthetic_local_set_3, "synthetic:local.set.3" },
- { Instructions::synthetic_local_set_4, "synthetic:local.set.4" },
- { Instructions::synthetic_local_set_5, "synthetic:local.set.5" },
- { Instructions::synthetic_local_set_6, "synthetic:local.set.6" },
- { Instructions::synthetic_local_set_7, "synthetic:local.set.7" },
- { Instructions::synthetic_local_copy, "synthetic:local.copy" },
- { Instructions::synthetic_i32_sub2local, "synthetic:i32.sub2local" },
- { Instructions::synthetic_i32_mul2local, "synthetic:i32.mul2local" },
- { Instructions::synthetic_i32_and2local, "synthetic:i32.and2local" },
- { Instructions::synthetic_i32_or2local, "synthetic:i32.or2local" },
- { Instructions::synthetic_i32_xor2local, "synthetic:i32.xor2local" },
- { Instructions::synthetic_i32_shl2local, "synthetic:i32.shl2local" },
- { Instructions::synthetic_i32_shru2local, "synthetic:i32.shru2local" },
- { Instructions::synthetic_i32_shrs2local, "synthetic:i32.shrs2local" },
- { Instructions::synthetic_i64_add2local, "synthetic:i64.add2local" },
- { Instructions::synthetic_i64_addconstlocal, "synthetic:i64.addconstlocal" },
- { Instructions::synthetic_i64_andconstlocal, "synthetic:i64.andconstlocal" },
- { Instructions::synthetic_i64_storelocal, "synthetic:i64.storelocal" },
- { Instructions::synthetic_i64_sub2local, "synthetic:i64.sub2local" },
- { Instructions::synthetic_i64_mul2local, "synthetic:i64.mul2local" },
- { Instructions::synthetic_i64_and2local, "synthetic:i64.and2local" },
- { Instructions::synthetic_i64_or2local, "synthetic:i64.or2local" },
- { Instructions::synthetic_i64_xor2local, "synthetic:i64.xor2local" },
- { Instructions::synthetic_i64_shl2local, "synthetic:i64.shl2local" },
- { Instructions::synthetic_i64_shru2local, "synthetic:i64.shru2local" },
- { Instructions::synthetic_i64_shrs2local, "synthetic:i64.shrs2local" },
- { Instructions::synthetic_local_seti64_const, "synthetic:local.seti64_const" },
- { Instructions::atomic_load, "atomic.load" },
- { Instructions::atomic_store, "atomic.store" },
- { Instructions::atomic_rmw, "atomic.rmw" },
- { Instructions::atomic_rmw_cmpxchg, "atomic.rmw.cmpxchg" },
- { Instructions::memory_atomic_notify, "memory.atomic.notify" },
- { Instructions::memory_atomic_wait32, "memory.atomic.wait32" },
- { Instructions::memory_atomic_wait64, "memory.atomic.wait64" },
- { Instructions::atomic_fence, "atomic.fence" },
-};
-HashMap<ByteString, Wasm::OpCode>& Wasm::Names::instructions_by_name = *new HashMap<ByteString, Wasm::OpCode>;
diff --git a/Libraries/LibWasm/Printer/Printer.h b/Libraries/LibWasm/Printer/Printer.h
deleted file mode 100644
index 4b808bd503d..00000000000
--- a/Libraries/LibWasm/Printer/Printer.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWasm/Export.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-class Reference;
-class Value;
-
-ByteString instruction_name(OpCode const& opcode);
-Optional<OpCode> instruction_from_name(StringView name);
-
-struct WASM_API Printer {
- AK_ALLOC_WITH_KMALLOC;
-
- explicit Printer(Stream& stream, size_t initial_indent = 0)
- : m_stream(stream)
- , m_indent(initial_indent)
- {
- }
-
- void print(Wasm::BlockType const&);
- void print(Wasm::CodeSection const&);
- void print(Wasm::CodeSection::Code const&);
- void print(Wasm::CodeSection::Func const&);
- void print(Wasm::CustomSection const&);
- void print(Wasm::DataCountSection const&);
- void print(Wasm::DataSection const&);
- void print(Wasm::DataSection::Data const&);
- void print(Wasm::ElementSection const&);
- void print(Wasm::ElementSection::Element const&);
- void print(Wasm::ExportSection const&);
- void print(Wasm::ExportSection::Export const&);
- void print(Wasm::Expression const&);
- void print(Wasm::FunctionSection const&);
- void print(Wasm::FunctionType const&);
- void print(Wasm::GlobalSection const&);
- void print(Wasm::GlobalSection::Global const&);
- void print(Wasm::GlobalType const&);
- void print(Wasm::ImportSection const&);
- void print(Wasm::ImportSection::Import const&);
- void print(Wasm::TagSection const&);
- void print(Wasm::Instruction const&);
- void print(Wasm::Limits const&);
- void print(Wasm::Locals const&);
- void print(Wasm::MemorySection const&);
- void print(Wasm::MemorySection::Memory const&);
- void print(Wasm::MemoryType const&);
- void print(Wasm::Module const&);
- void print(Wasm::Reference const&);
- void print(Wasm::StartSection const&);
- void print(Wasm::StartSection::StartFunction const&);
- void print(Wasm::TableSection const&);
- void print(Wasm::TableSection::Table const&);
- void print(Wasm::TableType const&);
- void print(Wasm::TypeSection const&);
- void print(Wasm::TypeSection::Type const&);
- void print(Wasm::StructType const&);
- void print(Wasm::ArrayType const&);
- void print(Wasm::FieldType const&);
- void print(Wasm::ValueType const&);
- void print(Wasm::TagType const&);
- void print(Wasm::Value const&);
- void print(Wasm::Value const&, ValueType const&);
- void print(Wasm::Catch const&);
- void print(Wasm::TypeIndex const&);
-
-private:
- void print_indent();
- template<typename... Args>
- void print(CheckedFormatString<Args...> fmt, Args&&... args)
- {
- StringBuilder builder;
- builder.appendff(fmt.view(), forward<Args>(args)...);
- m_stream.write_until_depleted(builder.string_view().bytes()).release_value_but_fixme_should_propagate_errors();
- }
-
- Stream& m_stream;
- size_t m_indent { 0 };
-};
-
-}
diff --git a/Libraries/LibWasm/Runtime/Runtime.cpp b/Libraries/LibWasm/Runtime.cpp
similarity index 99%
rename from Libraries/LibWasm/Runtime/Runtime.cpp
rename to Libraries/LibWasm/Runtime.cpp
index 54e924c434f..8728010793a 100644
--- a/Libraries/LibWasm/Runtime/Runtime.cpp
+++ b/Libraries/LibWasm/Runtime.cpp
@@ -6,7 +6,7 @@
#include <LibGC/CAPI.h>
#include <LibGC/Heap.h>
-#include <LibWasm/Runtime/Runtime.h>
+#include <LibWasm/Runtime.h>
#include <RustFFI.h>
namespace Wasm::Runtime {
diff --git a/Libraries/LibWasm/Runtime/Runtime.h b/Libraries/LibWasm/Runtime.h
similarity index 98%
rename from Libraries/LibWasm/Runtime/Runtime.h
rename to Libraries/LibWasm/Runtime.h
index 306ee59ba2f..e9cb6df5f3d 100644
--- a/Libraries/LibWasm/Runtime/Runtime.h
+++ b/Libraries/LibWasm/Runtime.h
@@ -19,7 +19,7 @@
#include <LibGC/ConservativeVector.h>
#include <LibGC/Forward.h>
#include <LibGC/PrimitiveStorage.h>
-#include <LibWasm/Runtime/Export.h>
+#include <LibWasm/Export.h>
namespace Wasm::FFI {
@@ -168,7 +168,7 @@ struct CustomSection {
using Values = GC::ConservativeVector<Value, 8>;
// A compiled module, which can be shared across threads and instantiated in any store.
-class WASMRUNTIME_API Module : public AtomicRefCounted<Module> {
+class WASM_API Module : public AtomicRefCounted<Module> {
public:
static ErrorOr<NonnullRefPtr<Module>, ByteString> compile(ReadonlyBytes);
~Module();
@@ -226,7 +226,7 @@ struct HostError {
// What the entities of one thread share: their heap, types, and the interpreter's state. One store serves a whole
// agent.
-class WASMRUNTIME_API Store {
+class WASM_API Store {
AK_MAKE_NONCOPYABLE(Store);
AK_MAKE_NONMOVABLE(Store);
AK_ALLOC_WITH_KMALLOC;
@@ -295,7 +295,7 @@ private:
};
// The state of a WASI (wasi_snapshot_preview1) command. Its functions only work on Unix hosts.
-class WASMRUNTIME_API Wasi {
+class WASM_API Wasi {
AK_MAKE_NONCOPYABLE(Wasi);
AK_MAKE_NONMOVABLE(Wasi);
AK_ALLOC_WITH_KMALLOC;
diff --git a/Libraries/LibWasm/Runtime/CMakeLists.txt b/Libraries/LibWasm/Runtime/CMakeLists.txt
deleted file mode 100644
index 35f9d8c36be..00000000000
--- a/Libraries/LibWasm/Runtime/CMakeLists.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-set(SOURCES
- Runtime.cpp
-)
-
-ladybird_lib(LibWasmRuntime wasmruntime EXPLICIT_SYMBOL_EXPORT)
-
-import_rust_crate(MANIFEST_PATH ../Engine/Cargo.toml CRATE_NAME libwasm_engine FEATURES allocator FFI_HEADER RustFFI.h)
-target_link_libraries(LibWasmRuntime PRIVATE libwasm_engine PUBLIC LibGC)
-if ((LINUX OR BSD) AND NOT BUILD_SHARED_LIBS)
- target_link_options(LibWasmRuntime INTERFACE LINKER:--allow-multiple-definition)
-endif()
diff --git a/Libraries/LibWasm/Rust/Cargo.toml b/Libraries/LibWasm/Rust/Cargo.toml
deleted file mode 100644
index 27fe64f99a8..00000000000
--- a/Libraries/LibWasm/Rust/Cargo.toml
+++ /dev/null
@@ -1,23 +0,0 @@
-[package]
-name = "libwasm_cranelift"
-version = "0.1.0"
-edition = "2024"
-
-[lib]
-crate-type = ["rlib"]
-
-[dependencies]
-ak = { path = "../../../AK/Rust" }
-cranelift-codegen = "0.136"
-cranelift-frontend = "0.136"
-cranelift-module = "0.136"
-cranelift-native = "0.136"
-target-lexicon = "0.13"
-libc = "0.2"
-
-[build-dependencies]
-cbindgen = "0.29"
-regex = "1"
-
-[lints]
-workspace = true
diff --git a/Libraries/LibWasm/Rust/build.rs b/Libraries/LibWasm/Rust/build.rs
deleted file mode 100644
index 75fa22347c0..00000000000
--- a/Libraries/LibWasm/Rust/build.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use std::env;
-use std::error::Error;
-use std::fmt::Write;
-use std::path::Path;
-use std::path::PathBuf;
-
-fn generate_opcodes(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
- let opcode_h = manifest_dir.join("../Opcode.h");
- println!("cargo:rerun-if-changed={}", opcode_h.display());
-
- let contents = std::fs::read_to_string(&opcode_h)?;
- let mut output = String::new();
-
- // Grab name and value from _M(name, value, pops, pushes)_ lines
- let re = regex::Regex::new(r"M\(\s*(\w+)\s*,\s*(0x[0-9a-fA-F]+)(?:[uUlL]+)?\s*,")?;
- for cap in re.captures_iter(&contents) {
- let cpp_name = &cap[1];
- let value = &cap[2];
-
- // Drop "structured_" and trailing underscrores, then uppercase the whole thing.
- let mut name = cpp_name.to_string();
- if let Some(stripped) = name.strip_prefix("structured_") {
- name = stripped.to_string();
- }
- if let Some(stripped) = name.strip_suffix('_') {
- name = stripped.to_string();
- }
- let name = name.to_uppercase();
-
- writeln!(output, "pub const {name}: u64 = {value};")?;
- }
-
- std::fs::write(out_dir.join("opcodes.rs"), output)?;
- Ok(())
-}
-
-fn main() -> Result<(), Box<dyn Error>> {
- let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
- let out_dir = PathBuf::from(env::var("OUT_DIR")?);
-
- println!("cargo:rerun-if-changed=build.rs");
- println!("cargo:rerun-if-changed=cbindgen.toml");
- println!("cargo:rerun-if-changed=src/lib.rs");
- println!("cargo:rerun-if-changed=src/serialized.rs");
-
- generate_opcodes(&manifest_dir, &out_dir)?;
-
- let ffi_out_dir = env::var("FFI_OUTPUT_DIR")
- .map(PathBuf::from)
- .unwrap_or_else(|_| out_dir.clone());
-
- cbindgen::generate(manifest_dir).map_or_else(
- |error| match error {
- cbindgen::Error::ParseSyntaxError { .. } => {}
- e => panic!("{e:?}"),
- },
- |bindings| {
- bindings.write_to_file(ffi_out_dir.join("CraneliftFFI.h"));
- },
- );
-
- Ok(())
-}
diff --git a/Libraries/LibWasm/Rust/cbindgen.toml b/Libraries/LibWasm/Rust/cbindgen.toml
deleted file mode 100644
index b3d94ffddee..00000000000
--- a/Libraries/LibWasm/Rust/cbindgen.toml
+++ /dev/null
@@ -1,20 +0,0 @@
-language = "C++"
-header = """/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */"""
-pragma_once = true
-include_version = true
-namespaces = ["Wasm", "Cranelift"]
-line_length = 120
-tab_width = 4
-no_includes = true
-sys_includes = ["stdint.h", "stddef.h"]
-usize_is_size_t = true
-
-[export]
-include = ["CraneliftInsn", "RuntimeLayout", "HelperReloc", "HelperId", "HELPER_COUNT", "SERIALIZED_CODE_ALIGNMENT"]
-
-[export.mangle]
-rename_types = "PascalCase"
diff --git a/Libraries/LibWasm/Rust/src/bin/cranelift-compiler.rs b/Libraries/LibWasm/Rust/src/bin/cranelift-compiler.rs
deleted file mode 100644
index 57996d302e9..00000000000
--- a/Libraries/LibWasm/Rust/src/bin/cranelift-compiler.rs
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (c) 2026-present, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#![allow(clippy::manual_let_else)]
-
-use libwasm_cranelift::serialized::compile_serialized_buffer;
-use std::env;
-
-// macOS POSIX shm objects don't support read/write/pread/pwrite, only mmap and
-// ftruncate. Mmap both buffers on all Unix platforms so Linux does not need to
-// copy them through temporary Vecs.
-#[cfg(unix)]
-mod unix {
- use std::ffi::c_void;
- use std::io;
-
- pub struct Mapping {
- ptr: *mut u8,
- len: usize,
- fd: i32,
- }
-
- impl Mapping {
- pub fn open(fd: i32, len: usize, writable: bool) -> Result<Self, Box<dyn std::error::Error>> {
- if fd < 0 {
- return Err("invalid fd".into());
- }
- let protection = if writable {
- libc::PROT_READ | libc::PROT_WRITE
- } else {
- libc::PROT_READ
- };
- let ptr = unsafe { libc::mmap(std::ptr::null_mut(), len, protection, libc::MAP_SHARED, fd, 0) };
- if ptr == libc::MAP_FAILED {
- return Err(io::Error::last_os_error().into());
- }
- Ok(Mapping {
- ptr: ptr.cast::<u8>(),
- len,
- fd,
- })
- }
-
- pub fn as_slice(&self) -> &[u8] {
- unsafe { ak::slice_from_raw_parts(self.ptr, self.len) }
- }
-
- pub fn as_slice_mut(&mut self) -> &mut [u8] {
- unsafe { ak::slice_from_raw_parts_mut(self.ptr, self.len) }
- }
- }
-
- impl Drop for Mapping {
- fn drop(&mut self) {
- unsafe {
- libc::munmap(self.ptr.cast::<c_void>(), self.len);
- libc::close(self.fd);
- }
- }
- }
-}
-
-#[cfg(windows)]
-mod win {
- use std::ffi::c_void;
- use std::io;
-
- const FILE_MAP_READ: u32 = 0x0004;
- const FILE_MAP_ALL_ACCESS: u32 = 0xf001f;
-
- #[link(name = "kernel32")]
- unsafe extern "system" {
- // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile
- fn MapViewOfFile(
- hFileMappingObject: *mut c_void, // HANDLE
- dwDesiredAccess: u32, // DWORD
- dwFileOffsetHigh: u32, // DWORD
- dwFileOffsetLow: u32, // DWORD
- dwNumberOfBytesToMap: usize, // size_t
- ) -> *mut c_void; // LPVOID
-
- // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-unmapviewoffile
- fn UnmapViewOfFile(lpBaseAddress: *const c_void, // LPCVOID
- ) -> i32; // BOOL
- }
-
- pub struct Mapping {
- ptr: *mut u8,
- len: usize,
- }
-
- impl Mapping {
- pub fn open(arg: &str, len: usize, writable: bool) -> Result<Self, Box<dyn std::error::Error>> {
- let handle_val = arg.parse::<usize>()?;
- let handle = handle_val as *mut c_void;
- let desired_access = if writable { FILE_MAP_ALL_ACCESS } else { FILE_MAP_READ };
- let ptr = unsafe { MapViewOfFile(handle, desired_access, 0, 0, len) };
- if ptr.is_null() {
- return Err(io::Error::last_os_error().into());
- }
- Ok(Mapping {
- ptr: ptr.cast::<u8>(),
- len,
- })
- }
-
- pub fn as_slice(&self) -> &[u8] {
- unsafe { ak::slice_from_raw_parts(self.ptr, self.len) }
- }
-
- pub fn as_slice_mut(&mut self) -> &mut [u8] {
- unsafe { ak::slice_from_raw_parts_mut(self.ptr, self.len) }
- }
- }
-
- impl Drop for Mapping {
- fn drop(&mut self) {
- unsafe {
- UnmapViewOfFile(self.ptr.cast());
- }
- }
- }
-}
-
-fn main() -> Result<(), Box<dyn std::error::Error>> {
- let mut arguments = env::args().skip(1);
- let input_handle = arguments
- .next()
- .ok_or("Usage: cranelift-compiler <input-handle> <input-size> <output-handle> <output-size>")?;
- let input_size = arguments.next().ok_or("missing input size")?.parse::<usize>()?;
- let output_handle = arguments.next().ok_or("missing output handle")?;
- let output_size = arguments.next().ok_or("missing output size")?.parse::<usize>()?;
-
- #[cfg(unix)]
- let input = unix::Mapping::open(input_handle.parse::<i32>()?, input_size, false)?;
- #[cfg(windows)]
- let input = win::Mapping::open(&input_handle, input_size, false)?;
-
- #[cfg(unix)]
- let mut output = unix::Mapping::open(output_handle.parse::<i32>()?, output_size, true)?;
- #[cfg(windows)]
- let mut output = win::Mapping::open(&output_handle, output_size, true)?;
-
- compile_serialized_buffer(input.as_slice(), output.as_slice_mut())?;
-
- Ok(())
-}
diff --git a/Libraries/LibWasm/Rust/src/compiler.rs b/Libraries/LibWasm/Rust/src/compiler.rs
deleted file mode 100644
index aa5dcd510a2..00000000000
--- a/Libraries/LibWasm/Rust/src/compiler.rs
+++ /dev/null
@@ -1,2608 +0,0 @@
-/*
- * Copyright (c) 2026-present, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use crate::CompiledFunction;
-use crate::CraneliftInsn;
-use crate::CraneliftTrap;
-use crate::HelperId;
-use crate::HelperReloc;
-use crate::RuntimeLayout;
-
-use cranelift_codegen::Context;
-use cranelift_codegen::FinalizedRelocTarget;
-use cranelift_codegen::binemit::Reloc;
-use cranelift_codegen::ir::AbiParam;
-use cranelift_codegen::ir::Block;
-use cranelift_codegen::ir::ExtFuncData;
-use cranelift_codegen::ir::ExternalName;
-use cranelift_codegen::ir::Function;
-use cranelift_codegen::ir::InstBuilder;
-use cranelift_codegen::ir::MemFlagsData;
-use cranelift_codegen::ir::Signature;
-use cranelift_codegen::ir::StackSlotData;
-use cranelift_codegen::ir::StackSlotKind;
-use cranelift_codegen::ir::UserExternalName;
-use cranelift_codegen::ir::UserFuncName;
-use cranelift_codegen::ir::condcodes::FloatCC;
-use cranelift_codegen::ir::condcodes::IntCC;
-use cranelift_codegen::ir::immediates::Ieee32;
-use cranelift_codegen::ir::immediates::Ieee64;
-use cranelift_codegen::ir::types;
-use cranelift_codegen::settings::Configurable;
-use cranelift_codegen::settings::{self};
-use cranelift_codegen::{self};
-use cranelift_frontend::FunctionBuilder;
-use cranelift_frontend::FunctionBuilderContext;
-use cranelift_frontend::Variable;
-use cranelift_native;
-
-// Opcode constants generated from Opcode.h (see build.rs.)
-#[allow(dead_code)]
-mod op {
- include!(concat!(env!("OUT_DIR"), "/opcodes.rs"));
-}
-
-const REG_COUNT: usize = 8;
-const STACK_MARKER: u8 = 8;
-const CALLREC_BASE: u8 = 9;
-
-/// The `Int` bank is always defined.
-/// The `F64` bank is trusted only until the next control-flow merge, where it may be undefined on an incoming edge.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum Bank {
- Int,
- F32,
- F64,
-}
-
-/// Control flow frame tracking for structured control flow.
-struct ControlFrame {
- kind: ControlKind,
- /// The cranelift block to branch to (for `br` targeting this frame).
- /// For blocks: the merge/after block.
- /// For loops: the loop header block.
- branch_target: cranelift_codegen::ir::Block,
- /// Where execution continues after this construct ends.
- after_block: cranelift_codegen::ir::Block,
- /// Number of result values.
- arity: u32,
- /// Number of parameters consumed from outer stack.
- param_count: usize,
- /// Stack depth at block entry, tracked for br*.
- stack_depth_at_entry: i32,
- /// Real value-stack size at block entry, minus this block's param count.
- /// Only meaningful (and only set) when vstack is disabled (max_stack_depth == 0).
- entry_real_depth_var: Option<Variable>,
- bank_snapshot: Option<([Bank; REG_COUNT], Vec<Bank>)>,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ControlKind {
- Block,
- Loop,
- If,
-}
-
-pub struct CraneliftCompiler;
-
-impl CraneliftCompiler {
- pub fn compile_to_bytes(
- insns: &[CraneliftInsn],
- layout: &RuntimeLayout,
- outcome_return_value: u64,
- result_arity: u32,
- num_locals: u32,
- num_params: u32,
- local_types: &[u8],
- ) -> Result<CompiledFunction, &'static str> {
- for insn in insns {
- if !Self::is_supported(insn) {
- return Err("unsupported instruction");
- }
- if matches!(insn.opcode, op::BLOCK | op::LOOP | op::IF) {
- let arity = insn.imm3 & 0xffff;
- if arity > 1 {
- return Err("multi-value blocks not supported");
- }
- }
- // Note: op::CALL is used for multi-value returns but also for some
- // single-return calls. We handle it via flush_vstack_to_real before the call.
- }
-
- let mut flag_builder = settings::builder();
- flag_builder.set("opt_level", "speed").unwrap();
- flag_builder.set("is_pic", "false").unwrap();
- let flags = settings::Flags::new(flag_builder);
- let isa = cranelift_native::builder()
- .map_err(|_| "unsupported host architecture")?
- .finish(flags)
- .map_err(|_| "failed to build ISA")?;
-
- // Function signature matches handler_ptr:
- // u64 fn(void* interpreter, void* configuration, void* insn, u32 short_ip, void* cc, void* addrs)
- let ptr_type = isa.pointer_type();
- let host_cc = isa.default_call_conv();
- let mut sig = Signature::new(host_cc);
- sig.params.push(AbiParam::new(ptr_type)); // interpreter
- sig.params.push(AbiParam::new(ptr_type)); // configuration
- sig.params.push(AbiParam::new(ptr_type)); // instruction (unused)
- sig.params.push(AbiParam::new(types::I32)); // short_ip (unused)
- sig.params.push(AbiParam::new(ptr_type)); // cc (unused)
- sig.params.push(AbiParam::new(ptr_type)); // addresses_ptr (unused)
- sig.returns.push(AbiParam::new(types::I64)); // Outcome
-
- let mut func = Function::with_name_signature(UserFuncName::user(0, 0), sig);
- let mut builder_ctx = FunctionBuilderContext::new();
- let mut builder = FunctionBuilder::new(&mut func, &mut builder_ctx);
-
- // Declare variables for virtual registers R0-R7.
- // We store everything as i64 and bitcast for floats.
- let reg_vars: [Variable; REG_COUNT] = std::array::from_fn(|_| builder.declare_var(types::I64));
-
- let entry_block = builder.create_block();
- builder.append_block_params_for_function_params(entry_block);
- builder.switch_to_block(entry_block);
- builder.seal_block(entry_block);
-
- let interpreter_val = builder.block_params(entry_block)[0];
- let configuration_val = builder.block_params(entry_block)[1];
-
- // Load regs[0..7] from configuration. regs is at offset `regs_offset` from Configuration*.
- // Each Value is `value_size` bytes; the low 8 bytes are the i64 payload.
- let regs_offset = layout.regs_offset as i32;
- let value_size = layout.value_size as i32;
- for (i, var) in reg_vars.iter().enumerate() {
- let offset = regs_offset + (i as i32) * value_size;
- let val = builder
- .ins()
- .load(types::I64, MemFlagsData::trusted(), configuration_val, offset);
- builder.def_var(*var, val);
- }
-
- let epilogue_block = builder.create_block();
- let trap_block = builder.create_block();
-
- // Build helper call signatures. We import them as indirect calls via function pointers.
- macro_rules! sig {
- (@ty ptr) => { ptr_type };
- (@ty i32) => { types::I32 };
- (@ty i64) => { types::I64 };
- (@def $name:ident : void fn($($param:ident),*)) => {
- let $name = {
- let mut s = Signature::new(host_cc);
- $(s.params.push(AbiParam::new(sig!(@ty $param)));)*
- builder.import_signature(s)
- };
- };
- (@def $name:ident : $ret:ident fn($($param:ident),*)) => {
- let $name = {
- let mut s = Signature::new(host_cc);
- $(s.params.push(AbiParam::new(sig!(@ty $param)));)*
- s.returns.push(AbiParam::new(sig!(@ty $ret)));
- builder.import_signature(s)
- };
- };
- ($($name:ident : $ret:ident fn($($param:ident),*);)*) => { $(sig!(@def $name : $ret fn($($param),*));)* }
- }
-
- sig! {
- call_fn_sig: i32 fn(ptr, ptr, i32);
- call_fn1_sig: i32 fn(ptr, ptr, i32, i64);
- call_fn2_sig: i32 fn(ptr, ptr, i32, i64, i64);
- call_fn3_sig: i32 fn(ptr, ptr, i32, i64, i64, i64);
- call_indirect_sig: i32 fn(ptr, ptr, i32, i32, i32);
- memory_copy_sig: i32 fn(ptr, ptr, i32, i32, i32, i32, i32);
- memory_fill_sig: i32 fn(ptr, ptr, i32, i32, i32, i32);
- cage_base_sig: i64 fn();
- mem_size_sig: i64 fn(ptr, i32);
- mem_grow_sig: i32 fn(ptr, i32, i32);
- call_wr_sig: i32 fn(ptr, ptr, i32);
- set_trap_sig: void fn(ptr, ptr, i32);
- }
-
- // Declare each runtime helper as an imported external function. At every use site
- // we emit `func_addr` which lowers (with is_pic=false) to a load from an inline
- // 8-byte literal marked with a `Reloc::Abs8` relocation -- the cache install path
- // walks these and rewrites the 8 bytes with the current process's helper address.
- macro_rules! decl_helper {
- ($sig:expr, $id:expr) => {{
- let user_ref = builder.func.declare_imported_user_function(UserExternalName {
- namespace: 0,
- index: $id as u32,
- });
- builder.func.import_function(ExtFuncData {
- name: ExternalName::user(user_ref),
- signature: $sig,
- colocated: false,
- patchable: false,
- })
- }};
- }
- let h_call_fn = decl_helper!(call_fn_sig, HelperId::call_function);
- let h_direct_call_0 = decl_helper!(call_fn_sig, HelperId::direct_call_0);
- let h_direct_call_1 = decl_helper!(call_fn1_sig, HelperId::direct_call_1);
- let h_direct_call_2 = decl_helper!(call_fn2_sig, HelperId::direct_call_2);
- let h_direct_call_3 = decl_helper!(call_fn3_sig, HelperId::direct_call_3);
- let h_set_trap = decl_helper!(set_trap_sig, HelperId::set_trap);
- let h_mem_size = decl_helper!(mem_size_sig, HelperId::memory_size);
- let h_mem_grow = decl_helper!(mem_grow_sig, HelperId::memory_grow);
- let h_call_wr = decl_helper!(call_wr_sig, HelperId::call_with_record);
- let h_call_indirect = decl_helper!(call_indirect_sig, HelperId::call_indirect);
- let h_memory_copy = decl_helper!(memory_copy_sig, HelperId::memory_copy);
- let h_memory_fill = decl_helper!(memory_fill_sig, HelperId::memory_fill);
- let h_primitive_storage_cage_base = decl_helper!(cage_base_sig, HelperId::primitive_storage_cage_base);
- let locals_base_offset = layout.locals_base_offset as i32;
- let memory_instances_offset = layout.memory_instances_offset as i32;
- let global_instances_offset = layout.global_instances_offset as i32;
- let global_instance_value_offset = layout.global_instance_value_offset as i32;
- let memory_instance_data_offset = layout.memory_instance_data_offset as i32;
- let memory_buffer_storage_offset_offset = layout.memory_buffer_storage_offset_offset as i32;
- let compiled_call_result_scratch_offset = layout.compiled_call_result_scratch_offset as i32;
- let value_stack_base_offset = layout.value_stack_base_offset as i32;
- let value_stack_top_offset = layout.value_stack_top_offset as i32;
- let call_record_base_offset = layout.call_record_base_offset as i32;
- // Accesses to memory32 are unchecked and may fault; the fault handler turns
- // faults inside a memory's guarded reservation into wasm traps.
- let wasm_memory_flags = MemFlagsData::new();
- let interp_var = builder.declare_var(ptr_type);
- builder.def_var(interp_var, interpreter_val);
- let config_var = builder.declare_var(ptr_type);
- builder.def_var(config_var, configuration_val);
- let locals_base_var = builder.declare_var(ptr_type);
- let initial_locals_base =
- builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), configuration_val, locals_base_offset);
- builder.def_var(locals_base_var, initial_locals_base);
- let is_scalar_memory_access = |opcode: u64| {
- matches!(
- opcode,
- op::I32_LOAD
- | op::I64_LOAD
- | op::F32_LOAD
- | op::F64_LOAD
- | op::I32_LOAD8_S
- | op::I32_LOAD8_U
- | op::I32_LOAD16_S
- | op::I32_LOAD16_U
- | op::I64_LOAD8_S
- | op::I64_LOAD8_U
- | op::I64_LOAD16_S
- | op::I64_LOAD16_U
- | op::I64_LOAD32_S
- | op::I64_LOAD32_U
- | op::I32_STORE
- | op::I64_STORE
- | op::F32_STORE
- | op::F64_STORE
- | op::I32_STORE8
- | op::I32_STORE16
- | op::I64_STORE8
- | op::I64_STORE16
- | op::I64_STORE32
- | op::SYNTHETIC_I32_STORELOCAL
- | op::SYNTHETIC_I64_STORELOCAL
- )
- };
- let mut used_memory_indices: Vec<u32> = insns
- .iter()
- .filter(|insn| is_scalar_memory_access(insn.opcode))
- .map(|insn| insn.imm3)
- .collect();
- used_memory_indices.sort_unstable();
- used_memory_indices.dedup();
-
- let mut memory_bases = Vec::with_capacity(used_memory_indices.len());
- if !used_memory_indices.is_empty() {
- // Each base address is stable for the whole call: memory32 storage reserves its
- // maximum (plus guard) up front, so growing commits in place and never moves it.
- let cage_base_storage = builder.ins().func_addr(ptr_type, h_primitive_storage_cage_base);
- let cage_base = builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cage_base_storage, 0);
- let memory_instances = builder.ins().load(
- ptr_type,
- MemFlagsData::trusted(),
- configuration_val,
- memory_instances_offset,
- );
- for memory_index in used_memory_indices {
- let memory_pointer_offset = builder
- .ins()
- .iconst(ptr_type, i64::from(memory_index) * i64::from(ptr_type.bytes()));
- let memory_pointer_address = builder.ins().iadd(memory_instances, memory_pointer_offset);
- let memory = builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), memory_pointer_address, 0);
- let storage_offset = builder.ins().load(
- types::I64,
- MemFlagsData::trusted(),
- memory,
- memory_instance_data_offset + memory_buffer_storage_offset_offset,
- );
- let storage_offset = if ptr_type == types::I64 {
- storage_offset
- } else {
- builder.ins().ireduce(ptr_type, storage_offset)
- };
- let memory_base = builder.ins().iadd(cage_base, storage_offset);
- memory_bases.push((memory_index, memory_base));
- }
- }
-
- let mut used_global_indices: Vec<u32> = insns
- .iter()
- .filter(|insn| matches!(insn.opcode, op::GLOBAL_GET | op::GLOBAL_SET))
- .map(|insn| insn.imm1 as u32)
- .collect();
- used_global_indices.sort_unstable();
- used_global_indices.dedup();
-
- let mut global_instances = Vec::with_capacity(used_global_indices.len());
- if !used_global_indices.is_empty() {
- let globals = builder.ins().load(
- ptr_type,
- MemFlagsData::trusted(),
- configuration_val,
- global_instances_offset,
- );
- for global_index in used_global_indices {
- let global_pointer_offset = builder
- .ins()
- .iconst(ptr_type, i64::from(global_index) * i64::from(ptr_type.bytes()));
- let global_pointer_address = builder.ins().iadd(globals, global_pointer_offset);
- let global = builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), global_pointer_address, 0);
- global_instances.push((global_index, global));
- }
- }
-
- let mut control_stack: Vec<ControlFrame> = Vec::new();
-
- // Virtual stack, to avoid touching the interpreter-side stack as much as possible.
- let has_raw_call = insns
- .iter()
- .any(|i| i.opcode == op::CALL || i.opcode == op::CALL_INDIRECT);
- let max_stack_depth = match has_raw_call {
- true => 0,
- // We can't easily track across control flow merges, so count dests instead.
- false => insns.iter().filter(|i| i.destination == STACK_MARKER).count().max(16),
- };
- let mut is_unreachable = false;
- let mut dirty_regs = [false; REG_COUNT];
- let mut stack_vars: Vec<Variable> = Vec::with_capacity(max_stack_depth);
- for _ in 0..max_stack_depth {
- let var = builder.declare_var(types::I64);
- let zero = builder.ins().iconst(types::I64, 0);
- builder.def_var(var, zero);
- stack_vars.push(var);
- }
- let mut sp: usize = 0;
-
- // If we allocate something on the stack, make sure to restore the stack at the end.
- let initial_stack_size_var = builder.declare_var(types::I64);
-
- let reg_vars_f64: [Variable; REG_COUNT] = std::array::from_fn(|_| builder.declare_var(types::F64));
- let stack_vars_f64: Vec<Variable> = (0..max_stack_depth).map(|_| builder.declare_var(types::F64)).collect();
- let reg_vars_f32: [Variable; REG_COUNT] = std::array::from_fn(|_| builder.declare_var(types::F32));
- let stack_vars_f32: Vec<Variable> = (0..max_stack_depth).map(|_| builder.declare_var(types::F32)).collect();
- let mut reg_ty = [Bank::Int; REG_COUNT];
- let mut stack_ty = vec![Bank::Int; max_stack_depth];
-
- const F32_KIND: u8 = 2;
- const F64_KIND: u8 = 3;
- let num_locals = num_locals as usize;
- let num_params = num_params as usize;
- let local_is_f64: Vec<bool> = (0..num_locals)
- .map(|i| local_types.get(i).copied() == Some(F64_KIND))
- .collect();
- let local_is_f32: Vec<bool> = (0..num_locals)
- .map(|i| local_types.get(i).copied() == Some(F32_KIND))
- .collect();
-
- // Promoting wasm locals to SSA variables keeps them in registers, which is a win only
- // as long as they actually fit. Functions with more locals than the machine has usable
- // registers make cranelift spill, and the spill traffic is both larger and slower than
- // just leaving the locals in the frame and loading them on use.
- // Set the cap according to the target's usable GPR count; the read/write macros fall back
- // to the in-memory path for any index we don't promote.
- let max_promote_locals = if cfg!(target_arch = "aarch64") {
- 24
- } else if cfg!(target_arch = "x86_64") {
- 12
- } else {
- 8
- };
- let local_vars: Vec<Variable> = if num_locals <= max_promote_locals {
- (0..num_locals)
- .map(|i| {
- let ty = if local_is_f64[i] {
- types::F64
- } else if local_is_f32[i] {
- types::F32
- } else {
- types::I64
- };
- builder.declare_var(ty)
- })
- .collect()
- } else {
- Vec::new()
- };
- let mut dirty_locals = vec![false; num_locals];
-
- // set_frame_lightweight verifies the stack-usage hint before these unchecked operations.
- macro_rules! emit_stack_push {
- ($builder:expr, $val:expr) => {{
- let v = $val;
- let cfg = $builder.use_var(config_var);
- let top = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_top_offset);
- $builder.ins().store(MemFlagsData::trusted(), v, top, 0);
- let zero_tag = $builder.ins().iconst(types::I64, 0);
- $builder.ins().store(MemFlagsData::trusted(), zero_tag, top, 8);
- let new_top = $builder.ins().iadd_imm_s(top, i64::from(value_size));
- $builder
- .ins()
- .store(MemFlagsData::trusted(), new_top, cfg, value_stack_top_offset);
- }};
- }
- macro_rules! emit_stack_pop {
- ($builder:expr) => {{
- let cfg = $builder.use_var(config_var);
- let top = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_top_offset);
- let new_top = $builder.ins().iadd_imm_s(top, -i64::from(value_size));
- $builder
- .ins()
- .store(MemFlagsData::trusted(), new_top, cfg, value_stack_top_offset);
- $builder
- .ins()
- .load(types::I64, MemFlagsData::trusted(), new_top, 0)
- }};
- }
- macro_rules! emit_stack_size {
- ($builder:expr) => {{
- let cfg = $builder.use_var(config_var);
- let top = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_top_offset);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_base_offset);
- let bytes = $builder.ins().isub(top, base);
- $builder.ins().ushr_imm_s(bytes, 4)
- }};
- }
- // Trim the real stack to `target_size + arity` values, keeping the top `arity` values
- // verbatim (helper-pushed call results carry real tags). Validation guarantees at least
- // that many values are present -- the vstack branch move relies on the same invariant.
- macro_rules! emit_stack_cleanup {
- ($builder:expr, $target_size:expr, $arity:expr) => {{
- debug_assert!(($arity as usize) <= 1);
- let cfg = $builder.use_var(config_var);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_base_offset);
- let target_bytes = $builder.ins().ishl_imm_s($target_size, 4);
- let trimmed_top = $builder.ins().iadd(base, target_bytes);
- let new_top = if $arity as usize > 0 {
- let top = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_top_offset);
- let bits = $builder
- .ins()
- .load(types::I64, MemFlagsData::trusted(), top, -value_size);
- let tag = $builder
- .ins()
- .load(types::I64, MemFlagsData::trusted(), top, -value_size + 8);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), bits, trimmed_top, 0);
- $builder.ins().store(MemFlagsData::trusted(), tag, trimmed_top, 8);
- $builder.ins().iadd_imm_s(trimmed_top, i64::from(value_size))
- } else {
- trimmed_top
- };
- $builder
- .ins()
- .store(MemFlagsData::trusted(), new_top, cfg, value_stack_top_offset);
- }};
- }
-
- if has_raw_call {
- let initial_stack_size = emit_stack_size!(builder);
- builder.def_var(initial_stack_size_var, initial_stack_size);
- } else {
- let zero = builder.ins().iconst(types::I64, 0);
- builder.def_var(initial_stack_size_var, zero);
- }
-
- // Read a value from a source location (register, virtual stack, or call record)
- macro_rules! read_src {
- ($builder:expr, $src:expr) => {{
- let src = $src;
- if src < STACK_MARKER {
- $builder.use_var(reg_vars[src as usize])
- } else if src == STACK_MARKER {
- if max_stack_depth > 0 && sp > 0 {
- // we have vstack, so just allocate on the native stack.
- sp -= 1;
- $builder.use_var(stack_vars[sp])
- } else {
- emit_stack_pop!($builder)
- }
- } else {
- // Frame entry allocated the record eagerly, so the read is a plain load.
- let cfg = $builder.use_var(config_var);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, call_record_base_offset);
- let off = i32::from(src - CALLREC_BASE) * value_size;
- $builder
- .ins()
- .load(types::I64, MemFlagsData::trusted(), base, off)
- }
- }};
- }
-
- // flush virtual stack slots 0..sp to the real value stack
- macro_rules! flush_vstack_to_real {
- ($builder:expr) => {{
- if max_stack_depth > 0 && sp > 0 {
- let cfg = $builder.use_var(config_var);
- let top = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_top_offset);
- let zero_tag = $builder.ins().iconst(types::I64, 0);
- for i in 0..sp {
- let val = $builder.use_var(stack_vars[i]);
- let offset = (i as i32) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), val, top, offset);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero_tag, top, offset + 8);
- }
- let new_top = $builder.ins().iadd_imm_s(top, i64::from(sp as i32 * value_size));
- $builder
- .ins()
- .store(MemFlagsData::trusted(), new_top, cfg, value_stack_top_offset);
- }
- sp = 0;
- }};
- }
- // push only the top n values from vstack to real stack
- macro_rules! push_top_n_to_real {
- ($builder:expr, $n:expr) => {{
- let n = $n as usize;
- if max_stack_depth > 0 && sp >= n && n > 0 {
- let cfg = $builder.use_var(config_var);
- let top = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, value_stack_top_offset);
- let zero_tag = $builder.ins().iconst(types::I64, 0);
- for i in 0..n {
- let val = $builder.use_var(stack_vars[sp - n + i]);
- let offset = (i as i32) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), val, top, offset);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero_tag, top, offset + 8);
- }
- let new_top = $builder.ins().iadd_imm_s(top, i64::from(n as i32 * value_size));
- $builder
- .ins()
- .store(MemFlagsData::trusted(), new_top, cfg, value_stack_top_offset);
- }
- }};
- }
-
- macro_rules! write_dst {
- ($builder:expr, $dst:expr, $val:expr) => {{
- let dst = $dst;
- let val = $val;
- if dst < STACK_MARKER {
- $builder.def_var(reg_vars[dst as usize], val);
- reg_ty[dst as usize] = Bank::Int;
- dirty_regs[dst as usize] = true;
- } else if dst == STACK_MARKER {
- if max_stack_depth > 0 {
- $builder.def_var(stack_vars[sp], val);
- stack_ty[sp] = Bank::Int;
- sp += 1;
- } else {
- emit_stack_push!($builder, val);
- }
- } else {
- // Frame entry allocated the record eagerly, so the write is two plain stores.
- let cfg = $builder.use_var(config_var);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, call_record_base_offset);
- let off = i32::from(dst - CALLREC_BASE) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), val, base, off);
- let zero_tag = $builder.ins().iconst(types::I64, 0);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero_tag, base, off + 8);
- }
- }};
- }
-
- macro_rules! read_src_f64 {
- ($builder:expr, $src:expr) => {{
- let src = $src;
- if src < STACK_MARKER {
- if reg_ty[src as usize] == Bank::F64 {
- $builder.use_var(reg_vars_f64[src as usize])
- } else {
- let raw = $builder.use_var(reg_vars[src as usize]);
- $builder.ins().bitcast(types::F64, MemFlagsData::new(), raw)
- }
- } else if src == STACK_MARKER {
- if max_stack_depth > 0 && sp > 0 {
- sp -= 1;
- if stack_ty[sp] == Bank::F64 {
- $builder.use_var(stack_vars_f64[sp])
- } else {
- let raw = $builder.use_var(stack_vars[sp]);
- $builder.ins().bitcast(types::F64, MemFlagsData::new(), raw)
- }
- } else {
- let raw = emit_stack_pop!($builder);
- $builder.ins().bitcast(types::F64, MemFlagsData::new(), raw)
- }
- } else {
- let cfg = $builder.use_var(config_var);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, call_record_base_offset);
- let off = i32::from(src - CALLREC_BASE) * value_size;
- $builder
- .ins()
- .load(types::F64, MemFlagsData::trusted(), base, off)
- }
- }};
- }
-
- macro_rules! write_dst_f64 {
- ($builder:expr, $dst:expr, $val:expr) => {{
- let dst = $dst;
- let val = $val;
- let bits = $builder.ins().bitcast(types::I64, MemFlagsData::new(), val);
- if dst < STACK_MARKER {
- $builder.def_var(reg_vars_f64[dst as usize], val);
- $builder.def_var(reg_vars[dst as usize], bits);
- reg_ty[dst as usize] = Bank::F64;
- dirty_regs[dst as usize] = true;
- } else if dst == STACK_MARKER {
- if max_stack_depth > 0 {
- $builder.def_var(stack_vars_f64[sp], val);
- $builder.def_var(stack_vars[sp], bits);
- stack_ty[sp] = Bank::F64;
- sp += 1;
- } else {
- emit_stack_push!($builder, bits);
- }
- } else {
- let cfg = $builder.use_var(config_var);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, call_record_base_offset);
- let off = i32::from(dst - CALLREC_BASE) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), bits, base, off);
- let zero_tag = $builder.ins().iconst(types::I64, 0);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero_tag, base, off + 8);
- }
- }};
- }
-
- macro_rules! read_src_f32 {
- ($builder:expr, $src:expr) => {{
- let src = $src;
- if src < STACK_MARKER {
- if reg_ty[src as usize] == Bank::F32 {
- $builder.use_var(reg_vars_f32[src as usize])
- } else {
- let raw = $builder.use_var(reg_vars[src as usize]);
- let raw32 = $builder.ins().ireduce(types::I32, raw);
- $builder.ins().bitcast(types::F32, MemFlagsData::new(), raw32)
- }
- } else if src == STACK_MARKER {
- if max_stack_depth > 0 && sp > 0 {
- sp -= 1;
- if stack_ty[sp] == Bank::F32 {
- $builder.use_var(stack_vars_f32[sp])
- } else {
- let raw = $builder.use_var(stack_vars[sp]);
- let raw32 = $builder.ins().ireduce(types::I32, raw);
- $builder.ins().bitcast(types::F32, MemFlagsData::new(), raw32)
- }
- } else {
- let raw = emit_stack_pop!($builder);
- let raw32 = $builder.ins().ireduce(types::I32, raw);
- $builder.ins().bitcast(types::F32, MemFlagsData::new(), raw32)
- }
- } else {
- let cfg = $builder.use_var(config_var);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, call_record_base_offset);
- let off = i32::from(src - CALLREC_BASE) * value_size;
- $builder
- .ins()
- .load(types::F32, MemFlagsData::trusted(), base, off)
- }
- }};
- }
-
- macro_rules! write_dst_f32 {
- ($builder:expr, $dst:expr, $val:expr) => {{
- let dst = $dst;
- let val = $val;
- // Keep the always-valid i64 copy in sync for bank-agnostic consumers: an f32 is 4
- // bytes, so bitcast to i32 and sign-extend into the boxed slot.
- let bits32 = $builder.ins().bitcast(types::I32, MemFlagsData::new(), val);
- let bits = $builder.ins().sextend(types::I64, bits32);
- if dst < STACK_MARKER {
- $builder.def_var(reg_vars_f32[dst as usize], val);
- $builder.def_var(reg_vars[dst as usize], bits);
- reg_ty[dst as usize] = Bank::F32;
- dirty_regs[dst as usize] = true;
- } else if dst == STACK_MARKER {
- if max_stack_depth > 0 {
- $builder.def_var(stack_vars_f32[sp], val);
- $builder.def_var(stack_vars[sp], bits);
- stack_ty[sp] = Bank::F32;
- sp += 1;
- } else {
- emit_stack_push!($builder, bits);
- }
- } else {
- let cfg = $builder.use_var(config_var);
- let base = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), cfg, call_record_base_offset);
- let off = i32::from(dst - CALLREC_BASE) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), bits, base, off);
- let zero_tag = $builder.ins().iconst(types::I64, 0);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero_tag, base, off + 8);
- }
- }};
- }
-
- macro_rules! reset_banks {
- () => {{
- for t in reg_ty.iter_mut() {
- *t = Bank::Int;
- }
- for t in stack_ty.iter_mut() {
- *t = Bank::Int;
- }
- }};
- }
-
- // Note that all reads from sources have to be in order (sources[0] before sources[1])
- macro_rules! i32_binop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let rhs_raw = read_src!($builder, $insn.sources[0]);
- let lhs_raw = read_src!($builder, $insn.sources[1]);
- let lhs = $builder.ins().ireduce(types::I32, lhs_raw);
- let rhs = $builder.ins().ireduce(types::I32, rhs_raw);
- let result = $builder.ins().$op(lhs, rhs);
- let result = $builder.ins().sextend(types::I64, result);
- write_dst!($builder, $insn.destination, result);
- }};
- }
- macro_rules! i64_binop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let rhs = read_src!($builder, $insn.sources[0]);
- let lhs = read_src!($builder, $insn.sources[1]);
- let result = $builder.ins().$op(lhs, rhs);
- write_dst!($builder, $insn.destination, result);
- }};
- }
- macro_rules! i32_unop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let src_raw = read_src!($builder, $insn.sources[0]);
- let src = $builder.ins().ireduce(types::I32, src_raw);
- let result = $builder.ins().$op(src);
- let result = $builder.ins().sextend(types::I64, result);
- write_dst!($builder, $insn.destination, result);
- }};
- }
- macro_rules! i64_unop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let src = read_src!($builder, $insn.sources[0]);
- let result = $builder.ins().$op(src);
- write_dst!($builder, $insn.destination, result);
- }};
- }
- macro_rules! i32_cmp {
- ($builder:expr, $insn:expr, $cc:expr) => {{
- let rhs_raw = read_src!($builder, $insn.sources[0]);
- let lhs_raw = read_src!($builder, $insn.sources[1]);
- let lhs = $builder.ins().ireduce(types::I32, lhs_raw);
- let rhs = $builder.ins().ireduce(types::I32, rhs_raw);
- let cmp = $builder.ins().icmp($cc, lhs, rhs);
- let result = $builder.ins().uextend(types::I64, cmp);
- write_dst!($builder, $insn.destination, result);
- }};
- }
- macro_rules! i64_cmp {
- ($builder:expr, $insn:expr, $cc:expr) => {{
- let rhs = read_src!($builder, $insn.sources[0]);
- let lhs = read_src!($builder, $insn.sources[1]);
- let cmp = $builder.ins().icmp($cc, lhs, rhs);
- let result = $builder.ins().uextend(types::I64, cmp);
- write_dst!($builder, $insn.destination, result);
- }};
- }
- macro_rules! f32_binop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let rhs = read_src_f32!($builder, $insn.sources[0]);
- let lhs = read_src_f32!($builder, $insn.sources[1]);
- let result = $builder.ins().$op(lhs, rhs);
- write_dst_f32!($builder, $insn.destination, result);
- }};
- }
- macro_rules! f64_binop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let rhs = read_src_f64!($builder, $insn.sources[0]);
- let lhs = read_src_f64!($builder, $insn.sources[1]);
- let result = $builder.ins().$op(lhs, rhs);
- write_dst_f64!($builder, $insn.destination, result);
- }};
- }
- macro_rules! f32_unop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let src = read_src_f32!($builder, $insn.sources[0]);
- let result = $builder.ins().$op(src);
- write_dst_f32!($builder, $insn.destination, result);
- }};
- }
- macro_rules! f64_unop {
- ($builder:expr, $insn:expr, $op:ident) => {{
- let src = read_src_f64!($builder, $insn.sources[0]);
- let result = $builder.ins().$op(src);
- write_dst_f64!($builder, $insn.destination, result);
- }};
- }
- macro_rules! f32_cmp {
- ($builder:expr, $insn:expr, $cc:expr) => {{
- let rhs = read_src_f32!($builder, $insn.sources[0]);
- let lhs = read_src_f32!($builder, $insn.sources[1]);
- let cmp = $builder.ins().fcmp($cc, lhs, rhs);
- let result = $builder.ins().uextend(types::I64, cmp);
- write_dst!($builder, $insn.destination, result);
- }};
- }
- macro_rules! f64_cmp {
- ($builder:expr, $insn:expr, $cc:expr) => {{
- let rhs = read_src_f64!($builder, $insn.sources[0]);
- let lhs = read_src_f64!($builder, $insn.sources[1]);
- let cmp = $builder.ins().fcmp($cc, lhs, rhs);
- let result = $builder.ins().uextend(types::I64, cmp);
- write_dst!($builder, $insn.destination, result);
- }};
- }
-
- macro_rules! read_local_inline {
- ($builder:expr, $idx_imm:expr) => {{
- let idx = ($idx_imm) as usize;
- if idx < local_vars.len() {
- let v = $builder.use_var(local_vars[idx]);
- if local_is_f64[idx] {
- $builder.ins().bitcast(types::I64, MemFlagsData::new(), v)
- } else if local_is_f32[idx] {
- let bits32 = $builder.ins().bitcast(types::I32, MemFlagsData::new(), v);
- $builder.ins().sextend(types::I64, bits32)
- } else {
- v
- }
- } else {
- let lb = $builder.use_var(locals_base_var);
- $builder
- .ins()
- .load(types::I64, MemFlagsData::trusted(), lb, (idx as i32) * value_size)
- }
- }};
- }
- macro_rules! read_local_f64 {
- ($builder:expr, $idx_imm:expr) => {{
- let idx = ($idx_imm) as usize;
- if idx < local_vars.len() && local_is_f64[idx] {
- $builder.use_var(local_vars[idx])
- } else if idx < local_vars.len() {
- let v = $builder.use_var(local_vars[idx]);
- $builder.ins().bitcast(types::F64, MemFlagsData::new(), v)
- } else {
- let lb = $builder.use_var(locals_base_var);
- $builder
- .ins()
- .load(types::F64, MemFlagsData::trusted(), lb, (idx as i32) * value_size)
- }
- }};
- }
- macro_rules! read_local_f32 {
- ($builder:expr, $idx_imm:expr) => {{
- let idx = ($idx_imm) as usize;
- if idx < local_vars.len() && local_is_f32[idx] {
- $builder.use_var(local_vars[idx])
- } else if idx < local_vars.len() {
- let v = $builder.use_var(local_vars[idx]);
- let v32 = $builder.ins().ireduce(types::I32, v);
- $builder.ins().bitcast(types::F32, MemFlagsData::new(), v32)
- } else {
- let lb = $builder.use_var(locals_base_var);
- $builder
- .ins()
- .load(types::F32, MemFlagsData::trusted(), lb, (idx as i32) * value_size)
- }
- }};
- }
- macro_rules! write_local_inline {
- ($builder:expr, $idx_imm:expr, $val:expr) => {{
- let idx = ($idx_imm) as usize;
- let v = $val;
- if idx < local_vars.len() {
- let stored = if local_is_f64[idx] {
- $builder.ins().bitcast(types::F64, MemFlagsData::new(), v)
- } else if local_is_f32[idx] {
- let v32 = $builder.ins().ireduce(types::I32, v);
- $builder.ins().bitcast(types::F32, MemFlagsData::new(), v32)
- } else {
- v
- };
- $builder.def_var(local_vars[idx], stored);
- dirty_locals[idx] = true;
- } else {
- let lb = $builder.use_var(locals_base_var);
- let offset = (idx as i32) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), v, lb, offset);
- let zero = $builder.ins().iconst(types::I64, 0);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero, lb, offset + 8);
- }
- }};
- }
- macro_rules! write_local_f64 {
- ($builder:expr, $idx_imm:expr, $val:expr) => {{
- let idx = ($idx_imm) as usize;
- let v = $val;
- if idx < local_vars.len() && local_is_f64[idx] {
- $builder.def_var(local_vars[idx], v);
- dirty_locals[idx] = true;
- } else if idx < local_vars.len() {
- let bits = $builder.ins().bitcast(types::I64, MemFlagsData::new(), v);
- $builder.def_var(local_vars[idx], bits);
- dirty_locals[idx] = true;
- } else {
- let lb = $builder.use_var(locals_base_var);
- let offset = (idx as i32) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), v, lb, offset);
- let zero = $builder.ins().iconst(types::I64, 0);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero, lb, offset + 8);
- }
- }};
- }
- macro_rules! write_local_f32 {
- ($builder:expr, $idx_imm:expr, $val:expr) => {{
- let idx = ($idx_imm) as usize;
- let v = $val;
- if idx < local_vars.len() && local_is_f32[idx] {
- $builder.def_var(local_vars[idx], v);
- dirty_locals[idx] = true;
- } else {
- let bits32 = $builder.ins().bitcast(types::I32, MemFlagsData::new(), v);
- let bits = $builder.ins().sextend(types::I64, bits32);
- write_local_inline!($builder, $idx_imm, bits);
- }
- }};
- }
- macro_rules! local_get {
- ($builder:expr, $idx_imm:expr, $dst:expr) => {{
- let idx = ($idx_imm) as usize;
- if idx < local_vars.len() && local_is_f64[idx] {
- let result = read_local_f64!($builder, $idx_imm);
- write_dst_f64!($builder, $dst, result);
- } else if idx < local_vars.len() && local_is_f32[idx] {
- let result = read_local_f32!($builder, $idx_imm);
- write_dst_f32!($builder, $dst, result);
- } else {
- let result = read_local_inline!($builder, $idx_imm);
- write_dst!($builder, $dst, result);
- }
- }};
- }
- macro_rules! local_set {
- ($builder:expr, $idx_imm:expr, $src:expr) => {{
- let idx = ($idx_imm) as usize;
- if idx < local_vars.len() && local_is_f64[idx] {
- let val = read_src_f64!($builder, $src);
- write_local_f64!($builder, $idx_imm, val);
- } else if idx < local_vars.len() && local_is_f32[idx] {
- let val = read_src_f32!($builder, $src);
- write_local_f32!($builder, $idx_imm, val);
- } else {
- let val = read_src!($builder, $src);
- write_local_inline!($builder, $idx_imm, val);
- }
- }};
- }
- macro_rules! flush_locals {
- ($builder:expr) => {{
- if !local_vars.is_empty() {
- let lb = $builder.use_var(locals_base_var);
- for i in 0..local_vars.len() {
- if !dirty_locals[i] {
- continue;
- }
- let v = $builder.use_var(local_vars[i]);
- let stored = if local_is_f32[i] {
- let bits32 = $builder.ins().bitcast(types::I32, MemFlagsData::new(), v);
- $builder.ins().sextend(types::I64, bits32)
- } else {
- v
- };
- let offset = (i as i32) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), stored, lb, offset);
- let zero = $builder.ins().iconst(types::I64, 0);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero, lb, offset + 8);
- }
- }
- }};
- }
-
- // Call + trap-check macro for helper calls that do not consume caller register state.
- // The callee gets arguments explicitly (register immediates, stack, or call record), and the caller's virtual registers stay live in SSA across the call.
- macro_rules! do_call_and_check {
- ($builder:expr, $sig:expr, $ptr:expr, $args:expr) => {{
- let call = $builder.ins().call_indirect($sig, $ptr, $args);
- let trapped = $builder.inst_results(call)[0];
- let is_trap = $builder.ins().icmp_imm_s(IntCC::NotEqual, trapped, 0);
- let cont = $builder.create_block();
- $builder.ins().brif(is_trap, trap_block, &[], cont, &[]);
- $builder.switch_to_block(cont);
- $builder.seal_block(cont);
- // Reload locals_base; frame_stack may have reallocated.
- let _cfg_for_lb = $builder.use_var(config_var);
- let new_lb = $builder
- .ins()
- .load(ptr_type, MemFlagsData::trusted(), _cfg_for_lb, locals_base_offset);
- $builder.def_var(locals_base_var, new_lb);
- }};
- }
- macro_rules! set_trap {
- ($builder:expr, $msg:expr) => {{
- let msg = $msg.as_bytes();
- let ss = $builder.create_sized_stack_slot(StackSlotData::new(
- StackSlotKind::ExplicitSlot,
- msg.len() as u32,
- 0,
- ));
- for (i, &byte) in msg.iter().enumerate() {
- let b = $builder.ins().iconst(types::I8, i64::from(byte));
- $builder.ins().stack_store(ptr_type, b, ss, i as i32);
- }
- let msg_ptr = $builder.ins().stack_addr(ptr_type, ss, 0);
- let msg_len = $builder.ins().iconst(types::I32, msg.len() as i64);
- let st_ptr = $builder.ins().func_addr(ptr_type, h_set_trap);
- let interp = $builder.use_var(interp_var);
- $builder
- .ins()
- .call_indirect(set_trap_sig, st_ptr, &[interp, msg_ptr, msg_len]);
- }};
- }
- // No bounds checks: the memory reserves the full base (u32) + offset (u32) span, so any
- // out-of-bounds access faults on an uncommitted page and unwinds as a wasm trap.
- macro_rules! inline_memory_address {
- ($builder:expr, $memory_index:expr, $addr:expr) => {{
- let memory_base = memory_bases
- .iter()
- .find_map(|(index, base)| (*index == $memory_index).then_some(*base))
- .expect("memory access must have a resolved base");
- let addr_offset = if ptr_type == types::I64 {
- $addr
- } else {
- $builder.ins().ireduce(ptr_type, $addr)
- };
- $builder.ins().iadd(memory_base, addr_offset)
- }};
- }
- macro_rules! inline_global_instance {
- ($global_index:expr) => {{
- global_instances
- .iter()
- .find_map(|(index, global)| (*index == $global_index).then_some(*global))
- .expect("global access must have a resolved instance")
- }};
- }
-
- // On a fresh call only the parameters are initialized by the caller.
- macro_rules! init_locals_fresh {
- ($builder:expr) => {{
- if local_vars.is_empty() {
- if num_locals > num_params {
- let lb = $builder.use_var(locals_base_var);
- let zero = $builder.ins().iconst(types::I64, 0);
- for i in num_params..num_locals {
- let offset = (i as i32) * value_size;
- $builder.ins().store(MemFlagsData::trusted(), zero, lb, offset);
- $builder
- .ins()
- .store(MemFlagsData::trusted(), zero, lb, offset + 8);
- }
- }
- } else {
- let lb = $builder.use_var(locals_base_var);
- for (i, var) in local_vars.iter().enumerate() {
- if i < num_params {
- let ty = if local_is_f64[i] {
- types::F64
- } else if local_is_f32[i] {
- types::F32
- } else {
- types::I64
- };
- let offset = (i as i32) * value_size;
- let val = $builder.ins().load(ty, MemFlagsData::trusted(), lb, offset);
- $builder.def_var(*var, val);
- } else if local_is_f64[i] {
- let zero = $builder.ins().f64const(0.0);
- $builder.def_var(*var, zero);
- } else if local_is_f32[i] {
- let zero = $builder.ins().f32const(0.0);
- $builder.def_var(*var, zero);
- } else {
- let zero = $builder.ins().iconst(types::I64, 0);
- $builder.def_var(*var, zero);
- }
- }
- }
- }};
- }
- macro_rules! init_locals_resume {
- ($builder:expr) => {{
- if !local_vars.is_empty() {
- let lb = $builder.use_var(locals_base_var);
- for (i, var) in local_vars.iter().enumerate() {
- let ty = if local_is_f64[i] {
- types::F64
- } else if local_is_f32[i] {
- types::F32
- } else {
- types::I64
- };
- let offset = (i as i32) * value_size;
- let val = $builder.ins().load(ty, MemFlagsData::trusted(), lb, offset);
- $builder.def_var(*var, val);
- }
- }
- }};
- }
-
- // If we have any tier-up checkpoints, the interpreter will eventually need to jump to some point in the function other than the entry block, so prepare dispatch blocks for that.
- // Note that the initial block will already have the correct register state loaded, so we don't need to sync registers for the tier-up dispatch targets.
- let has_tier_up = insns.iter().any(|i| i.opcode == op::SYNTHETIC_TIER_UP);
- let tier_up_target_ip = builder.block_params(entry_block)[3];
- let mut tier_up_dispatch_tail: Option<Block> = None;
- let tier_up_body_start: Option<Block> = if has_tier_up {
- let body_start = builder.create_block();
- let dispatch = builder.create_block();
- let fresh = builder.create_block();
- let resume = builder.create_block();
- let is_tier_up = builder.ins().icmp_imm_s(IntCC::NotEqual, tier_up_target_ip, 0);
- builder.ins().brif(is_tier_up, resume, &[], fresh, &[]);
-
- builder.switch_to_block(resume);
- builder.seal_block(resume);
- init_locals_resume!(builder);
- builder.ins().jump(dispatch, &[]);
-
- builder.switch_to_block(fresh);
- builder.seal_block(fresh);
- init_locals_fresh!(builder);
- builder.ins().jump(body_start, &[]);
-
- builder.switch_to_block(body_start);
- tier_up_dispatch_tail = Some(dispatch);
- Some(body_start)
- } else {
- init_locals_fresh!(builder);
- None
- };
-
- let mut ip = 0usize;
- while ip < insns.len() {
- let insn = &insns[ip];
- let opc = insn.opcode;
-
- match opc {
- op::NOP => {}
-
- op::UNREACHABLE => {
- Self::sync_regs_to_config(
- &mut builder,
- &reg_vars,
- config_var,
- regs_offset,
- value_size,
- &dirty_regs,
- );
- flush_locals!(builder);
- set_trap!(builder, "unreachable executed");
- builder.ins().jump(trap_block, &[]);
- is_unreachable = true;
- let dead = builder.create_block();
- builder.switch_to_block(dead);
- builder.seal_block(dead);
- }
-
- op::BLOCK => {
- let arity = insn.imm3 & 0xffff;
- let param_count = (insn.imm3 >> 16) as usize;
- let after = builder.create_block();
- let entry_real_depth_var = if max_stack_depth == 0 {
- let var = builder.declare_var(types::I64);
- let cur = emit_stack_size!(builder);
- let entry = builder.ins().iadd_imm_s(cur, -(param_count as i64));
- builder.def_var(var, entry);
- Some(var)
- } else {
- None
- };
- control_stack.push(ControlFrame {
- kind: ControlKind::Block,
- branch_target: after,
- after_block: after,
- arity,
- param_count,
- stack_depth_at_entry: (sp - param_count) as i32,
- entry_real_depth_var,
- bank_snapshot: None,
- });
- }
-
- op::LOOP => {
- let arity = insn.imm3 & 0xffff;
- let param_count = (insn.imm3 >> 16) as usize;
- let header = builder.create_block();
- let after = builder.create_block();
- let entry_real_depth_var = if max_stack_depth == 0 {
- let var = builder.declare_var(types::I64);
- let cur = emit_stack_size!(builder);
- let entry = builder.ins().iadd_imm_s(cur, -(param_count as i64));
- builder.def_var(var, entry);
- Some(var)
- } else {
- None
- };
- builder.ins().jump(header, &[]);
- builder.switch_to_block(header);
- control_stack.push(ControlFrame {
- kind: ControlKind::Loop,
- branch_target: header,
- after_block: after,
- arity,
- param_count,
- stack_depth_at_entry: (sp - param_count) as i32,
- entry_real_depth_var,
- bank_snapshot: None,
- });
- // Loop header is a merge point (entry edge + back-edges + any tier-up dispatch).
- reset_banks!();
- }
-
- op::IF => {
- let arity = insn.imm3 & 0xffff;
- let _param_count = (insn.imm3 >> 16) as usize;
- let has_else = insn.imm2 >= 0;
- let then_block = builder.create_block();
- let else_block = builder.create_block();
- let after = builder.create_block();
-
- let cond_raw = read_src!(builder, insn.sources[0]);
- let cond = builder.ins().icmp_imm_s(IntCC::NotEqual, cond_raw, 0);
- let entry_real_depth_var = if max_stack_depth == 0 {
- let var = builder.declare_var(types::I64);
- let cur = emit_stack_size!(builder);
- let entry = builder.ins().iadd_imm_s(cur, -(_param_count as i64));
- builder.def_var(var, entry);
- Some(var)
- } else {
- None
- };
- if has_else {
- builder.ins().brif(cond, then_block, &[], else_block, &[]);
- } else {
- builder.ins().brif(cond, then_block, &[], after, &[]);
- }
-
- builder.switch_to_block(then_block);
- builder.seal_block(then_block);
-
- control_stack.push(ControlFrame {
- kind: ControlKind::If,
- branch_target: after,
- after_block: if has_else { else_block } else { after },
- arity,
- param_count: _param_count,
- stack_depth_at_entry: (sp - _param_count) as i32,
- entry_real_depth_var,
- bank_snapshot: Some((reg_ty, stack_ty.clone())),
- });
- }
-
- op::ELSE => {
- if let Some(frame) = control_stack.last() {
- let else_block = frame.after_block;
- let after = frame.branch_target;
- let entry_depth = frame.stack_depth_at_entry;
- let pc = frame.param_count;
- let snapshot = frame.bank_snapshot.clone();
- builder.ins().jump(after, &[]);
- builder.switch_to_block(else_block);
- builder.seal_block(else_block);
- // Reset sp to entry depth + param_count (else branch inherits params).
- sp = (entry_depth as usize) + pc;
- if let Some((saved_reg_ty, saved_stack_ty)) = snapshot {
- reg_ty = saved_reg_ty;
- stack_ty = saved_stack_ty;
- }
- if let Some(frame) = control_stack.last_mut() {
- frame.after_block = after;
- }
- }
- }
-
- op::END | op::SYNTHETIC_END_EXPRESSION => {
- if let Some(frame) = control_stack.pop() {
- let after = if frame.kind == ControlKind::If && frame.after_block != frame.branch_target {
- // If without else: the after_block is the branch_target.
- frame.branch_target
- } else {
- frame.after_block
- };
-
- builder.ins().jump(after, &[]);
- builder.switch_to_block(after);
- is_unreachable = false;
- // `after` merges the block body with any branches to it.
- reset_banks!();
-
- // After end of block, sp = entry depth + arity.
- sp = (frame.stack_depth_at_entry + frame.arity as i32) as usize;
-
- if frame.kind == ControlKind::Loop {
- builder.seal_block(frame.branch_target); // loop header
- }
- builder.seal_block(after);
- } else if !is_unreachable {
- push_top_n_to_real!(builder, result_arity);
- builder.ins().jump(epilogue_block, &[]);
- let dead = builder.create_block();
- builder.switch_to_block(dead);
- builder.seal_block(dead);
- }
- }
-
- op::BR | op::SYNTHETIC_BR_NOSTACK => {
- let label_idx = insn.imm1 as usize;
- if label_idx < control_stack.len() {
- let target_idx = control_stack.len() - 1 - label_idx;
- let frame = &control_stack[target_idx];
- let target = frame.branch_target;
- let arity = if frame.kind == ControlKind::Loop {
- 0
- } else {
- frame.arity
- };
- let entry = frame.stack_depth_at_entry as usize;
- if max_stack_depth > 0 {
- // vstack enabled: move top arity values to entry position.
- if arity > 0 {
- let result = if sp > 0 {
- builder.use_var(stack_vars[sp - 1])
- } else {
- emit_stack_pop!(builder)
- };
- builder.def_var(stack_vars[entry], result);
- }
- } else {
- // vstack disabled: trim the real value stack down to the target label's entry depth + arity, preserving the top arity values.
- let entry_depth_var = frame
- .entry_real_depth_var
- .expect("entry_real_depth_var must be set when vstack is disabled");
- let target_size = builder.use_var(entry_depth_var);
- emit_stack_cleanup!(builder, target_size, arity);
- }
- builder.ins().jump(target, &[]);
- } else {
- // br to function label = return.
- push_top_n_to_real!(builder, result_arity);
- builder.ins().jump(epilogue_block, &[]);
- }
- sp = 0;
- is_unreachable = true;
- let dead = builder.create_block();
- builder.switch_to_block(dead);
- builder.seal_block(dead);
- }
-
- op::BR_IF | op::SYNTHETIC_BR_IF_NOSTACK => {
- let label_idx = insn.imm1 as usize;
- let cond_raw = read_src!(builder, insn.sources[0]);
- let cond = builder.ins().icmp_imm_s(IntCC::NotEqual, cond_raw, 0);
-
- if label_idx < control_stack.len() {
- let target_idx = control_stack.len() - 1 - label_idx;
- let frame = &control_stack[target_idx];
- let target = frame.branch_target;
- let arity = if frame.kind == ControlKind::Loop {
- 0
- } else {
- frame.arity
- };
- let entry = frame.stack_depth_at_entry as usize;
- let extras = (sp as i32 - entry as i32 - arity as i32).max(0);
- if max_stack_depth == 0 {
- // not vstack: real value stack may have extras between the target label's entry depth and the result on top.
- // On the taken path, trim using the saved entry-depth variable.
- let entry_depth_var = frame
- .entry_real_depth_var
- .expect("entry_real_depth_var must be set when vstack is disabled");
- let taken_block = builder.create_block();
- let fallthrough = builder.create_block();
- builder.ins().brif(cond, taken_block, &[], fallthrough, &[]);
- builder.switch_to_block(taken_block);
- builder.seal_block(taken_block);
- let target_size = builder.use_var(entry_depth_var);
- emit_stack_cleanup!(builder, target_size, arity);
- builder.ins().jump(target, &[]);
- builder.switch_to_block(fallthrough);
- builder.seal_block(fallthrough);
- } else if extras > 0 {
- let taken_block = builder.create_block();
- let fallthrough = builder.create_block();
- builder.ins().brif(cond, taken_block, &[], fallthrough, &[]);
- builder.switch_to_block(taken_block);
- builder.seal_block(taken_block);
- if arity > 0 {
- let result = builder.use_var(stack_vars[sp - 1]);
- builder.def_var(stack_vars[entry], result);
- }
- // Note: we don't change sp here since fallthrough needs the original sp.
- builder.ins().jump(target, &[]);
- builder.switch_to_block(fallthrough);
- builder.seal_block(fallthrough);
- } else {
- let fallthrough = builder.create_block();
- builder.ins().brif(cond, target, &[], fallthrough, &[]);
- builder.switch_to_block(fallthrough);
- builder.seal_block(fallthrough);
- }
- } else {
- if sp > 0 {
- let taken_block = builder.create_block();
- let fallthrough = builder.create_block();
- builder.ins().brif(cond, taken_block, &[], fallthrough, &[]);
- builder.switch_to_block(taken_block);
- builder.seal_block(taken_block);
- push_top_n_to_real!(builder, result_arity);
- builder.ins().jump(epilogue_block, &[]);
- builder.switch_to_block(fallthrough);
- builder.seal_block(fallthrough);
- } else {
- let fallthrough = builder.create_block();
- builder.ins().brif(cond, epilogue_block, &[], fallthrough, &[]);
- builder.switch_to_block(fallthrough);
- builder.seal_block(fallthrough);
- }
- }
- }
-
- op::RETURN => {
- push_top_n_to_real!(builder, result_arity);
- builder.ins().jump(epilogue_block, &[]);
- sp = 0;
- is_unreachable = true;
- let dead = builder.create_block();
- builder.switch_to_block(dead);
- builder.seal_block(dead);
- }
-
- op::I32_CONST | op::I64_CONST => {
- let val = builder.ins().iconst(types::I64, insn.imm1);
- write_dst!(builder, insn.destination, val);
- }
- op::F32_CONST => {
- let val = builder.ins().f32const(Ieee32::with_bits(insn.imm1 as u32));
- write_dst_f32!(builder, insn.destination, val);
- }
- op::F64_CONST => {
- let val = builder.ins().f64const(Ieee64::with_bits(insn.imm1 as u64));
- write_dst_f64!(builder, insn.destination, val);
- }
-
- op::LOCAL_GET | op::SYNTHETIC_ARGUMENT_GET => {
- local_get!(builder, insn.imm1, insn.destination);
- }
- op::LOCAL_SET | op::SYNTHETIC_ARGUMENT_SET => {
- local_set!(builder, insn.imm1, insn.sources[0]);
- }
- op::LOCAL_TEE | op::SYNTHETIC_ARGUMENT_TEE => {
- let idx = insn.imm1 as usize;
- if idx < local_vars.len() && local_is_f64[idx] {
- let val = read_src_f64!(builder, insn.sources[0]);
- write_local_f64!(builder, insn.imm1, val);
- write_dst_f64!(builder, insn.destination, val);
- } else if idx < local_vars.len() && local_is_f32[idx] {
- let val = read_src_f32!(builder, insn.sources[0]);
- write_local_f32!(builder, insn.imm1, val);
- write_dst_f32!(builder, insn.destination, val);
- } else {
- let val = read_src!(builder, insn.sources[0]);
- write_local_inline!(builder, insn.imm1, val);
- write_dst!(builder, insn.destination, val);
- }
- }
-
- opc if (op::SYNTHETIC_LOCAL_GET_0..=op::SYNTHETIC_LOCAL_GET_7).contains(&opc) => {
- let local_idx = (opc - op::SYNTHETIC_LOCAL_GET_0) as i64;
- local_get!(builder, local_idx, insn.destination);
- }
- opc if (op::SYNTHETIC_LOCAL_SET_0..=op::SYNTHETIC_LOCAL_SET_7).contains(&opc) => {
- let local_idx = (opc - op::SYNTHETIC_LOCAL_SET_0) as i64;
- local_set!(builder, local_idx, insn.sources[0]);
- }
- op::SYNTHETIC_LOCAL_COPY => {
- let val = read_local_inline!(builder, insn.imm1);
- write_local_inline!(builder, insn.imm2, val);
- }
-
- op::GLOBAL_GET => {
- let global = inline_global_instance!(insn.imm1 as u32);
- let result = builder.ins().load(
- types::I64,
- MemFlagsData::trusted(),
- global,
- global_instance_value_offset,
- );
- write_dst!(builder, insn.destination, result);
- }
- op::GLOBAL_SET => {
- let val = read_src!(builder, insn.sources[0]);
- let global = inline_global_instance!(insn.imm1 as u32);
- builder
- .ins()
- .store(MemFlagsData::trusted(), val, global, global_instance_value_offset);
- let zero = builder.ins().iconst(types::I64, 0);
- builder
- .ins()
- .store(MemFlagsData::trusted(), zero, global, global_instance_value_offset + 8);
- }
-
- op::DROP => {
- if insn.sources[0] == STACK_MARKER {
- read_src!(builder, insn.sources[0]);
- }
- // No need to do anything if it's not on the real stack.
- }
-
- op::SELECT | op::SELECT_TYPED => {
- let cond_raw = read_src!(builder, insn.sources[0]);
- let rhs = read_src!(builder, insn.sources[1]);
- let lhs = read_src!(builder, insn.sources[2]);
- let cond = builder.ins().icmp_imm_s(IntCC::NotEqual, cond_raw, 0);
- let result = builder.ins().select(cond, lhs, rhs);
- write_dst!(builder, insn.destination, result);
- }
-
- op::BR_TABLE => {
- let inline_count = (insn.imm3 & 0xff) as usize;
- if inline_count == 0xff {
- return Err("br_table too large for inline encoding");
- }
-
- let default_label = ((insn.imm3 >> 8) & 0xffff) as usize;
-
- // Collect all labels; first 8 from this instruction, rest from continuations.
- let mut all_labels: Vec<usize> = Vec::with_capacity(inline_count);
- for i in 0..inline_count {
- let packed = if i < 4 { insn.imm1 as u64 } else { insn.imm2 as u64 };
- all_labels.push(((packed >> ((i % 4) * 16)) & 0xffff) as usize);
- }
- while ip + 1 < insns.len() && insns[ip + 1].opcode == op::SYNTHETIC_BR_TABLE_CONT {
- ip += 1;
- let cont = &insns[ip];
- let chunk = (cont.imm3 & 0xff) as usize;
- for j in 0..chunk {
- let packed = if j < 4 { cont.imm1 as u64 } else { cont.imm2 as u64 };
- all_labels.push(((packed >> ((j % 4) * 16)) & 0xffff) as usize);
- }
- }
-
- let cond_raw = read_src!(builder, insn.sources[0]);
- let cond = builder.ins().ireduce(types::I32, cond_raw);
-
- let branch_to_label = |builder: &mut FunctionBuilder, label_idx: usize| {
- if label_idx < control_stack.len() {
- let target_idx = control_stack.len() - 1 - label_idx;
- let frame = &control_stack[target_idx];
- let target = frame.branch_target;
- let arity = if frame.kind == ControlKind::Loop {
- 0
- } else {
- frame.arity
- };
- let entry = frame.stack_depth_at_entry as usize;
- if max_stack_depth > 0 && arity > 0 {
- let result = if sp > 0 {
- builder.use_var(stack_vars[sp - 1])
- } else {
- emit_stack_pop!(builder)
- };
- builder.def_var(stack_vars[entry], result);
- } else if max_stack_depth == 0 {
- let entry_depth_var = frame
- .entry_real_depth_var
- .expect("entry_real_depth_var must be set when vstack is disabled");
- let target_size = builder.use_var(entry_depth_var);
- emit_stack_cleanup!(builder, target_size, arity);
- }
- builder.ins().jump(target, &[]);
- } else {
- push_top_n_to_real!(builder, result_arity);
- builder.ins().jump(epilogue_block, &[]);
- }
- };
-
- for (i, &label) in all_labels.iter().enumerate() {
- let case_block = builder.create_block();
- let next_fallthrough = builder.create_block();
- let compare = builder.ins().icmp_imm_s(IntCC::Equal, cond, i as i64);
- builder.ins().brif(compare, case_block, &[], next_fallthrough, &[]);
-
- builder.switch_to_block(case_block);
- builder.seal_block(case_block);
- branch_to_label(&mut builder, label);
-
- builder.switch_to_block(next_fallthrough);
- builder.seal_block(next_fallthrough);
- }
-
- branch_to_label(&mut builder, default_label);
- sp = 0;
- is_unreachable = true;
- let dead = builder.create_block();
- builder.switch_to_block(dead);
- builder.seal_block(dead);
- }
-
- op::I32_ADD => i32_binop!(builder, insn, iadd),
- op::I32_SUB => i32_binop!(builder, insn, isub),
- op::I32_MUL => i32_binop!(builder, insn, imul),
- op::I32_AND => i32_binop!(builder, insn, band),
- op::I32_OR => i32_binop!(builder, insn, bor),
- op::I32_XOR => i32_binop!(builder, insn, bxor),
- op::I32_SHL => i32_binop!(builder, insn, ishl),
- op::I32_SHRS => i32_binop!(builder, insn, sshr),
- op::I32_SHRU => i32_binop!(builder, insn, ushr),
- op::I32_ROTL => i32_binop!(builder, insn, rotl),
- op::I32_ROTR => i32_binop!(builder, insn, rotr),
- op::I32_DIVS => i32_binop!(builder, insn, sdiv),
- op::I32_DIVU => i32_binop!(builder, insn, udiv),
- op::I32_REMS => i32_binop!(builder, insn, srem),
- op::I32_REMU => i32_binop!(builder, insn, urem),
- op::I32_CLZ => i32_unop!(builder, insn, clz),
- op::I32_CTZ => i32_unop!(builder, insn, ctz),
- op::I32_POPCNT => i32_unop!(builder, insn, popcnt),
-
- op::I64_ADD => i64_binop!(builder, insn, iadd),
- op::I64_SUB => i64_binop!(builder, insn, isub),
- op::I64_MUL => i64_binop!(builder, insn, imul),
- op::I64_AND => i64_binop!(builder, insn, band),
- op::I64_OR => i64_binop!(builder, insn, bor),
- op::I64_XOR => i64_binop!(builder, insn, bxor),
- op::I64_SHL => i64_binop!(builder, insn, ishl),
- op::I64_SHRS => i64_binop!(builder, insn, sshr),
- op::I64_SHRU => i64_binop!(builder, insn, ushr),
- op::I64_ROTL => i64_binop!(builder, insn, rotl),
- op::I64_ROTR => i64_binop!(builder, insn, rotr),
- op::I64_DIVS => i64_binop!(builder, insn, sdiv),
- op::I64_DIVU => i64_binop!(builder, insn, udiv),
- op::I64_REMS => i64_binop!(builder, insn, srem),
- op::I64_REMU => i64_binop!(builder, insn, urem),
- op::I64_CLZ => i64_unop!(builder, insn, clz),
- op::I64_CTZ => i64_unop!(builder, insn, ctz),
- op::I64_POPCNT => i64_unop!(builder, insn, popcnt),
-
- op::I32_EQZ => {
- let src_raw = read_src!(builder, insn.sources[0]);
- let src = builder.ins().ireduce(types::I32, src_raw);
- let r = builder.ins().icmp_imm_s(IntCC::Equal, src, 0);
- let result = builder.ins().uextend(types::I64, r);
- write_dst!(builder, insn.destination, result);
- }
- op::I32_EQ => i32_cmp!(builder, insn, IntCC::Equal),
- op::I32_NE => i32_cmp!(builder, insn, IntCC::NotEqual),
- op::I32_LTS => i32_cmp!(builder, insn, IntCC::SignedLessThan),
- op::I32_LTU => i32_cmp!(builder, insn, IntCC::UnsignedLessThan),
- op::I32_GTS => i32_cmp!(builder, insn, IntCC::SignedGreaterThan),
- op::I32_GTU => i32_cmp!(builder, insn, IntCC::UnsignedGreaterThan),
- op::I32_LES => i32_cmp!(builder, insn, IntCC::SignedLessThanOrEqual),
- op::I32_LEU => i32_cmp!(builder, insn, IntCC::UnsignedLessThanOrEqual),
- op::I32_GES => i32_cmp!(builder, insn, IntCC::SignedGreaterThanOrEqual),
- op::I32_GEU => i32_cmp!(builder, insn, IntCC::UnsignedGreaterThanOrEqual),
-
- op::I64_EQZ => {
- let src = read_src!(builder, insn.sources[0]);
- let r = builder.ins().icmp_imm_s(IntCC::Equal, src, 0);
- let result = builder.ins().uextend(types::I64, r);
- write_dst!(builder, insn.destination, result);
- }
- op::I64_EQ => i64_cmp!(builder, insn, IntCC::Equal),
- op::I64_NE => i64_cmp!(builder, insn, IntCC::NotEqual),
- op::I64_LTS => i64_cmp!(builder, insn, IntCC::SignedLessThan),
- op::I64_LTU => i64_cmp!(builder, insn, IntCC::UnsignedLessThan),
- op::I64_GTS => i64_cmp!(builder, insn, IntCC::SignedGreaterThan),
- op::I64_GTU => i64_cmp!(builder, insn, IntCC::UnsignedGreaterThan),
- op::I64_LES => i64_cmp!(builder, insn, IntCC::SignedLessThanOrEqual),
- op::I64_LEU => i64_cmp!(builder, insn, IntCC::UnsignedLessThanOrEqual),
- op::I64_GES => i64_cmp!(builder, insn, IntCC::SignedGreaterThanOrEqual),
- op::I64_GEU => i64_cmp!(builder, insn, IntCC::UnsignedGreaterThanOrEqual),
-
- op::F32_ADD => f32_binop!(builder, insn, fadd),
- op::F32_SUB => f32_binop!(builder, insn, fsub),
- op::F32_MUL => f32_binop!(builder, insn, fmul),
- op::F32_DIV => f32_binop!(builder, insn, fdiv),
- op::F32_MIN => f32_binop!(builder, insn, fmin),
- op::F32_MAX => f32_binop!(builder, insn, fmax),
- op::F32_COPYSIGN => f32_binop!(builder, insn, fcopysign),
- op::F32_ABS => f32_unop!(builder, insn, fabs),
- op::F32_NEG => f32_unop!(builder, insn, fneg),
- op::F32_CEIL => f32_unop!(builder, insn, ceil),
- op::F32_FLOOR => f32_unop!(builder, insn, floor),
- op::F32_TRUNC => f32_unop!(builder, insn, trunc),
- op::F32_NEAREST => f32_unop!(builder, insn, nearest),
- op::F32_SQRT => f32_unop!(builder, insn, sqrt),
-
- op::F64_ADD => f64_binop!(builder, insn, fadd),
- op::F64_SUB => f64_binop!(builder, insn, fsub),
- op::F64_MUL => f64_binop!(builder, insn, fmul),
- op::F64_DIV => f64_binop!(builder, insn, fdiv),
- op::F64_MIN => f64_binop!(builder, insn, fmin),
- op::F64_MAX => f64_binop!(builder, insn, fmax),
- op::F64_COPYSIGN => f64_binop!(builder, insn, fcopysign),
- op::F64_ABS => f64_unop!(builder, insn, fabs),
- op::F64_NEG => f64_unop!(builder, insn, fneg),
- op::F64_CEIL => f64_unop!(builder, insn, ceil),
- op::F64_FLOOR => f64_unop!(builder, insn, floor),
- op::F64_TRUNC => f64_unop!(builder, insn, trunc),
- op::F64_NEAREST => f64_unop!(builder, insn, nearest),
- op::F64_SQRT => f64_unop!(builder, insn, sqrt),
-
- op::F32_EQ => f32_cmp!(builder, insn, FloatCC::Equal),
- op::F32_NE => f32_cmp!(builder, insn, FloatCC::NotEqual),
- op::F32_LT => f32_cmp!(builder, insn, FloatCC::LessThan),
- op::F32_GT => f32_cmp!(builder, insn, FloatCC::GreaterThan),
- op::F32_LE => f32_cmp!(builder, insn, FloatCC::LessThanOrEqual),
- op::F32_GE => f32_cmp!(builder, insn, FloatCC::GreaterThanOrEqual),
-
- op::F64_EQ => f64_cmp!(builder, insn, FloatCC::Equal),
- op::F64_NE => f64_cmp!(builder, insn, FloatCC::NotEqual),
- op::F64_LT => f64_cmp!(builder, insn, FloatCC::LessThan),
- op::F64_GT => f64_cmp!(builder, insn, FloatCC::GreaterThan),
- op::F64_LE => f64_cmp!(builder, insn, FloatCC::LessThanOrEqual),
- op::F64_GE => f64_cmp!(builder, insn, FloatCC::GreaterThanOrEqual),
-
- op::I32_WRAP_I64 => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I32, src);
- let result = builder.ins().sextend(types::I64, narrowed);
- write_dst!(builder, insn.destination, result);
- }
- op::I64_EXTEND_SI32 => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I32, src);
- let result = builder.ins().sextend(types::I64, narrowed);
- write_dst!(builder, insn.destination, result);
- }
- op::I64_EXTEND_UI32 => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I32, src);
- let result = builder.ins().uextend(types::I64, narrowed);
- write_dst!(builder, insn.destination, result);
- }
- op::I32_EXTEND8_S => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I8, src);
- let extended = builder.ins().sextend(types::I32, narrowed);
- let result = builder.ins().sextend(types::I64, extended);
- write_dst!(builder, insn.destination, result);
- }
- op::I32_EXTEND16_S => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I16, src);
- let extended = builder.ins().sextend(types::I32, narrowed);
- let result = builder.ins().sextend(types::I64, extended);
- write_dst!(builder, insn.destination, result);
- }
- op::I64_EXTEND8_S => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I8, src);
- let result = builder.ins().sextend(types::I64, narrowed);
- write_dst!(builder, insn.destination, result);
- }
- op::I64_EXTEND16_S => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I16, src);
- let result = builder.ins().sextend(types::I64, narrowed);
- write_dst!(builder, insn.destination, result);
- }
- op::I64_EXTEND32_S => {
- let src = read_src!(builder, insn.sources[0]);
- let narrowed = builder.ins().ireduce(types::I32, src);
- let result = builder.ins().sextend(types::I64, narrowed);
- write_dst!(builder, insn.destination, result);
- }
- // Float-int conversions
- op::F32_CONVERT_SI32 => {
- let src = read_src!(builder, insn.sources[0]);
- let i32_val = builder.ins().ireduce(types::I32, src);
- let f32_val = builder.ins().fcvt_from_sint(types::F32, i32_val);
- write_dst_f32!(builder, insn.destination, f32_val);
- }
- op::F32_CONVERT_UI32 => {
- let src = read_src!(builder, insn.sources[0]);
- let i32_val = builder.ins().ireduce(types::I32, src);
- let f32_val = builder.ins().fcvt_from_uint(types::F32, i32_val);
- write_dst_f32!(builder, insn.destination, f32_val);
- }
- op::F32_CONVERT_SI64 => {
- let src = read_src!(builder, insn.sources[0]);
- let f32_val = builder.ins().fcvt_from_sint(types::F32, src);
- write_dst_f32!(builder, insn.destination, f32_val);
- }
- op::F32_CONVERT_UI64 => {
- let src = read_src!(builder, insn.sources[0]);
- let f32_val = builder.ins().fcvt_from_uint(types::F32, src);
- write_dst_f32!(builder, insn.destination, f32_val);
- }
- op::F64_CONVERT_SI32 => {
- let src = read_src!(builder, insn.sources[0]);
- let i32_val = builder.ins().ireduce(types::I32, src);
- let f64_val = builder.ins().fcvt_from_sint(types::F64, i32_val);
- write_dst_f64!(builder, insn.destination, f64_val);
- }
- op::F64_CONVERT_UI32 => {
- let src = read_src!(builder, insn.sources[0]);
- let i32_val = builder.ins().ireduce(types::I32, src);
- let f64_val = builder.ins().fcvt_from_uint(types::F64, i32_val);
- write_dst_f64!(builder, insn.destination, f64_val);
- }
- op::F64_CONVERT_SI64 => {
- let src = read_src!(builder, insn.sources[0]);
- let f64_val = builder.ins().fcvt_from_sint(types::F64, src);
- write_dst_f64!(builder, insn.destination, f64_val);
- }
- op::F64_CONVERT_UI64 => {
- let src = read_src!(builder, insn.sources[0]);
- let f64_val = builder.ins().fcvt_from_uint(types::F64, src);
- write_dst_f64!(builder, insn.destination, f64_val);
- }
- op::I32_REINTERPRET_F32
- | op::F32_REINTERPRET_I32
- | op::I64_REINTERPRET_F64
- | op::F64_REINTERPRET_I64 => {
- let src = read_src!(builder, insn.sources[0]);
- write_dst!(builder, insn.destination, src);
- }
- op::F32_DEMOTE_F64 => {
- let f64_val = read_src_f64!(builder, insn.sources[0]);
- let f32_val = builder.ins().fdemote(types::F32, f64_val);
- write_dst_f32!(builder, insn.destination, f32_val);
- }
- op::F64_PROMOTE_F32 => {
- let f32_val = read_src_f32!(builder, insn.sources[0]);
- let f64_val = builder.ins().fpromote(types::F64, f32_val);
- write_dst_f64!(builder, insn.destination, f64_val);
- }
- // Truncation conversions (these can trap in wasm).
- // Cranelift's fcvt_to_sint/fcvt_to_uint trap on overflow/NaN; the handler then maps the resulting "BadConversionToInteger" trap back to a wasm trap.
- op::I32_TRUNC_SF32
- | op::I32_TRUNC_UF32
- | op::I32_TRUNC_SF64
- | op::I32_TRUNC_UF64
- | op::I64_TRUNC_SF32
- | op::I64_TRUNC_UF32
- | op::I64_TRUNC_SF64
- | op::I64_TRUNC_UF64 => {
- let is_f32_src = matches!(
- opc,
- op::I32_TRUNC_SF32 | op::I32_TRUNC_UF32 | op::I64_TRUNC_SF32 | op::I64_TRUNC_UF32
- );
- let is_i32_dst = matches!(
- opc,
- op::I32_TRUNC_SF32 | op::I32_TRUNC_UF32 | op::I32_TRUNC_SF64 | op::I32_TRUNC_UF64
- );
- let is_signed = matches!(
- opc,
- op::I32_TRUNC_SF32 | op::I32_TRUNC_SF64 | op::I64_TRUNC_SF32 | op::I64_TRUNC_SF64
- );
-
- let float_val = if is_f32_src {
- read_src_f32!(builder, insn.sources[0])
- } else {
- read_src_f64!(builder, insn.sources[0])
- };
-
- let int_type = if is_i32_dst { types::I32 } else { types::I64 };
- let int_val = if is_signed {
- builder.ins().fcvt_to_sint(int_type, float_val)
- } else {
- builder.ins().fcvt_to_uint(int_type, float_val)
- };
-
- let result = if is_i32_dst {
- builder.ins().sextend(types::I64, int_val)
- } else {
- int_val
- };
- write_dst!(builder, insn.destination, result);
- }
-
- op::I32_TRUNC_SAT_F32_S
- | op::I32_TRUNC_SAT_F32_U
- | op::I32_TRUNC_SAT_F64_S
- | op::I32_TRUNC_SAT_F64_U
- | op::I64_TRUNC_SAT_F32_S
- | op::I64_TRUNC_SAT_F32_U
- | op::I64_TRUNC_SAT_F64_S
- | op::I64_TRUNC_SAT_F64_U => {
- let is_f32_src = matches!(
- opc,
- op::I32_TRUNC_SAT_F32_S
- | op::I32_TRUNC_SAT_F32_U
- | op::I64_TRUNC_SAT_F32_S
- | op::I64_TRUNC_SAT_F32_U
- );
- let is_i32_dst = matches!(
- opc,
- op::I32_TRUNC_SAT_F32_S
- | op::I32_TRUNC_SAT_F32_U
- | op::I32_TRUNC_SAT_F64_S
- | op::I32_TRUNC_SAT_F64_U
- );
- let is_signed = matches!(
- opc,
- op::I32_TRUNC_SAT_F32_S
- | op::I32_TRUNC_SAT_F64_S
- | op::I64_TRUNC_SAT_F32_S
- | op::I64_TRUNC_SAT_F64_S
- );
-
- let float_val = if is_f32_src {
- read_src_f32!(builder, insn.sources[0])
- } else {
- read_src_f64!(builder, insn.sources[0])
- };
-
- let int_type = if is_i32_dst { types::I32 } else { types::I64 };
- let int_val = if is_signed {
- builder.ins().fcvt_to_sint_sat(int_type, float_val)
- } else {
- builder.ins().fcvt_to_uint_sat(int_type, float_val)
- };
-
- let result = if is_i32_dst {
- builder.ins().sextend(types::I64, int_val)
- } else {
- int_val
- };
- write_dst!(builder, insn.destination, result);
- }
-
- op::I32_LOAD
- | op::I64_LOAD
- | op::F32_LOAD
- | op::F64_LOAD
- | op::I32_LOAD8_S
- | op::I32_LOAD8_U
- | op::I32_LOAD16_S
- | op::I32_LOAD16_U
- | op::I64_LOAD8_S
- | op::I64_LOAD8_U
- | op::I64_LOAD16_S
- | op::I64_LOAD16_U
- | op::I64_LOAD32_S
- | op::I64_LOAD32_U => {
- // addr = base (from source reg as u32) + offset.
- let base_raw = read_src!(builder, insn.sources[0]);
- let base_u32 = builder.ins().ireduce(types::I32, base_raw);
- let base_u64 = builder.ins().uextend(types::I64, base_u32);
- let offset = builder.ins().iconst(types::I64, insn.imm1);
- let addr = builder.ins().iadd(base_u64, offset);
-
- let mem_idx = insn.imm3;
- let address = inline_memory_address!(builder, mem_idx, addr);
- if opc == op::F64_LOAD {
- let result = builder.ins().load(types::F64, wasm_memory_flags, address, 0);
- write_dst_f64!(builder, insn.destination, result);
- } else if opc == op::F32_LOAD {
- let result = builder.ins().load(types::F32, wasm_memory_flags, address, 0);
- write_dst_f32!(builder, insn.destination, result);
- } else {
- let result = match opc {
- op::I32_LOAD | op::I64_LOAD32_U => {
- let value = builder.ins().load(types::I32, wasm_memory_flags, address, 0);
- builder.ins().uextend(types::I64, value)
- }
- op::I64_LOAD => builder.ins().load(types::I64, wasm_memory_flags, address, 0),
- op::I32_LOAD8_S | op::I64_LOAD8_S => {
- let value = builder.ins().load(types::I8, wasm_memory_flags, address, 0);
- builder.ins().sextend(types::I64, value)
- }
- op::I32_LOAD8_U | op::I64_LOAD8_U => {
- let value = builder.ins().load(types::I8, wasm_memory_flags, address, 0);
- builder.ins().uextend(types::I64, value)
- }
- op::I32_LOAD16_S | op::I64_LOAD16_S => {
- let value = builder.ins().load(types::I16, wasm_memory_flags, address, 0);
- builder.ins().sextend(types::I64, value)
- }
- op::I32_LOAD16_U | op::I64_LOAD16_U => {
- let value = builder.ins().load(types::I16, wasm_memory_flags, address, 0);
- builder.ins().uextend(types::I64, value)
- }
- op::I64_LOAD32_S => {
- let value = builder.ins().load(types::I32, wasm_memory_flags, address, 0);
- builder.ins().sextend(types::I64, value)
- }
- _ => unreachable!(),
- };
- write_dst!(builder, insn.destination, result);
- }
- }
-
- op::I32_STORE
- | op::I64_STORE
- | op::F32_STORE
- | op::F64_STORE
- | op::I32_STORE8
- | op::I32_STORE16
- | op::I64_STORE8
- | op::I64_STORE16
- | op::I64_STORE32 => {
- let mem_idx = insn.imm3;
- let is_f32 = opc == op::F32_STORE;
- let val = if is_f32 {
- read_src_f32!(builder, insn.sources[0])
- } else {
- read_src!(builder, insn.sources[0])
- };
- let base_raw = read_src!(builder, insn.sources[1]);
- let base_u32 = builder.ins().ireduce(types::I32, base_raw);
- let base_u64 = builder.ins().uextend(types::I64, base_u32);
- let offset = builder.ins().iconst(types::I64, insn.imm1);
- let addr = builder.ins().iadd(base_u64, offset);
-
- let access_size = match opc {
- op::I32_STORE8 | op::I64_STORE8 => 1,
- op::I32_STORE16 | op::I64_STORE16 => 2,
- op::I32_STORE | op::F32_STORE | op::I64_STORE32 => 4,
- op::I64_STORE | op::F64_STORE => 8,
- _ => unreachable!(),
- };
- let address = inline_memory_address!(builder, mem_idx, addr);
- let value = if is_f32 {
- val
- } else {
- match access_size {
- 1 => builder.ins().ireduce(types::I8, val),
- 2 => builder.ins().ireduce(types::I16, val),
- 4 => builder.ins().ireduce(types::I32, val),
- 8 => val,
- _ => unreachable!(),
- }
- };
- builder.ins().store(wasm_memory_flags, value, address, 0);
- }
-
- op::MEMORY_SIZE => {
- let mem_idx = builder.ins().iconst(types::I32, insn.imm1);
- let _xv_config_var = builder.use_var(config_var);
- let _xc_0 = builder.ins().func_addr(ptr_type, h_mem_size);
- let call = builder
- .ins()
- .call_indirect(mem_size_sig, _xc_0, &[_xv_config_var, mem_idx]);
- let result = builder.inst_results(call)[0];
- write_dst!(builder, insn.destination, result);
- }
-
- op::MEMORY_GROW => {
- let pages = read_src!(builder, insn.sources[0]);
- let pages_i32 = builder.ins().ireduce(types::I32, pages);
- let mem_idx = builder.ins().iconst(types::I32, insn.imm1);
- let _xv_config_var = builder.use_var(config_var);
- let _xc_0 = builder.ins().func_addr(ptr_type, h_mem_grow);
- let call = builder
- .ins()
- .call_indirect(mem_grow_sig, _xc_0, &[_xv_config_var, mem_idx, pages_i32]);
- let result = builder.inst_results(call)[0];
- let result = builder.ins().sextend(types::I64, result);
- write_dst!(builder, insn.destination, result);
- }
-
- op::MEMORY_COPY => {
- // imm1 = dst_mem, imm2 = src_mem
- // sources: [0]=count, [1]=src_offset, [2]=dst_offset
- let count = read_src!(builder, insn.sources[0]);
- let src_offset = read_src!(builder, insn.sources[1]);
- let dst_offset = read_src!(builder, insn.sources[2]);
- let count_i32 = builder.ins().ireduce(types::I32, count);
- let src_i32 = builder.ins().ireduce(types::I32, src_offset);
- let dst_i32 = builder.ins().ireduce(types::I32, dst_offset);
- let dst_mem = builder.ins().iconst(types::I32, insn.imm1);
- let src_mem = builder.ins().iconst(types::I32, insn.imm2);
- let cfp = builder.ins().func_addr(ptr_type, h_memory_copy);
- let iv = builder.use_var(interp_var);
- let cv = builder.use_var(config_var);
- do_call_and_check!(
- builder,
- memory_copy_sig,
- cfp,
- &[iv, cv, dst_mem, src_mem, dst_i32, src_i32, count_i32]
- );
- }
-
- op::MEMORY_FILL => {
- // imm1 = mem_idx
- // sources: [0]=count, [1]=value, [2]=offset
- let count = read_src!(builder, insn.sources[0]);
- let value = read_src!(builder, insn.sources[1]);
- let offset = read_src!(builder, insn.sources[2]);
- let count_i32 = builder.ins().ireduce(types::I32, count);
- let value_i32 = builder.ins().ireduce(types::I32, value);
- let offset_i32 = builder.ins().ireduce(types::I32, offset);
- let mem_idx = builder.ins().iconst(types::I32, insn.imm1);
- let cfp = builder.ins().func_addr(ptr_type, h_memory_fill);
- let iv = builder.use_var(interp_var);
- let cv = builder.use_var(config_var);
- do_call_and_check!(
- builder,
- memory_fill_sig,
- cfp,
- &[iv, cv, mem_idx, offset_i32, value_i32, count_i32]
- );
- }
-
- // For CALL and CALL_INDIRECT, we have no extra information and have to use the interpreter stack for args and returns.
- op::CALL => {
- // Flush virtual stack, args are already on it from previous instructions.
- flush_vstack_to_real!(builder);
- let func_idx = builder.ins().iconst(types::I32, insn.imm1);
- let cfp = builder.ins().func_addr(ptr_type, h_call_fn);
- let iv = builder.use_var(interp_var);
- let cv = builder.use_var(config_var);
- do_call_and_check!(builder, call_fn_sig, cfp, &[iv, cv, func_idx]);
- // The helper pushes results to value_stack; pop to the actual destination.
- if insn.destination != STACK_MARKER {
- let result = emit_stack_pop!(builder);
- write_dst!(builder, insn.destination, result);
- }
- }
-
- op::CALL_INDIRECT => {
- flush_vstack_to_real!(builder);
- let element_index = read_src!(builder, insn.sources[0]);
- let element_index = builder.ins().ireduce(types::I32, element_index);
- let type_idx = builder.ins().iconst(types::I32, insn.imm1);
- let table_idx = builder.ins().iconst(types::I32, insn.imm2);
- let cfp = builder.ins().func_addr(ptr_type, h_call_indirect);
- let iv = builder.use_var(interp_var);
- let cv = builder.use_var(config_var);
- do_call_and_check!(
- builder,
- call_indirect_sig,
- cfp,
- &[iv, cv, table_idx, type_idx, element_index]
- );
- if insn.destination != STACK_MARKER {
- let result = emit_stack_pop!(builder);
- write_dst!(builder, insn.destination, result);
- }
- }
-
- opc if (op::SYNTHETIC_CALL_00..=op::SYNTHETIC_CALL_31).contains(&opc) => {
- let variant = (opc - op::SYNTHETIC_CALL_00) as usize;
- let param_count = variant / 2;
- let result_count = variant % 2;
- let func_idx = builder.ins().iconst(types::I32, insn.imm1);
- let iv = builder.use_var(interp_var);
- let cv = builder.use_var(config_var);
- match param_count {
- 0 => {
- let cfp = builder.ins().func_addr(ptr_type, h_direct_call_0);
- do_call_and_check!(builder, call_fn_sig, cfp, &[iv, cv, func_idx]);
- }
- 1 => {
- let arg0 = read_src!(builder, insn.sources[0]);
- let cfp = builder.ins().func_addr(ptr_type, h_direct_call_1);
- do_call_and_check!(builder, call_fn1_sig, cfp, &[iv, cv, func_idx, arg0]);
- }
- 2 => {
- let s0 = read_src!(builder, insn.sources[0]); // last param (top)
- let s1 = read_src!(builder, insn.sources[1]); // first param
- let cfp = builder.ins().func_addr(ptr_type, h_direct_call_2);
- do_call_and_check!(builder, call_fn2_sig, cfp, &[iv, cv, func_idx, s1, s0]);
- }
- 3 => {
- let s0 = read_src!(builder, insn.sources[0]); // last param (top)
- let s1 = read_src!(builder, insn.sources[1]); // middle param
- let s2 = read_src!(builder, insn.sources[2]); // first param
- let cfp = builder.ins().func_addr(ptr_type, h_direct_call_3);
- do_call_and_check!(builder, call_fn3_sig, cfp, &[iv, cv, func_idx, s2, s1, s0]);
- }
- _ => unreachable!(),
- }
-
- if result_count > 0 {
- let cv = builder.use_var(config_var);
- let result = builder.ins().load(
- types::I64,
- MemFlagsData::trusted(),
- cv,
- compiled_call_result_scratch_offset,
- );
- write_dst!(builder, insn.destination, result);
- }
- }
-
- op::SYNTHETIC_CALL_WITH_RECORD_0 | op::SYNTHETIC_CALL_WITH_RECORD_1 => {
- let func_idx = builder.ins().iconst(types::I32, insn.imm1);
- let cwp = builder.ins().func_addr(ptr_type, h_call_wr);
- let iv = builder.use_var(interp_var);
- let cv = builder.use_var(config_var);
- do_call_and_check!(builder, call_wr_sig, cwp, &[iv, cv, func_idx]);
- if opc == op::SYNTHETIC_CALL_WITH_RECORD_1 {
- let cv2 = builder.use_var(config_var);
- let result = builder.ins().load(
- types::I64,
- MemFlagsData::trusted(),
- cv2,
- compiled_call_result_scratch_offset,
- );
- write_dst!(builder, insn.destination, result);
- }
- }
-
- op::SYNTHETIC_LOCAL_SETI32_CONST | op::SYNTHETIC_LOCAL_SETI64_CONST => {
- let val = builder.ins().iconst(types::I64, insn.imm1);
- write_local_inline!(builder, insn.imm2, val);
- }
-
- op::SYNTHETIC_I32_ADD2LOCAL => {
- let r1 = read_local_inline!(builder, insn.imm1);
- let v1 = builder.ins().ireduce(types::I32, r1);
- let r2 = read_local_inline!(builder, insn.imm2);
- let v2 = builder.ins().ireduce(types::I32, r2);
- let result = builder.ins().iadd(v1, v2);
- let result = builder.ins().sextend(types::I64, result);
- write_dst!(builder, insn.destination, result);
- }
-
- op::SYNTHETIC_I32_ADDCONSTLOCAL => {
- let r = read_local_inline!(builder, insn.imm2);
- let v = builder.ins().ireduce(types::I32, r);
- let k = builder.ins().iconst(types::I32, insn.imm1);
- let result = builder.ins().iadd(v, k);
- let result = builder.ins().sextend(types::I64, result);
- write_dst!(builder, insn.destination, result);
- }
-
- op::SYNTHETIC_I32_ANDCONSTLOCAL => {
- let r = read_local_inline!(builder, insn.imm2);
- let v = builder.ins().ireduce(types::I32, r);
- let k = builder.ins().iconst(types::I32, insn.imm1);
- let result = builder.ins().band(v, k);
- let result = builder.ins().sextend(types::I64, result);
- write_dst!(builder, insn.destination, result);
- }
-
- opc if (op::SYNTHETIC_I32_SUB2LOCAL..=op::SYNTHETIC_I32_SHRS2LOCAL).contains(&opc) => {
- let r1 = read_local_inline!(builder, insn.imm1);
- let v1 = builder.ins().ireduce(types::I32, r1);
- let r2 = read_local_inline!(builder, insn.imm2);
- let v2 = builder.ins().ireduce(types::I32, r2);
- let result = match opc {
- op::SYNTHETIC_I32_SUB2LOCAL => builder.ins().isub(v1, v2),
- op::SYNTHETIC_I32_MUL2LOCAL => builder.ins().imul(v1, v2),
- op::SYNTHETIC_I32_AND2LOCAL => builder.ins().band(v1, v2),
- op::SYNTHETIC_I32_OR2LOCAL => builder.ins().bor(v1, v2),
- op::SYNTHETIC_I32_XOR2LOCAL => builder.ins().bxor(v1, v2),
- op::SYNTHETIC_I32_SHL2LOCAL => builder.ins().ishl(v1, v2),
- op::SYNTHETIC_I32_SHRU2LOCAL => builder.ins().ushr(v1, v2),
- op::SYNTHETIC_I32_SHRS2LOCAL => builder.ins().sshr(v1, v2),
- _ => unreachable!(),
- };
- let result = builder.ins().sextend(types::I64, result);
- write_dst!(builder, insn.destination, result);
- }
-
- op::SYNTHETIC_I64_ADD2LOCAL => {
- let v1 = read_local_inline!(builder, insn.imm1);
- let v2 = read_local_inline!(builder, insn.imm2);
- let result = builder.ins().iadd(v1, v2);
- write_dst!(builder, insn.destination, result);
- }
- op::SYNTHETIC_I64_ADDCONSTLOCAL => {
- let v = read_local_inline!(builder, insn.imm2);
- let k = builder.ins().iconst(types::I64, insn.imm1);
- let result = builder.ins().iadd(v, k);
- write_dst!(builder, insn.destination, result);
- }
- op::SYNTHETIC_I64_ANDCONSTLOCAL => {
- let v = read_local_inline!(builder, insn.imm2);
- let k = builder.ins().iconst(types::I64, insn.imm1);
- let result = builder.ins().band(v, k);
- write_dst!(builder, insn.destination, result);
- }
- opc if (op::SYNTHETIC_I64_SUB2LOCAL..=op::SYNTHETIC_I64_SHRS2LOCAL).contains(&opc) => {
- let v1 = read_local_inline!(builder, insn.imm1);
- let v2 = read_local_inline!(builder, insn.imm2);
- let result = match opc {
- op::SYNTHETIC_I64_SUB2LOCAL => builder.ins().isub(v1, v2),
- op::SYNTHETIC_I64_MUL2LOCAL => builder.ins().imul(v1, v2),
- op::SYNTHETIC_I64_AND2LOCAL => builder.ins().band(v1, v2),
- op::SYNTHETIC_I64_OR2LOCAL => builder.ins().bor(v1, v2),
- op::SYNTHETIC_I64_XOR2LOCAL => builder.ins().bxor(v1, v2),
- op::SYNTHETIC_I64_SHL2LOCAL => builder.ins().ishl(v1, v2),
- op::SYNTHETIC_I64_SHRU2LOCAL => builder.ins().ushr(v1, v2),
- op::SYNTHETIC_I64_SHRS2LOCAL => builder.ins().sshr(v1, v2),
- _ => unreachable!(),
- };
- write_dst!(builder, insn.destination, result);
- }
-
- op::SYNTHETIC_I32_STORELOCAL | op::SYNTHETIC_I64_STORELOCAL => {
- let base_raw = read_src!(builder, insn.sources[0]);
- let val = read_local_inline!(builder, insn.imm2);
- let base_u32 = builder.ins().ireduce(types::I32, base_raw);
- let base_u64 = builder.ins().uextend(types::I64, base_u32);
- let offset = builder.ins().iconst(types::I64, insn.imm1);
- let addr = builder.ins().iadd(base_u64, offset);
-
- let mem_idx = insn.imm3;
- let address = inline_memory_address!(builder, mem_idx, addr);
- let value = if opc == op::SYNTHETIC_I32_STORELOCAL {
- builder.ins().ireduce(types::I32, val)
- } else {
- val
- };
- builder.ins().store(wasm_memory_flags, value, address, 0);
- }
-
- op::SYNTHETIC_TIER_UP => {
- if let Some(tail) = tier_up_dispatch_tail {
- let header = control_stack
- .last()
- .expect("tier-up checkpoint must be inside a loop")
- .branch_target;
- let next_tail = builder.create_block();
- builder.switch_to_block(tail);
- let matches = builder.ins().icmp_imm_s(IntCC::Equal, tier_up_target_ip, insn.imm1);
- builder.ins().brif(matches, header, &[], next_tail, &[]);
- builder.seal_block(tail);
- tier_up_dispatch_tail = Some(next_tail);
- builder.switch_to_block(header);
- // The tier-up dispatch jumps straight into this header with regs loaded from config (i64 bank),
- // so we can't trust any F32/F64 vars to survive across this jump.
- reset_banks!();
- }
- }
-
- _ => {
- return Err("unsupported instruction during codegen");
- }
- }
-
- ip += 1;
- }
-
- // If we fell through without hitting end, sync all results and head to the epilogue.
- if !is_unreachable {
- push_top_n_to_real!(builder, result_arity);
- builder.ins().jump(epilogue_block, &[]);
- }
-
- if let Some(tail) = tier_up_dispatch_tail {
- let body_start = tier_up_body_start.expect("tier_up_body_start set when dispatch tail exists");
- builder.switch_to_block(tail);
- builder.ins().jump(body_start, &[]);
- builder.seal_block(tail);
- builder.seal_block(body_start);
- }
-
- builder.switch_to_block(trap_block);
- builder.seal_block(trap_block);
- // The helper already set the trap for us.
- let trap_ret = builder.ins().iconst(types::I64, outcome_return_value as i64);
- builder.ins().return_(&[trap_ret]);
-
- builder.switch_to_block(epilogue_block);
- builder.seal_block(epilogue_block);
- // Clean up excess values on the real stack (e.g. from BR out of nested blocks); nothing to touch if we have vstack info.
- if has_raw_call {
- let init_size = builder.use_var(initial_stack_size_var);
- emit_stack_cleanup!(builder, init_size, result_arity);
- }
- Self::sync_regs_to_config(
- &mut builder,
- &reg_vars,
- config_var,
- regs_offset,
- value_size,
- &dirty_regs,
- );
- flush_locals!(builder);
- let ret_val = builder.ins().iconst(types::I64, outcome_return_value as i64);
- builder.ins().return_(&[ret_val]);
-
- builder.finalize(isa.frontend_config());
-
- let mut ctx = Context::for_function(func);
- // Snapshot the code bytes + raw reloc list before we drop the borrow on ctx so we
- // can map UserExternalNameRefs back to helper ids via ctx.func.params below.
- let (bytes, raw_relocs, traps) = {
- let code = ctx
- .compile(&*isa, &mut Default::default())
- .map_err(|_| "cranelift compilation failed")?;
- let traps = code
- .buffer
- .traps()
- .iter()
- .map(|trap| CraneliftTrap {
- offset: trap.offset,
- code: trap.code.as_raw().get(),
- _padding: [0; 3],
- })
- .collect();
- let bytes = code.code_buffer().to_vec();
- let raw = code.buffer.relocs().to_vec();
- (bytes, raw, traps)
- };
-
- let mut relocs: Vec<HelperReloc> = Vec::with_capacity(raw_relocs.len());
- let user_names = ctx.func.params.user_named_funcs();
- for r in &raw_relocs {
- // We only ever ask cranelift to relocate helper-function addresses, so any
- // other reloc means it lowered something we didn't expect -- bail rather than
- // produce machine code that the cache layer can't faithfully reproduce.
- if r.kind != Reloc::Abs8 {
- return Err("unexpected non-Abs8 relocation");
- }
- let name = match &r.target {
- FinalizedRelocTarget::ExternalName(ExternalName::User(user_ref)) => &user_names[*user_ref],
- _ => return Err("unexpected relocation target"),
- };
- if name.namespace != 0 || name.index >= crate::HELPER_COUNT {
- return Err("relocation refers to an unknown helper id");
- }
- relocs.push(HelperReloc {
- code_offset: r.offset,
- helper_id: name.index,
- addend: r.addend,
- });
- }
-
- Ok(CompiledFunction {
- code: bytes,
- relocs,
- traps,
- })
- }
-
- fn is_supported(insn: &CraneliftInsn) -> bool {
- let opc = insn.opcode;
- matches!(
- opc,
- op::NOP
- | op::UNREACHABLE
- | op::BLOCK
- | op::LOOP
- | op::IF
- | op::ELSE
- | op::END
- | op::BR
- | op::BR_IF
- | op::BR_TABLE
- | op::RETURN
- | op::CALL
- | op::DROP
- | op::SELECT
- | op::SELECT_TYPED
- | op::LOCAL_GET
- | op::LOCAL_SET
- | op::LOCAL_TEE
- | op::GLOBAL_GET
- | op::GLOBAL_SET
- | op::I32_CONST
- | op::I64_CONST
- | op::F32_CONST
- | op::F64_CONST
- | op::I32_EQZ..=op::I32_GEU
- | op::I64_EQZ..=op::I64_GEU
- | op::F32_EQ..=op::F64_GE
- | op::I32_CLZ..=op::I32_ROTR
- | op::I64_CLZ..=op::I64_ROTR
- | op::F32_ABS..=op::F32_COPYSIGN
- | op::F64_ABS..=op::F64_COPYSIGN
- | op::I32_WRAP_I64..=op::F64_REINTERPRET_I64
- | op::I32_EXTEND8_S..=op::I64_EXTEND32_S
- | op::I32_LOAD..=op::I64_STORE32
- | op::MEMORY_SIZE
- | op::MEMORY_GROW
- | op::CALL_INDIRECT
- | op::I32_TRUNC_SAT_F32_S..=op::I64_TRUNC_SAT_F64_U
- | op::MEMORY_COPY
- | op::MEMORY_FILL
- | op::SYNTHETIC_END_EXPRESSION
- | op::SYNTHETIC_LOCAL_GET_0..=op::SYNTHETIC_LOCAL_GET_7
- | op::SYNTHETIC_LOCAL_SET_0..=op::SYNTHETIC_LOCAL_SET_7
- | op::SYNTHETIC_LOCAL_COPY
- | op::SYNTHETIC_BR_NOSTACK
- | op::SYNTHETIC_BR_IF_NOSTACK
- | op::SYNTHETIC_CALL_00..=op::SYNTHETIC_CALL_31
- | op::SYNTHETIC_I32_ADD2LOCAL..=op::SYNTHETIC_I32_ANDCONSTLOCAL
- | op::SYNTHETIC_I32_STORELOCAL
- | op::SYNTHETIC_LOCAL_SETI32_CONST
- | op::SYNTHETIC_CALL_WITH_RECORD_0
- | op::SYNTHETIC_CALL_WITH_RECORD_1
- | op::SYNTHETIC_ARGUMENT_GET
- | op::SYNTHETIC_ARGUMENT_SET
- | op::SYNTHETIC_ARGUMENT_TEE
- | op::SYNTHETIC_I32_SUB2LOCAL..=op::SYNTHETIC_I32_SHRS2LOCAL
- | op::SYNTHETIC_I64_ADD2LOCAL..=op::SYNTHETIC_LOCAL_SETI64_CONST
- | op::SYNTHETIC_BR_TABLE_CONT
- | op::SYNTHETIC_TIER_UP
- )
- }
-
- fn sync_regs_to_config(
- builder: &mut FunctionBuilder,
- reg_vars: &[Variable; REG_COUNT],
- config_var: Variable,
- regs_offset: i32,
- value_size: i32,
- dirty: &[bool; REG_COUNT],
- ) {
- let config = builder.use_var(config_var);
- for i in 0..REG_COUNT {
- if !dirty[i] {
- continue;
- }
- let val = builder.use_var(reg_vars[i]);
- let offset = regs_offset + (i as i32) * value_size;
- builder.ins().store(MemFlagsData::trusted(), val, config, offset);
- let zero = builder.ins().iconst(types::I64, 0);
- builder.ins().store(MemFlagsData::trusted(), zero, config, offset + 8);
- }
- }
-}
diff --git a/Libraries/LibWasm/Rust/src/lib.rs b/Libraries/LibWasm/Rust/src/lib.rs
deleted file mode 100644
index 95558bbdfe5..00000000000
--- a/Libraries/LibWasm/Rust/src/lib.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-pub mod compiler;
-pub mod serialized;
-
-use compiler::CraneliftCompiler;
-
-/// Immediates:
-/// constants: imm1 = value (i32 sign-extended, i64, or f32/f64 bits)
-/// local ops: imm1 = local index
-/// global ops: imm1 = global index
-/// branch: imm1 = label index (from control stack)
-/// block/loop: imm1 = end_ip, imm2 = else_ip (-1 if none), imm3 = arity | (param_count << 16)
-/// call: imm1 = function index
-/// memory ops: imm1 = offset, imm3 = memory index
-#[repr(C)]
-#[derive(Clone, Copy, Debug)]
-pub struct CraneliftInsn {
- pub opcode: u64,
- pub sources: [u8; 3],
- pub destination: u8,
- pub imm1: i64,
- pub imm2: i64,
- pub imm3: u32,
- pub _pad: u32,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy, Debug)]
-pub struct RuntimeLayout {
- pub regs_offset: u32,
- pub value_size: u32,
- pub locals_base_offset: u32,
- pub memory_instances_offset: u32,
- pub global_instances_offset: u32,
- pub global_instance_value_offset: u32,
- pub memory_instance_data_offset: u32,
- pub memory_buffer_storage_offset_offset: u32,
- pub compiled_call_result_scratch_offset: u32,
- pub value_stack_base_offset: u32,
- pub value_stack_top_offset: u32,
- pub call_record_base_offset: u32,
-}
-
-/// Stable index assigned to each runtime helper. Embedded in cranelift `ExternalName`
-/// entries so we can recover, post-codegen, which helper a given relocation targets.
-/// The numeric values are part of the cache blob format -- do NOT reorder.
-#[repr(u32)]
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[allow(non_camel_case_types)]
-pub enum HelperId {
- call_function = 0,
- set_trap = 1,
- memory_size = 2,
- memory_grow = 3,
- call_with_record = 4,
- direct_call_0 = 5,
- direct_call_1 = 6,
- direct_call_2 = 7,
- direct_call_3 = 8,
- call_indirect = 9,
- memory_copy = 10,
- memory_fill = 11,
- primitive_storage_cage_base = 12,
-}
-
-pub const HELPER_COUNT: u32 = 13;
-pub const SERIALIZED_CODE_ALIGNMENT: usize = 16;
-
-/// One relocation slot in the generated machine code. `code_offset` is the byte offset
-/// from the start of the function where 8 contiguous bytes hold the absolute helper
-/// address; on cache install, those bytes get rewritten to the current process's
-/// helper pointer.
-#[repr(C)]
-#[derive(Clone, Copy, Debug)]
-pub struct HelperReloc {
- pub code_offset: u32,
- pub helper_id: u32,
- pub addend: i64,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy, Debug)]
-pub struct CraneliftTrap {
- pub offset: u32,
- pub code: u8,
- pub _padding: [u8; 3],
-}
-
-/// Output of `compile_to_bytes`: the machine code plus the patch table.
-pub struct CompiledFunction {
- pub code: Vec<u8>,
- pub relocs: Vec<HelperReloc>,
- pub traps: Vec<CraneliftTrap>,
-}
-
-pub fn compile_to_bytes(
- insns: &[CraneliftInsn],
- layout: &RuntimeLayout,
- outcome_return_value: u64,
- result_arity: u32,
- num_locals: u32,
- num_params: u32,
- local_types: &[u8],
-) -> Result<CompiledFunction, &'static str> {
- CraneliftCompiler::compile_to_bytes(
- insns,
- layout,
- outcome_return_value,
- result_arity,
- num_locals,
- num_params,
- local_types,
- )
-}
diff --git a/Libraries/LibWasm/Rust/src/serialized.rs b/Libraries/LibWasm/Rust/src/serialized.rs
deleted file mode 100644
index b644e2cbf71..00000000000
--- a/Libraries/LibWasm/Rust/src/serialized.rs
+++ /dev/null
@@ -1,521 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use crate::CompiledFunction;
-use crate::CraneliftInsn;
-use crate::CraneliftTrap;
-use crate::HelperReloc;
-use crate::RuntimeLayout;
-use crate::SERIALIZED_CODE_ALIGNMENT;
-use crate::compile_to_bytes;
-use std::mem::align_of;
-use std::mem::size_of;
-use std::mem::size_of_val;
-
-#[repr(C)]
-#[derive(Clone, Copy)]
-struct InputHeader {
- function_count: u32,
- layout_offset: u32,
- outcome_return: u64,
- output_size: u64,
- total_size: u64,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy)]
-struct InputFunctionEntry {
- insn_offset: u32,
- insn_count: u32,
- result_arity: u32,
- num_locals: u32,
- locals_offset: u32,
- num_params: u32,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy)]
-struct OutputHeader {
- function_count: u32,
- _pad: u32,
- code_base_offset: u64,
- reloc_region_start: u64,
- total_size: u64,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy, Default)]
-struct OutputFunctionEntry {
- code_offset: u64,
- code_size: u32,
- compiled: u32,
- reloc_offset: u64,
- reloc_count: u32,
- _padding_after_reloc_count: u32,
- trap_offset: u64,
- trap_count: u32,
- _padding: u32,
-}
-
-fn align_up(value: usize, alignment: usize) -> Result<usize, &'static str> {
- value.checked_next_multiple_of(alignment).ok_or("alignment overflow")
-}
-
-fn as_bytes_slice<T>(value: &[T]) -> &[u8] {
- unsafe { ak::slice_from_raw_parts(value.as_ptr().cast::<u8>(), size_of_val(value)) }
-}
-
-fn read_pod<T: Copy>(base: &[u8], offset: usize) -> Result<T, &'static str> {
- let end = offset.checked_add(size_of::<T>()).ok_or("overflow")?;
- let bytes = base.get(offset..end).ok_or("out of bounds read")?;
- Ok(unsafe { (bytes.as_ptr().cast::<T>()).read_unaligned() })
-}
-
-fn parse_input(
- input: &[u8],
- output_size: usize,
-) -> Result<(InputHeader, Vec<InputFunctionEntry>, RuntimeLayout), &'static str> {
- let header: InputHeader = read_pod(input, 0)?;
- if usize::try_from(header.total_size).map_err(|_| "total_size overflow")? != input.len() {
- return Err("input buffer size mismatch");
- }
- if usize::try_from(header.output_size).map_err(|_| "output_size overflow")? != output_size {
- return Err("output buffer size mismatch");
- }
-
- let func_count = usize::try_from(header.function_count).map_err(|_| "function_count overflow")?;
- let entries_offset = size_of::<InputHeader>();
- let entries_size = func_count
- .checked_mul(size_of::<InputFunctionEntry>())
- .ok_or("input entries size overflow")?;
- let entries_end = entries_offset
- .checked_add(entries_size)
- .ok_or("input entries size overflow")?;
- if entries_end > input.len() {
- return Err("input entries are truncated");
- }
-
- let mut entries = Vec::with_capacity(func_count);
- let mut total_insn_count = 0usize;
- let mut total_locals_size = 0usize;
- for i in 0..func_count {
- let entry_offset = i
- .checked_mul(size_of::<InputFunctionEntry>())
- .and_then(|offset| entries_offset.checked_add(offset))
- .ok_or("input entry offset overflow")?;
- let entry: InputFunctionEntry = read_pod(input, entry_offset)?;
- total_insn_count = total_insn_count
- .checked_add(entry.insn_count as usize)
- .ok_or("instruction count overflow")?;
- total_locals_size = total_locals_size
- .checked_add(entry.num_locals as usize)
- .ok_or("locals size overflow")?;
- entries.push(entry);
- }
-
- let insn_region_offset = align_up(entries_end, align_of::<CraneliftInsn>())?;
- let insn_region_size = total_insn_count
- .checked_mul(size_of::<CraneliftInsn>())
- .ok_or("instruction region size overflow")?;
- let locals_region_offset = insn_region_offset
- .checked_add(insn_region_size)
- .ok_or("locals region offset overflow")?;
- let layout_offset = align_up(
- locals_region_offset
- .checked_add(total_locals_size)
- .ok_or("layout offset overflow")?,
- align_of::<RuntimeLayout>(),
- )?;
- let expected_size = layout_offset
- .checked_add(size_of::<RuntimeLayout>())
- .ok_or("input size overflow")?;
- if expected_size != input.len()
- || usize::try_from(header.layout_offset).map_err(|_| "layout_offset overflow")? != layout_offset
- {
- return Err("input regions are not canonical");
- }
-
- let mut insn_cursor = insn_region_offset;
- let mut locals_cursor = locals_region_offset;
- for entry in &entries {
- if entry.insn_offset as usize != insn_cursor || entry.locals_offset as usize != locals_cursor {
- return Err("input regions are not canonical");
- }
- insn_cursor = insn_cursor
- .checked_add(
- (entry.insn_count as usize)
- .checked_mul(size_of::<CraneliftInsn>())
- .ok_or("instruction region size overflow")?,
- )
- .ok_or("instruction region offset overflow")?;
- locals_cursor = locals_cursor
- .checked_add(entry.num_locals as usize)
- .ok_or("locals region offset overflow")?;
- }
-
- let layout = read_pod(input, layout_offset)?;
- Ok((header, entries, layout))
-}
-
-fn select_compiled_functions(
- compiled_chunks: Vec<Vec<(usize, CompiledFunction)>>,
- code_base_offset: usize,
- output_size: usize,
-) -> (Vec<(usize, CompiledFunction)>, usize, usize) {
- let mut compiled_functions = Vec::new();
- let mut code_size = 0usize;
- let mut reloc_size = 0usize;
- for (index, compiled) in compiled_chunks.into_iter().flatten() {
- let Some(aligned_code_size) = align_up(compiled.code.len(), SERIALIZED_CODE_ALIGNMENT).ok() else {
- continue;
- };
- let Some(function_reloc_size) = compiled
- .relocs
- .len()
- .checked_mul(size_of::<HelperReloc>())
- .and_then(|size| {
- compiled
- .traps
- .len()
- .checked_mul(size_of::<CraneliftTrap>())
- .and_then(|trap_size| size.checked_add(trap_size))
- })
- else {
- continue;
- };
- let Some(candidate_code_size) = code_size.checked_add(aligned_code_size) else {
- continue;
- };
- let Some(candidate_reloc_size) = reloc_size.checked_add(function_reloc_size) else {
- continue;
- };
- let Some(candidate_total_size) = code_base_offset
- .checked_add(candidate_code_size)
- .and_then(|offset| align_up(offset, align_of::<HelperReloc>()).ok())
- .and_then(|offset| offset.checked_add(candidate_reloc_size))
- else {
- continue;
- };
- if candidate_total_size > output_size {
- continue;
- }
-
- code_size = candidate_code_size;
- reloc_size = candidate_reloc_size;
- compiled_functions.push((index, compiled));
- }
-
- (compiled_functions, code_size, reloc_size)
-}
-
-pub fn compile_serialized_buffer(input: &[u8], output: &mut [u8]) -> Result<usize, &'static str> {
- let (header, entries, layout) = parse_input(input, output.len())?;
- let func_count = usize::try_from(header.function_count).map_err(|_| "function_count overflow")?;
-
- let thread_count = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(1)
- .max(1);
- let chunk_size = func_count.div_ceil(thread_count.max(1));
- let mapped_ref: &[u8] = input;
- let layout_ref = &layout;
- let outcome_return = header.outcome_return;
-
- // Compile into temporary per-function allocations first so the serialized
- // output contains only bytes that Cranelift actually produced.
- let compiled_chunks = std::thread::scope(|scope| {
- let mut handles = Vec::with_capacity(thread_count);
- for chunk_idx in 0..thread_count {
- let start = chunk_idx * chunk_size;
- if start >= func_count {
- break;
- }
- let end = (start + chunk_size).min(func_count);
- let chunk_entries = &entries[start..end];
- handles.push(scope.spawn(move || {
- let mut out: Vec<(usize, CompiledFunction)> = Vec::with_capacity(end - start);
- for (offset_in_chunk, entry) in chunk_entries.iter().enumerate() {
- let i = start + offset_in_chunk;
- if entry.insn_count == 0 {
- continue;
- }
- let Ok(insn_offset) = usize::try_from(entry.insn_offset) else {
- continue;
- };
- let insn_count = entry.insn_count as usize;
- let Some(insn_bytes_len) = insn_count.checked_mul(size_of::<CraneliftInsn>()) else {
- continue;
- };
- let Some(insn_end) = insn_offset.checked_add(insn_bytes_len) else {
- continue;
- };
- let Some(insn_bytes) = mapped_ref.get(insn_offset..insn_end) else {
- continue;
- };
- if insn_offset % align_of::<CraneliftInsn>() != 0 {
- continue;
- }
- let (prefix, insns, suffix) = unsafe { insn_bytes.align_to::<CraneliftInsn>() };
- if !prefix.is_empty() || !suffix.is_empty() || insns.len() != insn_count {
- continue;
- }
- let num_locals = entry.num_locals as usize;
- let local_types = usize::try_from(entry.locals_offset)
- .ok()
- .and_then(|offset| offset.checked_add(num_locals).map(|end| (offset, end)))
- .and_then(|(offset, end)| mapped_ref.get(offset..end))
- .unwrap_or(&[]);
- if let Ok(compiled) = compile_to_bytes(
- insns,
- layout_ref,
- outcome_return,
- entry.result_arity,
- entry.num_locals,
- entry.num_params,
- local_types,
- ) {
- out.push((i, compiled));
- }
- }
- out
- }));
- }
- handles
- .into_iter()
- .map(|handle| handle.join().map_err(|_| "compiler worker panicked"))
- .collect::<Result<Vec<_>, _>>()
- })?;
-
- // Pack the results as a header and function table followed by compact code
- // and relocation regions.
- let out_entries_offset = size_of::<OutputHeader>();
- let output_entries_size = func_count
- .checked_mul(size_of::<OutputFunctionEntry>())
- .ok_or("output entries size overflow")?;
- let code_base_offset = align_up(
- out_entries_offset
- .checked_add(output_entries_size)
- .ok_or("code base offset overflow")?,
- SERIALIZED_CODE_ALIGNMENT,
- )?;
-
- if code_base_offset > output.len() {
- return Err("output metadata out of bounds");
- }
-
- // Keep the successfully compiled functions that fit in the supplied output
- // buffer. A single unusually code-dense function should fall back to the
- // interpreter without discarding the rest of the batch.
- let (compiled_functions, code_size, reloc_size) =
- select_compiled_functions(compiled_chunks, code_base_offset, output.len());
-
- let reloc_region_start = align_up(
- code_base_offset
- .checked_add(code_size)
- .ok_or("relocation region offset overflow")?,
- align_of::<HelperReloc>(),
- )?;
- let total_size = reloc_region_start
- .checked_add(reloc_size)
- .ok_or("output size overflow")?;
- debug_assert!(total_size <= output.len());
-
- output
- .get_mut(0..code_base_offset)
- .ok_or("output metadata out of bounds")?
- .fill(0);
- let output_header = OutputHeader {
- function_count: header.function_count,
- _pad: 0,
- code_base_offset: u64::try_from(code_base_offset).map_err(|_| "code base offset overflow")?,
- reloc_region_start: u64::try_from(reloc_region_start).map_err(|_| "relocation region offset overflow")?,
- total_size: u64::try_from(total_size).map_err(|_| "output size overflow")?,
- };
- let output_header_bytes = as_bytes_slice(std::slice::from_ref(&output_header));
- output
- .get_mut(0..output_header_bytes.len())
- .ok_or("output header out of bounds")?
- .copy_from_slice(output_header_bytes);
-
- let mut code_cursor = 0usize;
- let mut reloc_cursor = 0usize;
- for (i, compiled) in compiled_functions {
- let code = compiled.code;
- let relocs = compiled.relocs;
- let traps = compiled.traps;
- let aligned = align_up(code.len(), SERIALIZED_CODE_ALIGNMENT).map_err(|_| "code alignment overflow")?;
- let reloc_bytes_len = relocs
- .len()
- .checked_mul(size_of::<HelperReloc>())
- .ok_or("relocation size overflow")?;
- let trap_bytes_len = traps
- .len()
- .checked_mul(size_of::<CraneliftTrap>())
- .ok_or("trap size overflow")?;
- let Some(code_end) = code_cursor.checked_add(aligned) else {
- continue;
- };
- if code_end > code_size {
- continue;
- }
- let Some(reloc_end) = reloc_cursor
- .checked_add(reloc_bytes_len)
- .and_then(|end| end.checked_add(trap_bytes_len))
- else {
- continue;
- };
- if reloc_end > reloc_size {
- continue;
- }
- let code_offset = code_cursor;
- let code_dst = code_base_offset
- .checked_add(code_offset)
- .ok_or("code destination overflow")?;
- let code_dst_end = code_dst.checked_add(code.len()).ok_or("code destination overflow")?;
- output
- .get_mut(code_dst..code_dst_end)
- .ok_or("code destination out of bounds")?
- .copy_from_slice(&code);
-
- let reloc_offset = reloc_cursor;
- if !relocs.is_empty() {
- let reloc_dst = reloc_region_start
- .checked_add(reloc_offset)
- .ok_or("relocation destination overflow")?;
- let reloc_dst_end = reloc_dst
- .checked_add(reloc_bytes_len)
- .ok_or("relocation destination overflow")?;
- output
- .get_mut(reloc_dst..reloc_dst_end)
- .ok_or("relocation destination out of bounds")?
- .copy_from_slice(as_bytes_slice(&relocs));
- }
-
- let trap_offset = reloc_cursor
- .checked_add(reloc_bytes_len)
- .ok_or("trap offset overflow")?;
- if !traps.is_empty() {
- let trap_dst = reloc_region_start
- .checked_add(trap_offset)
- .ok_or("trap destination overflow")?;
- let trap_dst_end = trap_dst
- .checked_add(trap_bytes_len)
- .ok_or("trap destination overflow")?;
- output
- .get_mut(trap_dst..trap_dst_end)
- .ok_or("trap destination out of bounds")?
- .copy_from_slice(as_bytes_slice(&traps));
- }
-
- let entry = OutputFunctionEntry {
- code_offset: u64::try_from(code_offset).map_err(|_| "code offset overflow")?,
- code_size: u32::try_from(code.len()).map_err(|_| "code size overflow")?,
- compiled: 1,
- reloc_offset: u64::try_from(reloc_offset).map_err(|_| "reloc offset overflow")?,
- reloc_count: u32::try_from(relocs.len()).map_err(|_| "reloc count overflow")?,
- _padding_after_reloc_count: 0,
- trap_offset: u64::try_from(trap_offset).map_err(|_| "trap offset overflow")?,
- trap_count: u32::try_from(traps.len()).map_err(|_| "trap count overflow")?,
- _padding: 0,
- };
- let entry_dst = i
- .checked_mul(size_of::<OutputFunctionEntry>())
- .and_then(|offset| out_entries_offset.checked_add(offset))
- .ok_or("output entry offset overflow")?;
- let entry_dst_end = entry_dst
- .checked_add(size_of::<OutputFunctionEntry>())
- .ok_or("output entry offset overflow")?;
- let entry_bytes = as_bytes_slice(std::slice::from_ref(&entry));
- output
- .get_mut(entry_dst..entry_dst_end)
- .ok_or("output entry out of bounds")?
- .copy_from_slice(entry_bytes);
-
- code_cursor = code_end;
- reloc_cursor = reloc_end;
- }
-
- Ok(total_size)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn output_function_entry_layout_has_no_implicit_padding() {
- assert_eq!(size_of::<OutputFunctionEntry>(), 48);
- assert_eq!(std::mem::offset_of!(OutputFunctionEntry, trap_offset), 32);
- }
-
- #[test]
- fn rejects_truncated_header() {
- assert_eq!(
- compile_serialized_buffer(&[], &mut []).unwrap_err(),
- "out of bounds read"
- );
- }
-
- #[test]
- fn rejects_buffer_size_mismatch() {
- let input = vec![0; size_of::<InputHeader>()];
- assert_eq!(
- compile_serialized_buffer(&input, &mut []).unwrap_err(),
- "input buffer size mismatch"
- );
- }
-
- #[test]
- fn rejects_function_count_larger_than_the_input() {
- let header = InputHeader {
- function_count: u32::MAX,
- layout_offset: 0,
- outcome_return: 0,
- output_size: 0,
- total_size: size_of::<InputHeader>() as u64,
- };
- let input = as_bytes_slice(std::slice::from_ref(&header));
- assert_eq!(
- compile_serialized_buffer(input, &mut []).unwrap_err(),
- "input entries are truncated"
- );
- }
-
- #[test]
- fn skips_only_compiled_functions_that_do_not_fit() {
- let compiled = vec![vec![
- (
- 0,
- CompiledFunction {
- code: vec![0; 16],
- relocs: vec![],
- traps: vec![],
- },
- ),
- (
- 1,
- CompiledFunction {
- code: vec![0; 64],
- relocs: vec![],
- traps: vec![],
- },
- ),
- (
- 2,
- CompiledFunction {
- code: vec![0; 16],
- relocs: vec![],
- traps: vec![],
- },
- ),
- ]];
-
- let (selected, code_size, reloc_size) = select_compiled_functions(compiled, 32, 64);
- assert_eq!(selected.iter().map(|(index, _)| *index).collect::<Vec<_>>(), vec![0, 2]);
- assert_eq!(code_size, 32);
- assert_eq!(reloc_size, 0);
- }
-}
diff --git a/Libraries/LibWasm/Tests/Executor/test-cranelift-global-access.js b/Libraries/LibWasm/Tests/Executor/test-cranelift-global-access.js
deleted file mode 100644
index a7d3ea77d32..00000000000
--- a/Libraries/LibWasm/Tests/Executor/test-cranelift-global-access.js
+++ /dev/null
@@ -1,42 +0,0 @@
-test("compiled global reads and writes directly access stable instances", () => {
- const globalsBinary = readBinaryWasmFile("Fixtures/Modules/cranelift-global-access.wasm");
- const calleeBinary = readBinaryWasmFile("Fixtures/Modules/cranelift-global-cross-module-callee.wasm");
- const callerBinary = readBinaryWasmFile("Fixtures/Modules/cranelift-global-cross-module-caller.wasm");
-
- const globals = parseWebAssemblyModule(globalsBinary);
- const callee = parseWebAssemblyModule(calleeBinary);
- const caller = parseWebAssemblyModule(callerBinary, { callee });
- const functions = [
- ["read_imported", globals, globals.getExport("read_imported")],
- ["i32_roundtrip", globals, globals.getExport("i32_roundtrip")],
- ["i64_roundtrip", globals, globals.getExport("i64_roundtrip")],
- ["f32_roundtrip", globals, globals.getExport("f32_roundtrip")],
- ["f64_roundtrip", globals, globals.getExport("f64_roundtrip")],
- ["increment_loop", globals, globals.getExport("increment_loop")],
- ["touch", callee, callee.getExport("touch")],
- ["read", callee, callee.getExport("read")],
- ["call_and_read", caller, caller.getExport("call_and_read")],
- ];
-
- if (functions.every(([, , fn]) => !isCraneliftEligible(fn))) return;
-
- for (const [name, , fn] of functions) {
- if (!isCraneliftEligible(fn)) throw new Error(`${name} is not Cranelift-eligible`);
- if (!isCraneliftCompiled(fn)) throw new Error(`${name} did not compile with Cranelift`);
- }
-
- expect(globals.invoke(functions[0][2], 0)).toBe(666);
- expect(globals.invoke(functions[1][2], 0x12345678)).toBe(0x12345678);
- expect(globals.invoke(functions[2][2], 0x123456789abcdefn)).toBe(0x123456789abcdefn);
- expect(globals.invoke(functions[3][2], 0x7fc12345)).toBe(0x7fc12345);
- expect(globals.invoke(functions[4][2], 0x7ff8123456789abcn)).toBe(0x7ff8123456789abcn);
- expect(globals.invoke(functions[5][2], 25)).toBe(25);
- expect(caller.invoke(functions[8][2])).toBe(42);
- expect(callee.invoke(functions[7][2])).toBe(99);
-
- const growthBinary = readBinaryWasmFile("Fixtures/Modules/global-storage-growth.wasm");
- for (let i = 0; i < 64; ++i) parseWebAssemblyModule(growthBinary);
-
- expect(globals.invoke(functions[1][2], 0x76543210)).toBe(0x76543210);
- expect(caller.invoke(functions[8][2])).toBe(42);
-});
diff --git a/Libraries/LibWasm/Tests/Executor/test-cranelift-multi-memory-access.js b/Libraries/LibWasm/Tests/Executor/test-cranelift-multi-memory-access.js
deleted file mode 100644
index 5354cb36ad4..00000000000
--- a/Libraries/LibWasm/Tests/Executor/test-cranelift-multi-memory-access.js
+++ /dev/null
@@ -1,31 +0,0 @@
-test("compiled loads and stores directly access every memory instance", () => {
- const binary = readBinaryWasmFile("Fixtures/Modules/cranelift-multi-memory-access.wasm");
- const module = parseWebAssemblyModule(binary);
- const roundtrip = module.getExport("roundtrip");
- const loadAt = module.getExport("load_at");
- const storeAt = module.getExport("store_at");
- const memoryOneIsDistinct = module.getExport("memory_one_is_distinct");
- const growAndRoundtrip = module.getExport("grow_and_roundtrip");
- const callGrowAndRoundtrip = module.getExport("call_grow_and_roundtrip");
- const functions = [roundtrip, loadAt, storeAt, memoryOneIsDistinct, growAndRoundtrip, callGrowAndRoundtrip];
-
- if (functions.every(fn => !isCraneliftEligible(fn))) return;
-
- for (const fn of functions) {
- expect(isCraneliftEligible(fn)).toBe(true);
- expect(isCraneliftCompiled(fn)).toBe(true);
- }
-
- expect(module.invoke(roundtrip, 0x12345678)).toBe(0x12345678);
- expect(module.invoke(memoryOneIsDistinct)).toBe(0);
- expect(() => module.invoke(loadAt, 65534)).toThrowWithMessage(
- TypeError,
- "Execution trapped: Memory access out of bounds"
- );
- expect(() => module.invoke(storeAt, 65534)).toThrowWithMessage(
- TypeError,
- "Execution trapped: Memory access out of bounds"
- );
- expect(module.invoke(growAndRoundtrip, 0x24681357)).toBe(0x24681357);
- expect(module.invoke(callGrowAndRoundtrip, 0x76543210)).toBe(0x76543210);
-});
diff --git a/Libraries/LibWasm/Tests/Executor/test-cranelift-default-memory-access.js b/Libraries/LibWasm/Tests/Executor/test-default-memory-access.js
similarity index 63%
rename from Libraries/LibWasm/Tests/Executor/test-cranelift-default-memory-access.js
rename to Libraries/LibWasm/Tests/Executor/test-default-memory-access.js
index 66e76eb09c2..5d41d0a0ebd 100644
--- a/Libraries/LibWasm/Tests/Executor/test-cranelift-default-memory-access.js
+++ b/Libraries/LibWasm/Tests/Executor/test-default-memory-access.js
@@ -1,4 +1,4 @@
-test("compiled default memory loads and stores use checked caged addresses", () => {
+test("default memory loads and stores trap past the end of the memory", () => {
// prettier-ignore
const binary = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60,
@@ -20,27 +20,6 @@ test("compiled default memory loads and stores use checked caged addresses", ()
const storeAt = module.getExport("store_at");
const loadMaxOffset = module.getExport("load_max_offset");
- const roundtripEligible = isCraneliftEligible(roundtrip);
- const loadAtEligible = isCraneliftEligible(loadAt);
- const storeAtEligible = isCraneliftEligible(storeAt);
- const loadMaxOffsetEligible = isCraneliftEligible(loadMaxOffset);
-
- if (!roundtripEligible && !loadAtEligible && !storeAtEligible && !loadMaxOffsetEligible) return;
-
- expect(roundtripEligible).toBe(true);
- expect(loadAtEligible).toBe(true);
- expect(storeAtEligible).toBe(true);
- expect(loadMaxOffsetEligible).toBe(true);
-
- const roundtripCompiled = isCraneliftCompiled(roundtrip);
- const loadAtCompiled = isCraneliftCompiled(loadAt);
- const storeAtCompiled = isCraneliftCompiled(storeAt);
- const loadMaxOffsetCompiled = isCraneliftCompiled(loadMaxOffset);
-
- expect(roundtripCompiled).toBe(true);
- expect(loadAtCompiled).toBe(true);
- expect(storeAtCompiled).toBe(true);
- expect(loadMaxOffsetCompiled).toBe(true);
expect(module.invoke(roundtrip, 0x12345678)).toBe(0x12345678);
expect(() => module.invoke(loadAt, 65534)).toThrowWithMessage(
TypeError,
diff --git a/Libraries/LibWasm/Tests/Executor/test-global-access.js b/Libraries/LibWasm/Tests/Executor/test-global-access.js
index 4f225bb053e..5f4119693f4 100644
--- a/Libraries/LibWasm/Tests/Executor/test-global-access.js
+++ b/Libraries/LibWasm/Tests/Executor/test-global-access.js
@@ -1,7 +1,7 @@
function loadGlobalModules() {
- const globalsBinary = readBinaryWasmFile("Fixtures/Modules/cranelift-global-access.wasm");
- const calleeBinary = readBinaryWasmFile("Fixtures/Modules/cranelift-global-cross-module-callee.wasm");
- const callerBinary = readBinaryWasmFile("Fixtures/Modules/cranelift-global-cross-module-caller.wasm");
+ const globalsBinary = readBinaryWasmFile("Fixtures/Modules/global-access.wasm");
+ const calleeBinary = readBinaryWasmFile("Fixtures/Modules/global-cross-module-callee.wasm");
+ const callerBinary = readBinaryWasmFile("Fixtures/Modules/global-cross-module-caller.wasm");
const globals = parseWebAssemblyModule(globalsBinary);
const callee = parseWebAssemblyModule(calleeBinary);
diff --git a/Libraries/LibWasm/Tests/Executor/test-inline-label-reservation.js b/Libraries/LibWasm/Tests/Executor/test-inline-label-reservation.js
index 5c55682fb98..73162965194 100644
--- a/Libraries/LibWasm/Tests/Executor/test-inline-label-reservation.js
+++ b/Libraries/LibWasm/Tests/Executor/test-inline-label-reservation.js
@@ -1,9 +1,5 @@
-test("inlining recomputes the frame's label reservation", () => {
- // $inlinee is spliced into $caller, so at the deepest point the label stack holds the caller's blocks
- // plus a wrapper block plus the inlinee's blocks — far more than the validator counted for $caller alone.
- // Labels are pushed unchecked, so without recomputing the reservation post-inlining this overflows the
- // frame's inline label storage and corrupts the adjacent frame stack. $caller returns two values to stay
- // on the interpreter path (and off Cranelift), which is what actually pushes the labels.
+test("blocks nested across calls", () => {
+ // At the deepest point, the blocks of $caller and of $inlinee, which it calls, are open together.
const bin = readBinaryWasmFile("Fixtures/Modules/inline-label-reservation.wasm");
const module = parseWebAssemblyModule(bin);
diff --git a/Libraries/LibWasm/Tests/Executor/test-multi-memory-access.js b/Libraries/LibWasm/Tests/Executor/test-multi-memory-access.js
index da764b57c2a..5b31f961001 100644
--- a/Libraries/LibWasm/Tests/Executor/test-multi-memory-access.js
+++ b/Libraries/LibWasm/Tests/Executor/test-multi-memory-access.js
@@ -1,5 +1,5 @@
test("multi-memory loads, stores, bounds checks, and growth remain interpreter-compatible", () => {
- const binary = readBinaryWasmFile("Fixtures/Modules/cranelift-multi-memory-access.wasm");
+ const binary = readBinaryWasmFile("Fixtures/Modules/multi-memory-access.wasm");
const module = parseWebAssemblyModule(binary);
const roundtrip = module.getExport("roundtrip");
const loadAt = module.getExport("load_at");
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-access.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/global-access.wasm
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-access.wasm
rename to Libraries/LibWasm/Tests/Fixtures/Modules/global-access.wasm
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-access.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/global-access.wat
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-access.wat
rename to Libraries/LibWasm/Tests/Fixtures/Modules/global-access.wat
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-callee.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-callee.wasm
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-callee.wasm
rename to Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-callee.wasm
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-callee.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-callee.wat
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-callee.wat
rename to Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-callee.wat
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-caller.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-caller.wasm
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-caller.wasm
rename to Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-caller.wasm
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-caller.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-caller.wat
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-global-cross-module-caller.wat
rename to Libraries/LibWasm/Tests/Fixtures/Modules/global-cross-module-caller.wat
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/inline-label-reservation.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/inline-label-reservation.wat
index be9c2fb8100..8c0dff5a00d 100644
--- a/Libraries/LibWasm/Tests/Fixtures/Modules/inline-label-reservation.wat
+++ b/Libraries/LibWasm/Tests/Fixtures/Modules/inline-label-reservation.wat
@@ -1,7 +1,5 @@
-;; The bytecode compiler inlines $inlinee into $caller, splicing the callee's blocks (plus a wrapper block) into the
-;; caller's instruction list. That pushes far more labels at run time than the validator counted for $caller alone, so
-;; the label reservation must be recomputed from the compiled instructions. $caller returns multiple values to keep it
-;; out of Cranelift and on the interpreter path that pushes labels.
+;; $caller nests blocks around calls to $inlinee, which nests blocks of its own, so the blocks open at the deepest point
+;; are many more than $caller has alone. $caller returns multiple values.
(module
(memory 1)
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-multi-memory-access.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/multi-memory-access.wasm
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-multi-memory-access.wasm
rename to Libraries/LibWasm/Tests/Fixtures/Modules/multi-memory-access.wasm
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-multi-memory-access.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/multi-memory-access.wat
similarity index 100%
rename from Libraries/LibWasm/Tests/Fixtures/Modules/cranelift-multi-memory-access.wat
rename to Libraries/LibWasm/Tests/Fixtures/Modules/multi-memory-access.wat
diff --git a/Libraries/LibWasm/TypeSystem.cpp b/Libraries/LibWasm/TypeSystem.cpp
deleted file mode 100644
index 71eb7278e69..00000000000
--- a/Libraries/LibWasm/TypeSystem.cpp
+++ /dev/null
@@ -1,551 +0,0 @@
-/*
- * Copyright (c) 2026, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/HashMap.h>
-#include <AK/Mutex.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/StringBuilder.h>
-#include <AK/kmalloc.h>
-#include <LibWasm/AbstractMachine/Validator.h>
-#include <LibWasm/TypeSystem.h>
-
-namespace Wasm {
-
-// https://webassembly.github.io/spec/core/valid/conventions.html#rolling-and-unrolling
-class TypeRegistry {
- AK_MAKE_NONCOPYABLE(TypeRegistry);
- AK_MAKE_NONMOVABLE(TypeRegistry);
-
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- static TypeRegistry& the()
- {
- // Defined types are deliberately immortal: they are the process-wide identities that
- // runtime values and compiled code point at.
- static TypeRegistry* registry = new TypeRegistry;
- return *registry;
- }
-
- DefinedType const* type_at(u32 registry_index)
- {
- MutexLocker locker(m_mutex);
- if (registry_index >= m_types.size())
- return nullptr;
- return m_types[registry_index].ptr();
- }
-
- ErrorOr<Vector<DefinedType const*>, ValidationError> intern_group(ReadonlySpan<TypeSection::Type> types, TypeSection::Type::RecGroupSpan group, ReadonlySpan<DefinedType const*> resolved_so_far);
-
-private:
- TypeRegistry() = default;
-
- Mutex m_mutex;
- Vector<NonnullOwnPtr<DefinedType>> m_types;
- HashMap<ByteString, u32> m_interned_groups; // group key -> index of first member
-};
-
-DefinedType const* TypeContext::resolve(TypeIndex index) const
-{
- if (types.is_empty())
- return TypeRegistry::the().type_at(index.value());
- if (index.value() >= types.size())
- return nullptr;
- return types[index.value()];
-}
-
-namespace {
-
-struct RolledTypeUse {
- enum class Form : u8 {
- Closed,
- Recursive,
- };
- Form form;
- u32 index; // registry index (Closed) or group-internal index (Recursive)
-};
-
-class GroupRoller {
-public:
- GroupRoller(TypeSection::Type::RecGroupSpan group, ReadonlySpan<DefinedType const*> resolved_so_far)
- : m_group(group)
- , m_resolved_so_far(resolved_so_far)
- {
- }
-
- // https://webassembly.github.io/spec/core/valid/conventions.html#aux-roll-rectype
- // roll_x(rectype) substitutes the type indices [x, x+n) with rec.i; anything below x must already be defined.
- ErrorOr<RolledTypeUse, ValidationError> roll(TypeIndex index) const
- {
- if (index.value() < m_group.first_type_index)
- return RolledTypeUse { RolledTypeUse::Form::Closed, m_resolved_so_far[index.value()]->registry_index() };
- if (index.value() < m_group.first_type_index + m_group.size)
- return RolledTypeUse { RolledTypeUse::Form::Recursive, index.value() - m_group.first_type_index };
- return ValidationError { ByteString::formatted("unknown type {} referenced from recursive type group", index.value()) };
- }
-
- ErrorOr<void, ValidationError> serialize(StringBuilder& builder, ValueType type) const
- {
- builder.append(static_cast<char>(type.kind()));
- builder.append(type.is_nullable() ? '\1' : '\0');
- if (type.is_typeuse()) {
- auto use = TRY(roll(type.unsafe_typeindex()));
- builder.append(use.form == RolledTypeUse::Form::Closed ? 'C' : 'R');
- builder.append(ReadonlyBytes { &use.index, sizeof(use.index) });
- }
- return {};
- }
-
- ErrorOr<void, ValidationError> serialize(StringBuilder& builder, FieldType const& field) const
- {
- TRY(serialize(builder, field.type()));
- builder.append(field.is_mutable() ? '\1' : '\0');
- return {};
- }
-
- ErrorOr<void, ValidationError> serialize(StringBuilder& builder, TypeSection::Type const& type) const
- {
- builder.append(type.is_final() ? '\1' : '\0');
- u32 supertype_count = type.supertypes().size();
- builder.append(ReadonlyBytes { &supertype_count, sizeof(supertype_count) });
- for (auto supertype : type.supertypes()) {
- auto use = TRY(roll(supertype));
- builder.append(use.form == RolledTypeUse::Form::Closed ? 'C' : 'R');
- builder.append(ReadonlyBytes { &use.index, sizeof(use.index) });
- }
-
- TRY(type.description().visit(
- [&](FunctionType const& function) -> ErrorOr<void, ValidationError> {
- builder.append('F');
- u32 count = function.parameters().size();
- builder.append(ReadonlyBytes { &count, sizeof(count) });
- for (auto& parameter : function.parameters())
- TRY(serialize(builder, parameter));
- count = function.results().size();
- builder.append(ReadonlyBytes { &count, sizeof(count) });
- for (auto& result : function.results())
- TRY(serialize(builder, result));
- return {};
- },
- [&](StructType const& struct_) -> ErrorOr<void, ValidationError> {
- builder.append('S');
- u32 count = struct_.fields().size();
- builder.append(ReadonlyBytes { &count, sizeof(count) });
- for (auto& field : struct_.fields())
- TRY(serialize(builder, field));
- return {};
- },
- [&](ArrayType const& array) -> ErrorOr<void, ValidationError> {
- builder.append('A');
- return serialize(builder, array.type());
- }));
- return {};
- }
-
- // https://webassembly.github.io/spec/core/valid/conventions.html#aux-unroll-rectype
- ErrorOr<ValueType, ValidationError> substituted(ValueType type, u32 group_base_registry_index) const
- {
- if (!type.is_typeuse())
- return type;
- auto use = TRY(roll(type.unsafe_typeindex()));
- auto registry_index = use.form == RolledTypeUse::Form::Closed ? use.index : group_base_registry_index + use.index;
- return ValueType(ValueType::TypeUseReference, TypeIndex(registry_index), type.is_nullable());
- }
-
- ErrorOr<TypeSection::Type, ValidationError> substituted(TypeSection::Type const& type, u32 group_base_registry_index) const
- {
- Vector<TypeIndex> supertypes;
- supertypes.ensure_capacity(type.supertypes().size());
- for (auto supertype : type.supertypes()) {
- auto use = TRY(roll(supertype));
- supertypes.append(TypeIndex(use.form == RolledTypeUse::Form::Closed ? use.index : group_base_registry_index + use.index));
- }
-
- auto composite = TRY(type.description().visit(
- [&](FunctionType const& function) -> ErrorOr<TypeSection::Type::CompositeType, ValidationError> {
- Vector<ValueType> parameters;
- parameters.ensure_capacity(function.parameters().size());
- for (auto& parameter : function.parameters())
- parameters.append(TRY(substituted(parameter, group_base_registry_index)));
- Vector<ValueType> results;
- results.ensure_capacity(function.results().size());
- for (auto& result : function.results())
- results.append(TRY(substituted(result, group_base_registry_index)));
- return TypeSection::Type::CompositeType { FunctionType { move(parameters), move(results) } };
- },
- [&](StructType const& struct_) -> ErrorOr<TypeSection::Type::CompositeType, ValidationError> {
- Vector<FieldType> fields;
- fields.ensure_capacity(struct_.fields().size());
- for (auto& field : struct_.fields())
- fields.append(FieldType { field.is_mutable(), TRY(substituted(field.type(), group_base_registry_index)) });
- return TypeSection::Type::CompositeType { StructType { move(fields) } };
- },
- [&](ArrayType const& array) -> ErrorOr<TypeSection::Type::CompositeType, ValidationError> {
- return TypeSection::Type::CompositeType { ArrayType { FieldType { array.type().is_mutable(), TRY(substituted(array.type().type(), group_base_registry_index)) } } };
- }));
-
- return TypeSection::Type { move(composite), move(supertypes), type.is_final() };
- }
-
-private:
- TypeSection::Type::RecGroupSpan m_group;
- ReadonlySpan<DefinedType const*> m_resolved_so_far;
-};
-
-}
-
-ErrorOr<Vector<DefinedType const*>, ValidationError> TypeRegistry::intern_group(ReadonlySpan<TypeSection::Type> types, TypeSection::Type::RecGroupSpan group, ReadonlySpan<DefinedType const*> resolved_so_far)
-{
- GroupRoller roller { group, resolved_so_far };
-
- StringBuilder key_builder;
- u32 group_size = group.size;
- key_builder.append(ReadonlyBytes { &group_size, sizeof(group_size) });
- for (size_t i = 0; i < group.size; ++i)
- TRY(roller.serialize(key_builder, types[group.first_type_index + i]));
- auto key = key_builder.to_byte_string();
-
- MutexLocker locker(m_mutex);
-
- Optional<u32> base_registry_index = m_interned_groups.get(key);
- if (!base_registry_index.has_value()) {
- auto base = static_cast<u32>(m_types.size());
- for (size_t i = 0; i < group.size; ++i) {
- auto sub_type = TRY(roller.substituted(types[group.first_type_index + i], base));
- sub_type.set_rec_group({ base, group.size });
- m_types.append(adopt_own(*new DefinedType(move(sub_type), base + i)));
- }
- for (size_t i = 0; i < group.size; ++i) {
- auto& defined_type = *m_types[base + i];
- if (!defined_type.m_sub_type.supertypes().is_empty()) {
- auto supertype_registry_index = defined_type.m_sub_type.supertypes().first().value();
- if (supertype_registry_index >= base + i)
- return ValidationError { ByteString::formatted("Invalid supertype {}, supertypes must precede their subtypes", supertype_registry_index) };
- defined_type.m_supertype = m_types[supertype_registry_index].ptr();
- defined_type.m_subtyping_depth = defined_type.m_supertype->m_subtyping_depth + 1;
- defined_type.m_ancestors.ensure_capacity(defined_type.m_subtyping_depth + 1);
- defined_type.m_ancestors.extend(defined_type.m_supertype->m_ancestors);
- }
- defined_type.m_ancestors.append(&defined_type);
- }
- m_interned_groups.set(move(key), base);
- base_registry_index = base;
- }
-
- Vector<DefinedType const*> result;
- result.ensure_capacity(group.size);
- for (size_t i = 0; i < group.size; ++i)
- result.append(m_types[*base_registry_index + i].ptr());
- return result;
-}
-
-// https://webassembly.github.io/spec/core/valid/modules.html#types
-ErrorOr<Vector<DefinedType const*>, ValidationError> canonicalize_module_types(TypeSection const& section)
-{
- Vector<DefinedType const*> resolved;
- resolved.ensure_capacity(section.types().size());
-
- for (size_t type_index = 0; type_index < section.types().size();) {
- auto group = section.types()[type_index].rec_group();
- if (group.first_type_index != type_index || group.first_type_index + group.size > section.types().size())
- return ValidationError { ByteString("malformed recursive type group spans"sv) };
- auto group_types = TRY(TypeRegistry::the().intern_group(section.types(), group, resolved));
- resolved.extend(move(group_types));
- type_index += group.size;
- }
-
- return resolved;
-}
-
-DefinedType const* canonicalize_type(TypeSection::Type const& type, TypeContext const& context)
-{
- Vector<TypeSection::Type> closed_types;
-
- Vector<TypeIndex> supertypes;
- for (auto supertype : type.supertypes()) {
- auto const* resolved = context.resolve(supertype);
- VERIFY(resolved);
- supertypes.append(TypeIndex(resolved->registry_index()));
- }
-
- auto close = [&](ValueType value_type) {
- return canonicalized(value_type, context);
- };
-
- auto composite = type.description().visit(
- [&](FunctionType const& function) -> TypeSection::Type::CompositeType {
- Vector<ValueType> parameters;
- for (auto& parameter : function.parameters())
- parameters.append(close(parameter));
- Vector<ValueType> results;
- for (auto& result : function.results())
- results.append(close(result));
- return FunctionType { move(parameters), move(results) };
- },
- [&](StructType const& struct_) -> TypeSection::Type::CompositeType {
- Vector<FieldType> fields;
- for (auto& field : struct_.fields())
- fields.append(FieldType { field.is_mutable(), close(field.type()) });
- return StructType { move(fields) };
- },
- [&](ArrayType const& array) -> TypeSection::Type::CompositeType {
- return ArrayType { FieldType { array.type().is_mutable(), close(array.type().type()) } };
- });
-
- closed_types.append(TypeSection::Type { move(composite), move(supertypes), type.is_final() });
- closed_types.first().set_rec_group({ 0, 1 });
-
- auto result = TypeRegistry::the().intern_group(closed_types.span(), { 0, 1 }, {});
- VERIFY(!result.is_error());
- return result.release_value().first();
-}
-
-ValueType canonicalized(ValueType type, TypeContext const& context)
-{
- if (!type.is_typeuse() || context.types.is_empty())
- return type;
- auto const* resolved = context.resolve(type.unsafe_typeindex());
- VERIFY(resolved);
- return ValueType(ValueType::TypeUseReference, TypeIndex(resolved->registry_index()), type.is_nullable());
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#defined-types
-bool matches_defined_type(DefinedType const& defined_type1, DefinedType const& defined_type2)
-{
- if (&defined_type1 == &defined_type2)
- return true;
- if (defined_type2.subtyping_depth() >= defined_type1.subtyping_depth())
- return false;
- return defined_type1.ancestors()[defined_type2.subtyping_depth()] == &defined_type2;
-}
-
-// https://webassembly.github.io/spec/core/syntax/types.html#heap-types
-ValueType::Kind top_of_heap_type(ValueType const& type, TypeContext const& context)
-{
- switch (type.kind()) {
- case ValueType::AnyReference:
- case ValueType::EqReference:
- case ValueType::I31Reference:
- case ValueType::StructReference:
- case ValueType::ArrayReference:
- case ValueType::NoneReference:
- return ValueType::AnyReference;
- case ValueType::FunctionReference:
- case ValueType::NoFunctionReference:
- return ValueType::FunctionReference;
- case ValueType::ExternReference:
- case ValueType::NoExternReference:
- return ValueType::ExternReference;
- case ValueType::ExceptionReference:
- case ValueType::NoExceptionReference:
- return ValueType::ExceptionReference;
- case ValueType::TypeUseReference: {
- auto const* defined_type = context.resolve(type.unsafe_typeindex());
- VERIFY(defined_type);
- return defined_type->expansion().visit(
- [](FunctionType const&) { return ValueType::FunctionReference; },
- [](StructType const&) { return ValueType::AnyReference; },
- [](ArrayType const&) { return ValueType::AnyReference; });
- }
- default:
- VERIFY_NOT_REACHED();
- }
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#heap-types
-bool matches_heap_type(ValueType const& heap_type1, ValueType const& heap_type2, TypeContext const& context)
-{
- VERIFY(heap_type1.is_reference() && heap_type2.is_reference());
-
- // The heap type heaptype_1 matches the heap type heaptype_2 if:
- // Either: The heap type heaptype_2 is of the form heaptype_1.
- if (heap_type1.kind() == heap_type2.kind()) {
- if (!heap_type1.is_typeuse())
- return true;
- auto const* defined_type1 = context.resolve(heap_type1.unsafe_typeindex());
- auto const* defined_type2 = context.resolve(heap_type2.unsafe_typeindex());
- VERIFY(defined_type1 && defined_type2);
- // Or: deftype_1 matches deftype_2.
- return matches_defined_type(*defined_type1, *defined_type2);
- }
-
- switch (heap_type1.kind()) {
- // Or: heaptype_1 is eq and heaptype_2 is any.
- case ValueType::EqReference:
- return heap_type2.kind() == ValueType::AnyReference;
- // Or: heaptype_1 is i31/struct/array and heaptype_2 is eq (or any, transitively).
- case ValueType::I31Reference:
- case ValueType::StructReference:
- case ValueType::ArrayReference:
- return heap_type2.kind() == ValueType::EqReference || heap_type2.kind() == ValueType::AnyReference;
- // Or: heaptype_1 is a defined type.
- case ValueType::TypeUseReference: {
- auto const* defined_type = context.resolve(heap_type1.unsafe_typeindex());
- VERIFY(defined_type);
- switch (heap_type2.kind()) {
- // ... and heaptype_2 is func and the expansion of deftype is (func t1* -> t2*).
- case ValueType::FunctionReference:
- return defined_type->expansion().has<FunctionType>();
- // ... and heaptype_2 is struct and the expansion of deftype is (struct fieldtype*).
- case ValueType::StructReference:
- return defined_type->expansion().has<StructType>();
- // ... and heaptype_2 is array and the expansion of deftype is (array fieldtype).
- case ValueType::ArrayReference:
- return defined_type->expansion().has<ArrayType>();
- // Transitively: deftype <= struct/array <= eq <= any.
- case ValueType::EqReference:
- case ValueType::AnyReference:
- return defined_type->expansion().has<StructType>() || defined_type->expansion().has<ArrayType>();
- default:
- return false;
- }
- }
- // Or: heaptype_1 is none and heaptype_2 matches any.
- case ValueType::NoneReference:
- return top_of_heap_type(heap_type2, context) == ValueType::AnyReference;
- // Or: heaptype_1 is nofunc and heaptype_2 matches func.
- case ValueType::NoFunctionReference:
- return top_of_heap_type(heap_type2, context) == ValueType::FunctionReference;
- // Or: heaptype_1 is noexn and heaptype_2 matches exn.
- case ValueType::NoExceptionReference:
- return top_of_heap_type(heap_type2, context) == ValueType::ExceptionReference;
- // Or: heaptype_1 is noextern and heaptype_2 matches extern.
- case ValueType::NoExternReference:
- return top_of_heap_type(heap_type2, context) == ValueType::ExternReference;
- default:
- return false;
- }
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#reference-types
-bool matches_reference_type(ValueType const& reference_type1, ValueType const& reference_type2, TypeContext const& context)
-{
- if (reference_type1.is_nullable() && !reference_type2.is_nullable())
- return false;
- return matches_heap_type(reference_type1, reference_type2, context);
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#value-types
-bool matches_value_type(ValueType const& value_type1, ValueType const& value_type2, TypeContext const& context)
-{
- if (value_type1.is_reference() && value_type2.is_reference())
- return matches_reference_type(value_type1, value_type2, context);
- return !value_type1.is_reference() && !value_type2.is_reference() && value_type1.kind() == value_type2.kind();
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#result-types
-bool matches_result_types(ReadonlySpan<ValueType> result_types1, ReadonlySpan<ValueType> result_types2, TypeContext const& context)
-{
- if (result_types1.size() != result_types2.size())
- return false;
- for (size_t i = 0; i < result_types1.size(); ++i) {
- if (!matches_value_type(result_types1[i], result_types2[i], context))
- return false;
- }
- return true;
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#field-types
-static bool matches_storage_type(ValueType const& storage_type1, ValueType const& storage_type2, TypeContext const& context)
-{
- if (storage_type1.is_packed() || storage_type2.is_packed())
- return storage_type1.kind() == storage_type2.kind();
- return matches_value_type(storage_type1, storage_type2, context);
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#field-types
-bool matches_field_type(FieldType const& field_type1, FieldType const& field_type2, TypeContext const& context)
-{
- if (field_type1.is_mutable() != field_type2.is_mutable())
- return false;
- if (!matches_storage_type(field_type1.type(), field_type2.type(), context))
- return false;
- if (field_type1.is_mutable() && !matches_storage_type(field_type2.type(), field_type1.type(), context))
- return false;
- return true;
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#composite-types
-bool matches_composite_type(TypeSection::Type::CompositeType const& composite_type1, TypeSection::Type::CompositeType const& composite_type2, TypeContext const& context)
-{
- return composite_type2.visit(
- [&](FunctionType const& function2) {
- auto const* function1 = composite_type1.get_pointer<FunctionType>();
- if (!function1)
- return false;
- return matches_result_types(function2.parameters(), function1->parameters(), context)
- && matches_result_types(function1->results(), function2.results(), context);
- },
- [&](StructType const& struct2) {
- auto const* struct1 = composite_type1.get_pointer<StructType>();
- if (!struct1 || struct1->fields().size() < struct2.fields().size())
- return false;
- for (size_t i = 0; i < struct2.fields().size(); ++i) {
- if (!matches_field_type(struct1->fields()[i], struct2.fields()[i], context))
- return false;
- }
- return true;
- },
- [&](ArrayType const& array2) {
- auto const* array1 = composite_type1.get_pointer<ArrayType>();
- if (!array1)
- return false;
- return matches_field_type(array1->type(), array2.type(), context);
- });
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#limits
-bool matches_limits(Limits const& limits1, Limits const& limits2)
-{
- if (limits1.min() < limits2.min())
- return false;
- if (!limits2.max().has_value())
- return true;
- return limits1.max().has_value() && *limits1.max() <= *limits2.max();
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#memory-types
-bool matches_memory_type(MemoryType const& memory_type1, MemoryType const& memory_type2)
-{
- if (memory_type1.limits().address_type() != memory_type2.limits().address_type())
- return false;
- return matches_limits(memory_type1.limits(), memory_type2.limits());
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#table-types
-bool matches_table_type(TableType const& table_type1, TableType const& table_type2, TypeContext const& context1, TypeContext const& context2)
-{
- if (table_type1.limits().address_type() != table_type2.limits().address_type())
- return false;
- if (!matches_limits(table_type1.limits(), table_type2.limits()))
- return false;
- auto element_type1 = canonicalized(table_type1.element_type(), context1);
- auto element_type2 = canonicalized(table_type2.element_type(), context2);
- return matches_reference_type(element_type1, element_type2, TypeContext {})
- && matches_reference_type(element_type2, element_type1, TypeContext {});
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#global-types
-bool matches_global_type(GlobalType const& global_type1, GlobalType const& global_type2, TypeContext const& context1, TypeContext const& context2)
-{
- if (global_type1.is_mutable() != global_type2.is_mutable())
- return false;
- auto value_type1 = canonicalized(global_type1.type(), context1);
- auto value_type2 = canonicalized(global_type2.type(), context2);
- if (!matches_value_type(value_type1, value_type2, TypeContext {}))
- return false;
- if (global_type1.is_mutable() && !matches_value_type(value_type2, value_type1, TypeContext {}))
- return false;
- return true;
-}
-
-// https://webassembly.github.io/spec/core/valid/matching.html#tag-types
-bool matches_tag_type(DefinedType const& defined_type1, DefinedType const& defined_type2)
-{
- return matches_defined_type(defined_type1, defined_type2) && matches_defined_type(defined_type2, defined_type1);
-}
-
-}
diff --git a/Libraries/LibWasm/TypeSystem.h b/Libraries/LibWasm/TypeSystem.h
deleted file mode 100644
index 311b476f8af..00000000000
--- a/Libraries/LibWasm/TypeSystem.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (c) 2026, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Error.h>
-#include <AK/Span.h>
-#include <AK/Vector.h>
-#include <LibWasm/Export.h>
-#include <LibWasm/Types.h>
-
-namespace Wasm {
-
-struct ValidationError;
-
-// https://webassembly.github.io/spec/core/valid/conventions.html#defined-types
-// https://webassembly.github.io/spec/core/valid/conventions.html#rolling-and-unrolling
-class WASM_API DefinedType {
- AK_MAKE_NONCOPYABLE(DefinedType);
- AK_MAKE_NONMOVABLE(DefinedType);
-
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- // https://webassembly.github.io/spec/core/valid/conventions.html#aux-unroll-deftype
- TypeSection::Type const& sub_type() const { return m_sub_type; }
-
- // https://webassembly.github.io/spec/core/valid/conventions.html#aux-expand-deftype
- auto& expansion() const { return m_sub_type.description(); }
-
- // The (single) declared supertype.
- DefinedType const* supertype() const { return m_supertype; }
- bool is_final() const { return m_sub_type.is_final(); }
-
- u32 subtyping_depth() const { return m_subtyping_depth; }
- ReadonlySpan<DefinedType const*> ancestors() const { return m_ancestors; }
-
- u32 registry_index() const { return m_registry_index; }
-
-private:
- friend class TypeRegistry;
-
- DefinedType(TypeSection::Type sub_type, u32 registry_index)
- : m_sub_type(move(sub_type))
- , m_registry_index(registry_index)
- {
- }
-
- TypeSection::Type m_sub_type;
- DefinedType const* m_supertype { nullptr };
- Vector<DefinedType const*> m_ancestors;
- u32 m_subtyping_depth { 0 };
- u32 m_registry_index { 0 };
-};
-
-// https://webassembly.github.io/spec/core/valid/conventions.html#contexts
-struct WASM_API TypeContext {
- DefinedType const* resolve(TypeIndex index) const;
-
- ReadonlySpan<DefinedType const*> types {};
-};
-
-WASM_API ErrorOr<Vector<DefinedType const*>, ValidationError> canonicalize_module_types(TypeSection const&);
-WASM_API DefinedType const* canonicalize_type(TypeSection::Type const&, TypeContext const& context);
-// https://webassembly.github.io/spec/core/valid/conventions.html#aux-clostype
-WASM_API ValueType canonicalized(ValueType, TypeContext const&);
-
-// https://webassembly.github.io/spec/core/valid/matching.html
-WASM_API ValueType::Kind top_of_heap_type(ValueType const&, TypeContext const&);
-WASM_API bool matches_heap_type(ValueType const& heap_type1, ValueType const& heap_type2, TypeContext const&);
-WASM_API bool matches_reference_type(ValueType const& reference_type1, ValueType const& reference_type2, TypeContext const&);
-WASM_API bool matches_value_type(ValueType const& value_type1, ValueType const& value_type2, TypeContext const&);
-WASM_API bool matches_result_types(ReadonlySpan<ValueType> result_types1, ReadonlySpan<ValueType> result_types2, TypeContext const&);
-WASM_API bool matches_field_type(FieldType const&, FieldType const&, TypeContext const&);
-WASM_API bool matches_composite_type(TypeSection::Type::CompositeType const&, TypeSection::Type::CompositeType const&, TypeContext const&);
-WASM_API bool matches_defined_type(DefinedType const&, DefinedType const&);
-WASM_API bool matches_limits(Limits const&, Limits const&);
-WASM_API bool matches_memory_type(MemoryType const&, MemoryType const&);
-WASM_API bool matches_table_type(TableType const&, TableType const&, TypeContext const& context1, TypeContext const& context2);
-WASM_API bool matches_global_type(GlobalType const&, GlobalType const&, TypeContext const& context1, TypeContext const& context2);
-WASM_API bool matches_tag_type(DefinedType const&, DefinedType const&);
-
-}
diff --git a/Libraries/LibWasm/Types.h b/Libraries/LibWasm/Types.h
deleted file mode 100644
index ca98a12b6b5..00000000000
--- a/Libraries/LibWasm/Types.h
+++ /dev/null
@@ -1,1893 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/AtomicRefCounted.h>
-#include <AK/Badge.h>
-#include <AK/ByteString.h>
-#include <AK/ConditionVariable.h>
-#include <AK/DistinctNumeric.h>
-#include <AK/FixedArray.h>
-#include <AK/Function.h>
-#include <AK/LEB128.h>
-#include <AK/Mutex.h>
-#include <AK/NumericLimits.h>
-#include <AK/Optional.h>
-#include <AK/OwnPtr.h>
-#include <AK/Result.h>
-#include <AK/String.h>
-#include <AK/Time.h>
-#include <AK/UFixedBigInt.h>
-#include <AK/Variant.h>
-#include <AK/WeakPtr.h>
-#include <AK/kmalloc.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibWasm/Constants.h>
-#include <LibWasm/Export.h>
-#include <LibWasm/Forward.h>
-#include <LibWasm/Opcode.h>
-
-namespace Wasm {
-
-class DefinedType;
-class Module;
-
-template<size_t M>
-using NativeIntegralType = Conditional<M == 8, u8, Conditional<M == 16, u16, Conditional<M == 32, u32, Conditional<M == 64, u64, void>>>>;
-
-template<size_t M>
-using NativeFloatingType = Conditional<M == 32, f32, Conditional<M == 64, f64, void>>;
-
-template<size_t M, size_t N, template<typename> typename SetSign, typename ElementType = SetSign<NativeIntegralType<M>>>
-using NativeVectorType __attribute__((vector_size(N * sizeof(ElementType)))) = ElementType;
-
-template<size_t M, size_t N, typename ElementType = NativeFloatingType<M>>
-using NativeFloatingVectorType __attribute__((vector_size(N * sizeof(ElementType)))) = ElementType;
-
-template<typename T, template<typename> typename SetSign>
-using Native128ByteVectorOf = NativeVectorType<sizeof(T) * 8, 16 / sizeof(T), SetSign, T>;
-
-enum class ParseError {
- UnexpectedEof,
- UnknownInstruction,
- ExpectedFloatingImmediate,
- ExpectedIndex,
- ExpectedKindTag,
- ExpectedSignedImmediate,
- ExpectedSize,
- ExpectedValueOrTerminator,
- InvalidImmediate,
- InvalidIndex,
- InvalidInput,
- InvalidModuleMagic,
- InvalidModuleVersion,
- InvalidSize,
- InvalidTag,
- InvalidType,
- HugeAllocationRequested,
- OutOfMemory,
- SectionSizeMismatch,
- InvalidUtf8,
- DuplicateSection,
- SectionOutOfOrder,
-};
-
-WASM_API ByteString parse_error_to_byte_string(ParseError);
-
-template<typename T>
-using ParseResult = ErrorOr<T, ParseError>;
-
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, TypeIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, FunctionIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, TableIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, ElementIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, MemoryIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, TagIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, LocalIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, GlobalIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, LabelIndex);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u32, DataIndex);
-AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u32, InstructionPointer, Arithmetic, Comparison, Flags, Increment);
-
-}
-
-namespace AK {
-
-template<>
-struct SentinelOptionalTraits<Wasm::InstructionPointer> {
- static constexpr Wasm::InstructionPointer sentinel_value() { return { NumericLimits<Wasm::InstructionPointer::Type>::max() }; }
- static constexpr bool is_sentinel(Wasm::InstructionPointer const& value) { return value.value() == NumericLimits<Wasm::InstructionPointer::Type>::max(); }
-};
-
-template<>
-class Optional<Wasm::InstructionPointer> : public SentinelOptional<Wasm::InstructionPointer> {
-public:
- using SentinelOptional::SentinelOptional;
-};
-
-}
-
-namespace Wasm {
-
-constexpr static inline auto LocalArgumentMarker = static_cast<LocalIndex::Type>(1) << (sizeof(LocalIndex::Type) * 8 - 1);
-
-ParseError with_eof_check(Stream const& stream, ParseError error_if_not_eof);
-
-template<typename T>
-struct GenericIndexParser {
- static ParseResult<T> parse(Stream& stream)
- {
- auto value_or_error = stream.read_value<LEB128<u32>>();
- if (value_or_error.is_error())
- return with_eof_check(stream, ParseError::ExpectedIndex);
- u32 value = value_or_error.release_value();
- return T { value };
- }
-};
-
-class ReconsumableStream : public Stream {
-public:
- explicit ReconsumableStream(Stream& stream)
- : m_stream(stream)
- {
- }
-
- void unread(ReadonlyBytes data) { m_buffer.append(data.data(), data.size()); }
-
-private:
- virtual ErrorOr<Bytes> read_some(Bytes bytes) override
- {
- auto original_bytes = bytes;
-
- size_t bytes_read_from_buffer = 0;
- if (!m_buffer.is_empty()) {
- auto read_size = min(bytes.size(), m_buffer.size());
- m_buffer.span().slice(0, read_size).copy_to(bytes);
- bytes = bytes.slice(read_size);
- for (size_t i = 0; i < read_size; ++i)
- m_buffer.take_first();
- bytes_read_from_buffer = read_size;
- }
-
- return original_bytes.trim(TRY(m_stream.read_some(bytes)).size() + bytes_read_from_buffer);
- }
-
- virtual bool is_eof() const override
- {
- return m_buffer.is_empty() && m_stream.is_eof();
- }
-
- virtual ErrorOr<void> discard(size_t count) override
- {
- size_t bytes_discarded_from_buffer = 0;
- if (!m_buffer.is_empty()) {
- auto read_size = min(count, m_buffer.size());
- for (size_t i = 0; i < read_size; ++i)
- m_buffer.take_first();
- bytes_discarded_from_buffer = read_size;
- }
-
- return m_stream.discard(count - bytes_discarded_from_buffer);
- }
-
- virtual ErrorOr<size_t> write_some(ReadonlyBytes) override
- {
- return Error::from_errno(EBADF);
- }
-
- virtual bool is_open() const override
- {
- return m_stream.is_open();
- }
-
- virtual void close() override
- {
- m_stream.close();
- }
-
- Stream& m_stream;
- Vector<u8, 8> m_buffer;
-};
-
-// https://webassembly.github.io/spec/core/syntax/types.html#value-types
-// valtype ::= numtype | vectype | reftype
-// https://webassembly.github.io/spec/core/syntax/types.html#reference-types
-// reftype ::= ref null? heaptype
-// https://webassembly.github.io/spec/core/syntax/types.html#heap-types
-// heaptype ::= absheaptype | typeidx
-// absheaptype ::= func | nofunc | extern | noextern | any | eq | i31 | struct | array | none | exn | noexn
-// https://webassembly.github.io/spec/core/syntax/types.html#composite-types
-// packtype ::= i8 | i16
-class ValueType {
-public:
- enum Kind : u8 {
- I32,
- I64,
- F32,
- F64,
- V128,
- I8, // as packtype
- I16, // as packtype
- FunctionReference,
- NoFunctionReference,
- ExternReference,
- NoExternReference,
- AnyReference,
- EqReference,
- I31Reference,
- StructReference,
- ArrayReference,
- NoneReference,
- ExceptionReference,
- NoExceptionReference,
- TypeUseReference,
- };
-
- explicit ValueType(Kind kind)
- : m_kind(kind)
- {
- }
-
- explicit ValueType(Kind kind, bool nullable)
- : m_kind(kind)
- , m_nullable(nullable)
- {
- }
-
- explicit ValueType(Kind kind, TypeIndex type_index, bool nullable = true)
- : m_kind(kind)
- , m_nullable(nullable)
- , m_type_index(type_index)
- {
- VERIFY(kind == TypeUseReference);
- }
-
- bool operator==(ValueType const&) const = default;
-
- bool is_nullable() const { return m_nullable; }
- void set_nullable(bool nullable) { m_nullable = nullable; }
-
- auto is_reference() const { return m_kind >= FunctionReference; }
- auto is_vector() const { return m_kind == V128; }
- auto is_packed() const { return m_kind == I8 || m_kind == I16; }
- auto is_numeric() const { return !is_reference() && !is_vector() && !is_packed(); }
- auto is_typeuse() const { return m_kind == TypeUseReference; }
- auto kind() const { return m_kind; }
-
- // https://webassembly.github.io/spec/core/syntax/types.html#aux-unpack
- // unpack(valtype) = valtype
- // unpack(packtype) = i32
- ValueType unpacked() const
- {
- if (is_packed())
- return ValueType(I32);
- return *this;
- }
-
- // https://webassembly.github.io/spec/core/valid/types.html#defaultable-types
- bool is_defaultable() const
- {
- if (is_reference())
- return m_nullable;
- return true;
- }
-
- auto unsafe_typeindex() const
- {
- VERIFY(m_kind == TypeUseReference);
- return m_type_index;
- }
-
- static ParseResult<ValueType> parse(Stream& stream);
-
- ByteString kind_name() const
- {
- switch (m_kind) {
- case I32:
- return "i32";
- case I64:
- return "i64";
- case F32:
- return "f32";
- case F64:
- return "f64";
- case V128:
- return "v128";
- case I8:
- return "i8";
- case I16:
- return "i16";
- case FunctionReference:
- return m_nullable ? "funcref" : "(ref func)";
- case NoFunctionReference:
- return m_nullable ? "nullfuncref" : "(ref nofunc)";
- case ExternReference:
- return m_nullable ? "externref" : "(ref extern)";
- case NoExternReference:
- return m_nullable ? "nullexternref" : "(ref noextern)";
- case AnyReference:
- return m_nullable ? "anyref" : "(ref any)";
- case EqReference:
- return m_nullable ? "eqref" : "(ref eq)";
- case I31Reference:
- return m_nullable ? "i31ref" : "(ref i31)";
- case StructReference:
- return m_nullable ? "structref" : "(ref struct)";
- case ArrayReference:
- return m_nullable ? "arrayref" : "(ref array)";
- case NoneReference:
- return m_nullable ? "nullref" : "(ref none)";
- case ExceptionReference:
- return m_nullable ? "exnref" : "(ref exn)";
- case NoExceptionReference:
- return m_nullable ? "nullexnref" : "(ref noexn)";
- case TypeUseReference:
- return ByteString::formatted("(ref {}{})", m_nullable ? "null " : "", unsafe_typeindex().value());
- }
- VERIFY_NOT_REACHED();
- }
-
-private:
- Kind m_kind;
- bool m_nullable { true };
- TypeIndex m_type_index;
-};
-
-static_assert(sizeof(ValueType) == 8);
-
-// https://webassembly.github.io/spec/core/bikeshed/#result-types%E2%91%A2
-class ResultType {
-public:
- explicit ResultType(Vector<ValueType> types)
- : m_types(move(types))
- {
- }
-
- auto const& types() const { return m_types; }
-
- static ParseResult<ResultType> parse(ConstrainedStream& stream);
-
-private:
- Vector<ValueType> m_types;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#function-types%E2%91%A4
-class FunctionType {
-public:
- FunctionType(Vector<ValueType> parameters, Vector<ValueType> results)
- : m_parameters(move(parameters))
- , m_results(move(results))
- {
- }
-
- auto& parameters() const { return m_parameters; }
- auto& results() const { return m_results; }
-
- static ParseResult<FunctionType> parse(ConstrainedStream& stream);
-
-private:
- Vector<ValueType> m_parameters;
- Vector<ValueType> m_results;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#composite-types%E2%91%A0
-class FieldType {
-public:
- FieldType(bool is_mutable, ValueType type_)
- : m_is_mutable(is_mutable)
- , m_type(type_)
- {
- }
-
- auto& type() const { return m_type; }
- auto is_mutable() const { return m_is_mutable; }
-
- static ParseResult<FieldType> parse(ConstrainedStream& stream);
-
-private:
- bool m_is_mutable { false };
- ValueType m_type;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#composite-types%E2%91%A0
-class StructType {
-public:
- StructType(Vector<FieldType> fields)
- : m_fields(move(fields))
- {
- }
-
- auto& fields() const { return m_fields; }
-
- static ParseResult<StructType> parse(ConstrainedStream& stream);
-
-private:
- Vector<FieldType> m_fields;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#composite-types%E2%91%A0
-class ArrayType {
-public:
- ArrayType(FieldType type)
- : m_type(type)
- {
- }
-
- auto& type() const { return m_type; }
-
- static ParseResult<ArrayType> parse(ConstrainedStream& stream);
-
-private:
- FieldType m_type;
-};
-
-// https://webassembly.github.io/memory64/core/bikeshed/#address-type%E2%91%A0
-enum class AddressType : u8 {
- I32,
- I64,
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#limits%E2%91%A5
-class Limits {
-public:
- explicit Limits(AddressType address_type, u64 min, Optional<u64> max = {})
- : m_address_type(address_type)
- , m_min(min)
- , m_max(move(max))
- {
- }
-
- ValueType address_value_type() const
- {
- return m_address_type == AddressType::I32 ? ValueType(ValueType::I32) : ValueType(ValueType::I64);
- }
- auto address_type() const { return m_address_type; }
- auto min() const { return m_min; }
- auto& max() const { return m_max; }
- bool is_subset_of(Limits other) const
- {
- return m_min >= other.min()
- && (!other.max().has_value() || (m_max.has_value() && *m_max <= *other.max()))
- && m_address_type == other.m_address_type;
- }
-
- static ParseResult<Limits> parse(ConstrainedStream& stream);
-
-private:
- AddressType m_address_type { AddressType::I32 };
- u64 m_min { 0 };
- Optional<u64> m_max;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#memory-types%E2%91%A4
-class MemoryType {
-public:
- explicit MemoryType(Limits limits)
- : m_limits(move(limits))
- {
- }
-
- auto& limits() const { return m_limits; }
-
- static ParseResult<MemoryType> parse(ConstrainedStream& stream);
-
-private:
- Limits m_limits;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#table-types%E2%91%A4
-class TableType {
-public:
- explicit TableType(ValueType element_type, Limits limits)
- : m_element_type(element_type)
- , m_limits(move(limits))
- {
- VERIFY(m_element_type.is_reference());
- }
-
- auto& limits() const { return m_limits; }
- auto& element_type() const { return m_element_type; }
-
- static ParseResult<TableType> parse(ConstrainedStream& stream);
-
-private:
- ValueType m_element_type;
- Limits m_limits;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#global-types%E2%91%A4
-class GlobalType {
-public:
- GlobalType(ValueType type, bool is_mutable)
- : m_type(type)
- , m_is_mutable(is_mutable)
- {
- }
-
- auto& type() const { return m_type; }
- auto is_mutable() const { return m_is_mutable; }
-
- static ParseResult<GlobalType> parse(ConstrainedStream& stream);
-
-private:
- ValueType m_type;
- bool m_is_mutable { false };
-};
-
-// https://webassembly.github.io/exception-handling/core/binary/types.html#tag-types
-class TagType {
-public:
- enum Flags : u8 {
- None = 0
- };
-
- TagType(TypeIndex type, Flags flags)
- : m_flags(flags)
- , m_type(type)
- {
- }
-
- auto& type() const { return m_type; }
- auto flags() const { return m_flags; }
-
- static ParseResult<TagType> parse(ConstrainedStream& stream);
-
-private:
- Flags m_flags { None };
- TypeIndex m_type;
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#binary-blocktype
-class BlockType {
-public:
- enum Kind {
- Empty,
- Type,
- Index,
- };
-
- BlockType()
- : m_kind(Empty)
- , m_empty(0)
- {
- }
-
- explicit BlockType(ValueType type)
- : m_kind(Type)
- , m_value_type(type)
- {
- }
-
- explicit BlockType(TypeIndex index)
- : m_kind(Index)
- , m_type_index(index)
- {
- }
-
- auto kind() const { return m_kind; }
- auto& value_type() const
- {
- VERIFY(kind() == Type);
- return m_value_type;
- }
- auto& type_index() const
- {
- VERIFY(kind() == Index);
- return m_type_index;
- }
-
- static ParseResult<BlockType> parse(ConstrainedStream& stream);
-
-private:
- Kind m_kind { Empty };
- union {
- ValueType m_value_type;
- TypeIndex m_type_index;
- u8 m_empty;
- };
-};
-
-// Proposal "exception-handling"
-// https://webassembly.github.io/exception-handling/core/binary/instructions.html
-class Catch {
-public:
- Catch(bool ref, TagIndex index, LabelIndex label) // catch[_ref] x l
- : m_matching_tag_index(index)
- , m_target_label(label)
- , m_is_ref(ref)
- {
- }
-
- explicit Catch(bool ref, LabelIndex label) // catch_all[_ref] l
- : m_target_label(label)
- , m_is_ref(ref)
- {
- }
-
- auto& matching_tag_index() const { return m_matching_tag_index; }
- auto& target_label() const { return m_target_label; }
- auto is_ref() const { return m_is_ref; }
-
- static ParseResult<Catch> parse(ConstrainedStream& stream);
-
-private:
- Optional<TagIndex> m_matching_tag_index; // None for catch_all
- LabelIndex m_target_label;
- bool m_is_ref = false; // true if catch*_ref
-};
-
-// https://webassembly.github.io/spec/core/bikeshed/#binary-instr
-// https://webassembly.github.io/spec/core/bikeshed/#reference-instructions%E2%91%A6
-// https://webassembly.github.io/spec/core/bikeshed/#parametric-instructions%E2%91%A6
-// https://webassembly.github.io/spec/core/bikeshed/#variable-instructions%E2%91%A6
-// https://webassembly.github.io/spec/core/bikeshed/#table-instructions%E2%91%A6
-// https://webassembly.github.io/spec/core/bikeshed/#memory-instructions%E2%91%A6
-// https://webassembly.github.io/spec/core/bikeshed/#numeric-instructions%E2%91%A6
-class Instruction {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- explicit Instruction(OpCode opcode)
- : m_opcode(opcode)
- , m_arguments(static_cast<u8>(0))
- {
- }
-
- struct TableElementArgs {
- ElementIndex element_index;
- TableIndex table_index;
- };
-
- struct TableTableArgs {
- TableIndex lhs;
- TableIndex rhs;
- };
-
- template<typename ExtraData>
- struct StructuredInstructionArgsBase {
- using Extra = ExtraData;
-
- BlockType block_type;
- InstructionPointer end_ip; // 'end' instruction IP if there is no 'else'; otherwise IP of instruction after 'end'.
- ExtraData extra;
-
- struct Meta {
- u32 arity;
- u32 parameter_count;
- bool tier_up_eligible;
- };
- mutable Meta meta {};
- };
-
- struct StructuredInstructionArgs : StructuredInstructionArgsBase<Optional<InstructionPointer>> {
- using Base = StructuredInstructionArgsBase<Optional<InstructionPointer>>;
- using Meta = typename Base::Meta;
-
- StructuredInstructionArgs(BlockType block_type, InstructionPointer end_ip, Optional<InstructionPointer> else_ip, Meta meta = {})
- : Base { block_type, end_ip, else_ip, meta }
- {
- }
-
- auto& else_ip() { return extra; }
- auto& else_ip() const { return extra; }
- };
-
- struct TableBranchArgs {
- Vector<LabelIndex> labels;
- LabelIndex default_;
- };
-
- struct BranchArgs {
- LabelIndex label;
- mutable bool has_stack_adjustment { false };
- };
-
- struct IndirectCallArgs {
- TypeIndex type;
- TableIndex table;
- };
-
- struct MemoryArgument {
- u32 align;
- u64 offset;
- MemoryIndex memory_index { 0 };
- };
-
- // Proposal "threads"
- struct AtomicMemoryArgument {
- enum class Width : u8 {
- I32,
- I64,
- I8As32, // i8 stack, memory accessed zero-extended to i32.
- I16As32,
- I8As64,
- I16As64,
- I32As64,
- };
- enum class Op : u8 {
- None,
- Add,
- Sub,
- And,
- Or,
- Xor,
- Xchg,
- };
-
- MemoryArgument memory;
- Width width;
- Op op { Op::None };
-
- size_t access_size() const
- {
- switch (width) {
- case Width::I8As32:
- case Width::I8As64:
- return 1;
- case Width::I16As32:
- case Width::I16As64:
- return 2;
- case Width::I32:
- case Width::I32As64:
- return 4;
- case Width::I64:
- return 8;
- }
- VERIFY_NOT_REACHED();
- }
-
- ValueType value_type() const
- {
- switch (width) {
- case Width::I32:
- case Width::I8As32:
- case Width::I16As32:
- return ValueType { ValueType::I32 };
- case Width::I64:
- case Width::I8As64:
- case Width::I16As64:
- case Width::I32As64:
- return ValueType { ValueType::I64 };
- }
- VERIFY_NOT_REACHED();
- }
- };
-
- struct MemoryAndLaneArgument {
- MemoryArgument memory;
- u8 lane;
- };
-
- struct LaneIndex {
- u8 lane;
- };
-
- // Proposal "multi-memory"
- struct MemoryCopyArgs {
- MemoryIndex src_index;
- MemoryIndex dst_index;
- };
-
- struct MemoryInitArgs {
- DataIndex data_index;
- MemoryIndex memory_index;
- };
-
- struct MemoryIndexArgument {
- MemoryIndex memory_index;
- };
-
- // Proposal "gc"
- struct StructFieldArgs {
- TypeIndex type_index;
- u32 field_index;
- };
-
- struct ArrayNewFixedArgs {
- TypeIndex type_index;
- u32 count;
- };
-
- struct ArrayDataArgs {
- TypeIndex type_index;
- DataIndex data_index;
- };
-
- struct ArrayElemArgs {
- TypeIndex type_index;
- ElementIndex element_index;
- };
-
- struct ArrayCopyArgs {
- TypeIndex destination_type_index;
- TypeIndex source_type_index;
- };
-
- struct BranchOnCastArgs {
- BranchArgs branch;
- ValueType source_type; // Nullability carries the castop null_1? flag.
- ValueType target_type; // Nullability carries the castop null_2? flag.
- };
-
- // Proposal "exception-handling"
- struct TryTableArgs : StructuredInstructionArgsBase<OwnPtr<FixedArray<Catch>>> {
- using Base = StructuredInstructionArgsBase<OwnPtr<FixedArray<Catch>>>;
- using Meta = typename Base::Meta;
-
- TryTableArgs(BlockType block_type, InstructionPointer end_ip, ReadonlySpan<Catch> catches, Meta meta = {})
- : Base { block_type, end_ip, create_catches(catches), meta }
- {
- }
-
- TryTableArgs(TryTableArgs const& other)
- : Base { other.block_type, other.end_ip, clone_catches(other.extra), other.meta }
- {
- }
-
- TryTableArgs& operator=(TryTableArgs const& other)
- {
- if (this == &other)
- return *this;
- block_type = other.block_type;
- end_ip = other.end_ip;
- extra = clone_catches(other.extra);
- meta = other.meta;
- return *this;
- }
-
- TryTableArgs(TryTableArgs&&) = default;
- TryTableArgs& operator=(TryTableArgs&&) = default;
-
- ReadonlySpan<Catch> catches() const
- {
- if (!extra)
- return {};
- return extra->span();
- }
-
- private:
- static OwnPtr<FixedArray<Catch>> create_catches(ReadonlySpan<Catch> catches)
- {
- if (catches.is_empty())
- return nullptr;
- return make<FixedArray<Catch>>(MUST(FixedArray<Catch>::create(catches)));
- }
-
- static OwnPtr<FixedArray<Catch>> clone_catches(OwnPtr<FixedArray<Catch>> const& catches)
- {
- if (!catches)
- return nullptr;
- return make<FixedArray<Catch>>(MUST(catches->clone()));
- }
- };
-
- struct ShuffleArgument {
- explicit ShuffleArgument(u8 (&lanes)[16])
- : lanes {
- lanes[0], lanes[1], lanes[2], lanes[3], lanes[4], lanes[5], lanes[6], lanes[7],
- lanes[8], lanes[9], lanes[10], lanes[11], lanes[12], lanes[13], lanes[14], lanes[15]
- }
- {
- }
-
- u8 lanes[16];
- };
-
- template<typename T>
- explicit Instruction(OpCode opcode, T argument)
- : m_opcode(opcode)
- , m_arguments(move(argument))
- {
- }
-
- explicit Instruction(OpCode opcode, LocalIndex argument)
- : m_opcode(opcode)
- , m_local_index(argument)
- , m_arguments(static_cast<u8>(0))
- {
- }
-
- template<typename Arg1>
- explicit Instruction(OpCode opcode, LocalIndex argument0, Arg1&& argument1)
- : m_opcode(opcode)
- , m_local_index(argument0)
- , m_arguments(forward<Arg1>(argument1))
- {
- }
-
- static ParseResult<Instruction> parse(ConstrainedStream& stream);
-
- auto& opcode() const { return m_opcode; }
- auto& arguments() const { return m_arguments; }
- auto& arguments() { return m_arguments; }
-
- LocalIndex local_index() const { return m_local_index; }
-
- void set_local_index(Badge<Module>, LocalIndex index) { m_local_index = index; }
-
-private:
- OpCode m_opcode { 0 };
- LocalIndex m_local_index;
-
- Variant<
- ArrayCopyArgs,
- ArrayDataArgs,
- ArrayElemArgs,
- ArrayNewFixedArgs,
- AtomicMemoryArgument,
- BlockType,
- BranchArgs,
- BranchOnCastArgs,
- DataIndex,
- ElementIndex,
- FunctionIndex,
- GlobalIndex,
- TagIndex,
- IndirectCallArgs,
- LabelIndex,
- LaneIndex,
- LocalIndex, // Only used by instructions that take more than one local index (currently only fused ops).
- MemoryArgument,
- MemoryAndLaneArgument,
- MemoryCopyArgs,
- MemoryIndexArgument,
- MemoryInitArgs,
- StructFieldArgs,
- StructuredInstructionArgs,
- ShuffleArgument,
- TableBranchArgs,
- TableElementArgs,
- TableIndex,
- TableTableArgs,
- TryTableArgs,
- TypeIndex,
- ValueType,
- Vector<ValueType>,
- double,
- float,
- i32,
- i64,
- u128,
- u8> // Empty state
- m_arguments;
-};
-
-}
-
-namespace AK {
-
-template<>
-struct SentinelOptionalTraits<Wasm::Instruction> {
- static Wasm::Instruction sentinel_value() { return Wasm::Instruction { Wasm::OpCode { NumericLimits<Wasm::OpCode::Type>::max() } }; }
- static bool is_sentinel(Wasm::Instruction const& value) { return value.opcode().value() == NumericLimits<Wasm::OpCode::Type>::max(); }
-};
-
-template<>
-class Optional<Wasm::Instruction> : public SentinelOptional<Wasm::Instruction> {
-public:
- using SentinelOptional::SentinelOptional;
-};
-
-}
-
-namespace Wasm {
-
-static_assert(sizeof(Optional<Instruction>) == sizeof(Instruction));
-
-static_assert(sizeof(Optional<InstructionPointer>) == sizeof(InstructionPointer));
-
-struct Dispatch {
- enum RegisterOrStack : u8 {
- R0,
- R1,
- R2,
- R3,
- R4,
- R5,
- R6,
- R7,
- CountRegisters,
- Stack = CountRegisters,
- CallRecord,
- LastCallRecord = NumericLimits<u8>::max(),
- };
-
- static_assert(is_power_of_two(to_underlying(Stack)), "Stack marker must be a single bit");
-
- union {
- OpCode instruction_opcode;
- FlatPtr handler_ptr;
- };
- Instruction const* instruction { nullptr };
-};
-
-union SourcesAndDestination {
- struct {
- Dispatch::RegisterOrStack sources[3];
- Dispatch::RegisterOrStack destination;
- };
- u32 sources_and_destination;
-};
-
-class InstructionStorage {
- using Chunk = FixedArray<Optional<Instruction>>;
-
-public:
- InstructionStorage() = default;
- InstructionStorage(InstructionStorage const&) = delete;
- InstructionStorage& operator=(InstructionStorage const&) = delete;
- InstructionStorage(InstructionStorage&&) = default;
- InstructionStorage& operator=(InstructionStorage&&) = default;
-
- Instruction& append(Instruction);
-
- size_t size() const { return m_size; }
- size_t capacity() const { return m_capacity; }
- bool is_empty() const { return m_size == 0; }
-
-private:
- void add_chunk();
-
- Vector<Chunk, 0, FastLastAccess::Yes> m_chunks;
- size_t m_size { 0 };
- size_t m_capacity { 0 };
- size_t m_next_index_in_last_chunk { 0 };
-};
-
-void free_cranelift_code(void* handle);
-
-struct CraneliftTrap {
- u32 offset { 0 };
- u8 code { 0 };
- u8 _padding[3] { 0, 0, 0 };
-};
-static_assert(sizeof(CraneliftTrap) == 8);
-
-struct CompiledInstructions {
- Vector<Dispatch> dispatches;
- Vector<SourcesAndDestination> src_dst_mappings;
- InstructionStorage extra_instruction_storage;
-
- Vector<u8> cranelift_local_types;
-
- // Pointer/size_t-sized members first, then the u32, then the bools, so the trailing scalars pack
- // into one word instead of scattering padding between them.
-
- // Native entry point for this function (conforms to the interpreter handler ABI). Zero until
- // the background/AOT compile has fully installed the code. Published with an atomic store-release
- // as the LAST step of install_compiled_function() and read with an atomic load-acquire at every
- // execution-decision site, so a function can tier up to JIT concurrently with execution without
- // a reader ever observing a half-installed function. dispatches[0].handler_ptr always stays the
- // C++ interpreter handler, so the interpreter path is valid regardless of compilation state.
- FlatPtr cranelift_entry = 0;
- void* cranelift_code_handle = nullptr; // Owned; freed when the owning Module is destroyed.
- size_t cranelift_code_size = 0;
- CraneliftTrap const* cranelift_traps = nullptr; // Owned by cranelift_code_handle.
- size_t cranelift_trap_count = 0;
- size_t max_call_arg_count = 0;
- size_t max_call_rec_size = 0;
-
- u32 cranelift_result_arity = 0; // result count to hand to try_cranelift_compile(); only meaningful when cranelift_eligible.
- u32 cranelift_local_count = 0; // total locals (params + declared + inlined); lets Cranelift promote locals to SSA instead of memory. Only meaningful when cranelift_eligible.
- u32 cranelift_param_count = 0; // leading locals that are parameters; the compiled entry block zero-initializes everything past them. Only meaningful when cranelift_eligible.
- u32 cranelift_inlined_locals = 0; // extra locals appended for inlined callee bodies (see try_compile_instructions); the frame is grown by this much in both interpreter and JIT paths.
- u32 max_label_depth = 0; // max concurrent labels (incl. the function-level label) the compiled stream can push.
-
- bool direct = false; // true if all dispatches contain handler_ptr, otherwise false and all contain instruction_opcode.
- bool cranelift_eligible = false; // true if this expression cleared the Cranelift type/shape checks during validation.
- bool has_tier_up_checkpoints = false; // true if try_compile_instructions inserted synthetic_tier_up ops (Tier-Up sites).
- bool cranelift_compiled = false;
-};
-
-// Read the native entry with acquire ordering: a non-zero result means the function is fully
-// installed and every cranelift_* field written before publication is visible to this thread.
-inline FlatPtr cranelift_entry_acquire(CompiledInstructions const& ci)
-{
- return AK::atomic_load(const_cast<FlatPtr volatile*>(&ci.cranelift_entry), AK::MemoryOrder::memory_order_acquire);
-}
-
-// Publish the native entry with release ordering. Must be the LAST write of install.
-inline void publish_cranelift_entry(CompiledInstructions& ci, FlatPtr entry)
-{
- AK::atomic_store(&ci.cranelift_entry, entry, AK::MemoryOrder::memory_order_release);
-}
-
-template<Enum auto... Vs>
-consteval auto as_ordered()
-{
- using Type = CommonType<decltype(to_underlying(Vs))...>;
- Array<Type, sizeof...(Vs)> result;
- [&]<Type... Is>(IntegerSequence<Type, Is...>) {
- (void)((result[to_underlying(Vs)] = Is), ...);
- }(MakeIntegerSequence<Type, static_cast<Type>(sizeof...(Vs))>());
- return result;
-}
-
-struct SectionId {
-public:
- enum class SectionIdKind : u8 {
- Custom,
- Type,
- Import,
- Function,
- Table,
- Memory,
- Global,
- Export,
- Start,
- Element,
- DataCount,
- Code,
- Data,
- Tag,
- };
-
- constexpr inline static auto section_order = as_ordered<
- SectionIdKind::Type,
- SectionIdKind::Import,
- SectionIdKind::Function,
- SectionIdKind::Table,
- SectionIdKind::Memory,
- SectionIdKind::Tag,
- SectionIdKind::Global,
- SectionIdKind::Export,
- SectionIdKind::Start,
- SectionIdKind::Element,
- SectionIdKind::DataCount,
- SectionIdKind::Code,
- SectionIdKind::Data,
- SectionIdKind::Custom>();
-
- explicit SectionId(SectionIdKind kind)
- : m_kind(kind)
- {
- }
-
- bool can_appear_after(SectionIdKind other) const
- {
- if (kind() == SectionIdKind::Custom || other == SectionIdKind::Custom)
- return true;
-
- auto index = section_order[to_underlying(kind())];
- auto other_index = section_order[to_underlying(other)];
- return index >= other_index;
- }
-
- SectionIdKind kind() const
- {
- return m_kind;
- }
-
- static ParseResult<SectionId> parse(Stream& stream);
-
-private:
- SectionIdKind m_kind;
-};
-
-class CustomSection {
-public:
- CustomSection(ByteString name, ByteBuffer contents)
- : m_name(move(name))
- , m_contents(move(contents))
- {
- }
-
- auto& name() const { return m_name; }
- auto& contents() const { return m_contents; }
-
- static ParseResult<CustomSection> parse(ConstrainedStream& stream);
-
-private:
- ByteString m_name;
- ByteBuffer m_contents;
-};
-
-class TypeSection {
-public:
- // https://webassembly.github.io/spec/core/syntax/types.html#recursive-types
- // https://webassembly.github.io/spec/core/syntax/types.html#composite-types
- class Type {
- public:
- using CompositeType = Variant<FunctionType, StructType, ArrayType>;
-
- struct RecGroupSpan {
- u32 first_type_index { 0 };
- u32 size { 1 };
- };
-
- Type(CompositeType type, Vector<TypeIndex> supertypes = {}, bool is_final = true)
- : m_description(move(type))
- , m_supertypes(move(supertypes))
- , m_is_final(is_final)
- {
- }
-
- auto& description() const { return m_description; }
-
- auto& function() const { return m_description.get<FunctionType>(); }
- auto& unsafe_function() const { return m_description.unsafe_get<FunctionType>(); }
- bool is_function() const { return m_description.has<FunctionType>(); }
-
- auto& struct_() const { return m_description.get<StructType>(); }
- bool is_struct() const { return m_description.has<StructType>(); }
-
- auto& array() const { return m_description.get<ArrayType>(); }
- bool is_array() const { return m_description.has<ArrayType>(); }
-
- // sub final? x* ct
- auto& supertypes() const { return m_supertypes; }
- bool is_final() const { return m_is_final; }
-
- auto& rec_group() const { return m_rec_group; }
- void set_rec_group(RecGroupSpan span) { m_rec_group = span; }
-
- ByteString name() const
- {
- return m_description.visit(
- [](FunctionType const&) -> ByteString { return "function type"; },
- [](StructType const&) -> ByteString { return "struct type"; },
- [](ArrayType const&) -> ByteString { return "array type"; });
- }
-
- static ParseResult<Type> parse(ConstrainedStream& stream, Optional<u8> leading_tag = {});
-
- private:
- CompositeType m_description;
- Vector<TypeIndex> m_supertypes;
- bool m_is_final { true };
- RecGroupSpan m_rec_group;
- };
-
- TypeSection() = default;
-
- explicit TypeSection(Vector<Type> types)
- : m_types(move(types))
- {
- }
-
- auto& types() const { return m_types; }
-
- static ParseResult<TypeSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Type> m_types;
-};
-
-class ImportSection {
-public:
- class Import {
- public:
- using ImportDesc = Variant<TypeIndex, TableType, MemoryType, GlobalType, FunctionType, TagType>;
- Import(ByteString module, ByteString name, ImportDesc description)
- : m_module(move(module))
- , m_name(move(name))
- , m_description(move(description))
- {
- }
-
- auto& module() const { return m_module; }
- auto& name() const { return m_name; }
- auto& description() const { return m_description; }
-
- static ParseResult<Import> parse(ConstrainedStream& stream);
-
- private:
- template<typename T>
- static ParseResult<Import> parse_with_type(auto&& stream, auto&& module, auto&& name)
- {
- auto result = TRY(T::parse(stream));
- return Import { module, name, result };
- }
-
- ByteString m_module;
- ByteString m_name;
- ImportDesc m_description;
- };
-
-public:
- ImportSection() = default;
-
- explicit ImportSection(Vector<Import> imports)
- : m_imports(move(imports))
- {
- }
-
- auto& imports() const { return m_imports; }
-
- static ParseResult<ImportSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Import> m_imports;
-};
-
-class FunctionSection {
-public:
- FunctionSection() = default;
-
- explicit FunctionSection(Vector<TypeIndex> types)
- : m_types(move(types))
- {
- }
-
- auto& types() const { return m_types; }
-
- static ParseResult<FunctionSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<TypeIndex> m_types;
-};
-
-class Expression {
-public:
- explicit Expression(Vector<Instruction> instructions)
- : m_instructions(move(instructions))
- {
- }
-
- auto& instructions() const { return m_instructions; }
-
- static ParseResult<Expression> parse(ConstrainedStream& stream, Optional<size_t> size_hint = {});
-
- void set_stack_usage_hint(size_t value) const { m_stack_usage_hint = value; }
- auto stack_usage_hint() const { return m_stack_usage_hint; }
-
- mutable CompiledInstructions compiled_instructions;
-
-private:
- Vector<Instruction> m_instructions;
- mutable Optional<size_t> m_stack_usage_hint;
-};
-
-class TableSection {
-public:
- class Table {
- public:
- explicit Table(TableType type, Expression initializer)
- : m_type(move(type))
- , m_initializer(move(initializer))
- {
- }
-
- auto& type() const { return m_type; }
- auto& initializer() const { return m_initializer; }
-
- static ParseResult<Table> parse(ConstrainedStream& stream);
-
- private:
- TableType m_type;
- Expression m_initializer;
- };
-
-public:
- TableSection() = default;
-
- explicit TableSection(Vector<Table> tables)
- : m_tables(move(tables))
- {
- }
-
- auto& tables() const { return m_tables; }
-
- static ParseResult<TableSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Table> m_tables;
-};
-
-class MemorySection {
-public:
- class Memory {
- public:
- explicit Memory(MemoryType type)
- : m_type(move(type))
- {
- }
-
- auto& type() const { return m_type; }
-
- static ParseResult<Memory> parse(ConstrainedStream& stream);
-
- private:
- MemoryType m_type;
- };
-
-public:
- MemorySection() = default;
-
- explicit MemorySection(Vector<Memory> memories)
- : m_memories(move(memories))
- {
- }
-
- auto& memories() const { return m_memories; }
-
- static ParseResult<MemorySection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Memory> m_memories;
-};
-
-class GlobalSection {
-public:
- class Global {
- public:
- explicit Global(GlobalType type, Expression expression)
- : m_type(move(type))
- , m_expression(move(expression))
- {
- }
-
- auto& type() const { return m_type; }
- auto& expression() const { return m_expression; }
-
- static ParseResult<Global> parse(ConstrainedStream& stream);
-
- private:
- GlobalType m_type;
- Expression m_expression;
- };
-
-public:
- GlobalSection() = default;
-
- explicit GlobalSection(Vector<Global> entries)
- : m_entries(move(entries))
- {
- }
-
- auto& entries() const { return m_entries; }
-
- static ParseResult<GlobalSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Global> m_entries;
-};
-
-class ExportSection {
-private:
- using ExportDesc = Variant<FunctionIndex, TableIndex, MemoryIndex, GlobalIndex, TagIndex>;
-
-public:
- class Export {
- public:
- explicit Export(ByteString name, ExportDesc description)
- : m_name(move(name))
- , m_description(move(description))
- {
- }
-
- auto& name() const { return m_name; }
- auto& description() const { return m_description; }
-
- static ParseResult<Export> parse(ConstrainedStream& stream);
-
- private:
- ByteString m_name;
- ExportDesc m_description;
- };
-
- ExportSection() = default;
-
- explicit ExportSection(Vector<Export> entries)
- : m_entries(move(entries))
- {
- }
-
- auto& entries() const { return m_entries; }
-
- static ParseResult<ExportSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Export> m_entries;
-};
-
-class StartSection {
-public:
- class StartFunction {
- public:
- explicit StartFunction(FunctionIndex index)
- : m_index(index)
- {
- }
-
- auto& index() const { return m_index; }
-
- static ParseResult<StartFunction> parse(ConstrainedStream& stream);
-
- private:
- FunctionIndex m_index;
- };
-
- StartSection() = default;
-
- explicit StartSection(Optional<StartFunction> func)
- : m_function(move(func))
- {
- }
-
- auto& function() const { return m_function; }
-
- static ParseResult<StartSection> parse(ConstrainedStream& stream);
-
-private:
- Optional<StartFunction> m_function;
-};
-
-class ElementSection {
-public:
- struct Active {
- TableIndex index;
- Expression expression;
- };
- struct Declarative {
- };
- struct Passive {
- };
-
- struct Element {
- static ParseResult<Element> parse(ConstrainedStream&);
-
- ValueType type;
- Vector<Expression> init;
- Variant<Active, Passive, Declarative> mode;
- };
-
- ElementSection() = default;
-
- explicit ElementSection(Vector<Element> segs)
- : m_segments(move(segs))
- {
- }
-
- auto& segments() const { return m_segments; }
-
- static ParseResult<ElementSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Element> m_segments;
-};
-
-class Locals {
-public:
- explicit Locals(u32 n, ValueType type)
- : m_n(n)
- , m_type(type)
- {
- }
-
- // Yikes...
- auto n() const { return m_n; }
- auto& type() const { return m_type; }
-
- static ParseResult<Locals> parse(ConstrainedStream& stream);
-
-private:
- u32 m_n { 0 };
- ValueType m_type;
-};
-
-class CodeSection {
-public:
- // https://webassembly.github.io/spec/core/bikeshed/#binary-func
- class Func {
- public:
- explicit Func(Vector<Locals> locals, Expression body)
- : m_locals(move(locals))
- , m_body(move(body))
- {
- for (auto const& local : m_locals)
- m_total_local_count += local.n();
- }
-
- auto& locals() const { return m_locals; }
- auto& body() const { return m_body; }
-
- static ParseResult<Func> parse(ConstrainedStream& stream, size_t size_hint);
-
- auto total_local_count() const { return m_total_local_count; }
-
- private:
- Vector<Locals> m_locals;
- Expression m_body;
- size_t m_total_local_count { 0 };
- };
- class Code {
- public:
- explicit Code(u32 size, Func func)
- : m_size(size)
- , m_func(move(func))
- {
- }
-
- auto size() const { return m_size; }
- auto& func() const { return m_func; }
-
- static ParseResult<Code> parse(ConstrainedStream& stream);
-
- private:
- u32 m_size { 0 };
- Func m_func;
- };
-
- CodeSection() = default;
-
- explicit CodeSection(Vector<Code> funcs)
- : m_functions(move(funcs))
- {
- }
-
- auto& functions() const { return m_functions; }
-
- static ParseResult<CodeSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Code> m_functions;
-};
-
-class DataSection {
-public:
- class Data {
- public:
- struct Passive {
- Vector<u8> init;
- };
- struct Active {
- Vector<u8> init;
- MemoryIndex index;
- Expression offset;
- };
- using Value = Variant<Passive, Active>;
-
- explicit Data(Value value)
- : m_value(move(value))
- {
- }
-
- auto& value() const { return m_value; }
-
- static ParseResult<Data> parse(ConstrainedStream& stream);
-
- private:
- Value m_value;
- };
-
- DataSection() = default;
-
- explicit DataSection(Vector<Data> data)
- : m_data(move(data))
- {
- }
-
- auto& data() const { return m_data; }
-
- static ParseResult<DataSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<Data> m_data;
-};
-
-class DataCountSection {
-public:
- DataCountSection() = default;
-
- explicit DataCountSection(Optional<u32> count)
- : m_count(move(count))
- {
- }
-
- auto& count() const { return m_count; }
-
- static ParseResult<DataCountSection> parse(ConstrainedStream& stream);
-
-private:
- Optional<u32> m_count;
-};
-
-class TagSection {
-public:
- TagSection() = default;
-
- explicit TagSection(Vector<TagType> tags)
- : m_tags(move(tags))
- {
- }
-
- auto& tags() const { return m_tags; }
-
- static ParseResult<TagSection> parse(ConstrainedStream& stream);
-
-private:
- Vector<TagType> m_tags;
-};
-
-enum class CompileToNative : u8 {
- No,
- Yes,
-};
-
-// Lightweight per-module compile stats accumulator. Exposed to embedders via record_module_stats() below.
-// The cranelift_* and cache_hit fields are filled in by compile_module_to_native() once native compilation actually runs (possibly on another thread).
-struct ModuleStats {
- Array<u8, 32> wasm_hash {};
- size_t input_size_bytes { 0 };
- AK::Duration parse_time;
- AK::Duration validate_time;
- AK::Duration cranelift_time;
- size_t cranelift_blob_size_bytes { 0 };
- size_t function_count { 0 };
- size_t tier_up_function_count { 0 }; // functions instrumented with tier-up checkpoints
- size_t tier_up_checkpoint_count { 0 }; // total tier-up checkpoints inserted across the module
- bool cache_hit { false };
-};
-
-// Caller-supplied hooks for the Cranelift on-disk cache.
-// - `wasm_hash` is a 32-byte digest of the wasm bytes; embedded in produced blobs and verified against `existing_blob` before any install.
-// - `existing_blob` is the prior cache hit (or empty for a miss); the native-compile pass tries to install it before falling through to cranelift.
-// Owned, since the compile may run asynchronously long after the config was assembled.
-// - `on_compiled` is invoked exactly once if a fresh blob was produced; never invoked on a cache hit nor when no cranelift output was captured.
-struct CompileCacheConfig {
- Array<u8, 32> wasm_hash {};
- ByteBuffer existing_blob;
- AK::Function<void(ByteBuffer)> on_compiled;
-};
-
-class WASM_API Module : public AtomicRefCounted<Module>
- , public Weakable<Module> {
-public:
- enum class ValidationStatus {
- Unchecked,
- Invalid,
- Valid,
- };
-
- static constexpr Array<u8, 4> wasm_magic { 0, 'a', 's', 'm' };
- static constexpr Array<u8, 4> wasm_version { 1, 0, 0, 0 };
-
- Module() = default;
-
- auto& custom_sections() { return m_custom_sections; }
- auto& custom_sections() const { return m_custom_sections; }
- auto& type_section() const { return m_type_section; }
- auto& type_section() { return m_type_section; }
- auto& import_section() const { return m_import_section; }
- auto& import_section() { return m_import_section; }
- auto& function_section() { return m_function_section; }
- auto& function_section() const { return m_function_section; }
- auto& table_section() { return m_table_section; }
- auto& table_section() const { return m_table_section; }
- auto& memory_section() { return m_memory_section; }
- auto& memory_section() const { return m_memory_section; }
- auto& global_section() { return m_global_section; }
- auto& global_section() const { return m_global_section; }
- auto& export_section() { return m_export_section; }
- auto& export_section() const { return m_export_section; }
- auto& start_section() { return m_start_section; }
- auto& start_section() const { return m_start_section; }
- auto& element_section() { return m_element_section; }
- auto& element_section() const { return m_element_section; }
- auto& code_section() { return m_code_section; }
- auto& code_section() const { return m_code_section; }
- auto& data_section() { return m_data_section; }
- auto& data_section() const { return m_data_section; }
- auto& data_count_section() { return m_data_count_section; }
- auto& data_count_section() const { return m_data_count_section; }
- auto& tag_section() { return m_tag_section; }
- auto& tag_section() const { return m_tag_section; }
-
- void set_validation_status(ValidationStatus status, Badge<Validator>) { set_validation_status(status); }
- ValidationStatus validation_status() const { return m_validation_status; }
- StringView validation_error() const LIFETIME_BOUND { return *m_validation_error; }
- void set_validation_error(ByteString error) { m_validation_error = move(error); }
- bool has_attempted_cranelift_compilation() const { return m_cranelift_compilation_state.load(AK::MemoryOrder::memory_order_acquire) == 2; }
- bool try_begin_cranelift_compilation() const
- {
- u8 not_started = 0;
- return m_cranelift_compilation_state.compare_exchange_strong(not_started, 1, AK::MemoryOrder::memory_order_acq_rel);
- }
- void finish_cranelift_compilation() const
- {
- MutexLocker locker(m_cranelift_compilation_mutex);
- m_cranelift_compilation_state.store(2, AK::MemoryOrder::memory_order_release);
- m_cranelift_compilation_state_changed.broadcast();
- }
- void wait_for_cranelift_compilation() const
- {
- if (m_cranelift_compilation_state.load(AK::MemoryOrder::memory_order_acquire) != 1)
- return;
-
- MutexLocker locker(m_cranelift_compilation_mutex);
- m_cranelift_compilation_state_changed.wait_while([this] {
- return m_cranelift_compilation_state.load(AK::MemoryOrder::memory_order_acquire) == 1;
- });
- }
-
- // Disk-cache config for native compilation. Parked here by the embedder before compilation is kicked off, and consumed by whichever path ends up driving compile_module_to_native() first.
- void set_cranelift_cache_config(CompileCacheConfig config) { m_cranelift_cache_config = move(config); }
- Optional<CompileCacheConfig> take_cranelift_cache_config() { return move(m_cranelift_cache_config); }
-
- // Compile stats parked here by the embedder; compile_module_to_native() fills in the cranelift_* / cache_hit fields once native compilation runs, then records them.
- void set_compile_stats(ModuleStats stats) { m_compile_stats = move(stats); }
- Optional<ModuleStats> take_compile_stats() { return move(m_compile_stats); }
-
- static ParseResult<NonnullRefPtr<Module>> parse(Stream& stream);
-
- size_t minimum_call_record_allocation_size() const { return m_minimum_call_record_allocation_size; }
- void set_minimum_call_record_allocation_size(size_t size) { m_minimum_call_record_allocation_size = size; }
-
- // The defined type of each (flattened) type-section entry; filled in during validation.
- // https://webassembly.github.io/spec/core/valid/conventions.html#defined-types
- auto& canonical_types() const { return m_canonical_types; }
- void set_canonical_types(Vector<DefinedType const*> types) { m_canonical_types = move(types); }
-
-private:
- void set_validation_status(ValidationStatus status) { m_validation_status = status; }
- void preprocess();
-
- Vector<CustomSection> m_custom_sections;
- TypeSection m_type_section;
- ImportSection m_import_section;
- FunctionSection m_function_section;
- TableSection m_table_section;
- MemorySection m_memory_section;
- GlobalSection m_global_section;
- ExportSection m_export_section;
- StartSection m_start_section;
- ElementSection m_element_section;
- CodeSection m_code_section;
- DataSection m_data_section;
- DataCountSection m_data_count_section;
- TagSection m_tag_section;
-
- ValidationStatus m_validation_status { ValidationStatus::Unchecked };
- Optional<ByteString> m_validation_error;
- mutable Atomic<u8> m_cranelift_compilation_state { 0 };
- mutable Mutex m_cranelift_compilation_mutex;
- mutable ConditionVariable m_cranelift_compilation_state_changed { m_cranelift_compilation_mutex };
- Optional<CompileCacheConfig> m_cranelift_cache_config;
- Optional<ModuleStats> m_compile_stats;
-
- Vector<DefinedType const*> m_canonical_types;
-
- size_t m_minimum_call_record_allocation_size { 0 };
-};
-
-CompiledInstructions try_compile_instructions(Expression const&, Span<FunctionType const> functions, Span<CodeSection::Func const* const> callee_bodies = {}, size_t current_function_index = 0, size_t caller_local_count = 0, size_t imported_function_count = 0);
-ErrorOr<void, ValidationError> ensure_cranelift_compiled(Module&);
-WASM_API void start_cranelift_compilation(Module&);
-bool try_cranelift_compile(CompiledInstructions& compiled, u32 result_arity = 0);
-void flush_cranelift_batch();
-void discard_cranelift_batch();
-
-void compile_module_to_native(Module&);
-
-WASM_API ByteString const& cranelift_compiler_path();
-WASM_API ErrorOr<Core::AnonymousBuffer> compile_cranelift_buffer(Core::AnonymousBuffer const&);
-
-using CraneliftCompileCallback = Function<Core::AnonymousBuffer(Core::AnonymousBuffer const&)>;
-WASM_API void set_cranelift_compile_callback(CraneliftCompileCallback);
-
-WASM_API void record_module_stats(ModuleStats);
-WASM_API void dump_module_stats();
-
-// Cranelift disk-cache plumbing. Validator drives these around CodeSection validation:
-// 1. set_cranelift_active_function_index() before each function so cache-hit installs
-// and post-compile capture know which function they're talking about.
-// 2. begin_cranelift_cache_capture() to start collecting compiled bytes + relocs.
-// 3. try_install_cranelift_cache_blob() with the wasm-bytes hash + stored blob; if
-// it returns true, individual try_cranelift_compile calls will short-circuit by
-// installing from the stashed records instead of queueing fresh compiles.
-// 4. After flush, serialize_cranelift_cache_blob() returns a blob to hand to the
-// cache store (or {} if nothing was captured); abort_cranelift_cache_capture()
-// throws the capture away.
-void set_cranelift_active_function_index(u32 function_index);
-void begin_cranelift_cache_capture();
-void abort_cranelift_cache_capture();
-void abort_cranelift_cache_install();
-Optional<ByteBuffer> serialize_cranelift_cache_blob(ReadonlyBytes wasm_hash);
-bool try_install_cranelift_cache_blob(ReadonlyBytes expected_wasm_hash, ReadonlyBytes blob);
-
-}
diff --git a/Libraries/LibWasm/WASI/Wasi.cpp b/Libraries/LibWasm/WASI/Wasi.cpp
deleted file mode 100644
index f0cf49ec5a5..00000000000
--- a/Libraries/LibWasm/WASI/Wasi.cpp
+++ /dev/null
@@ -1,1323 +0,0 @@
-/*
- * Copyright (c) 2023, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ByteReader.h>
-#include <AK/Checked.h>
-#include <AK/Debug.h>
-#include <AK/FlyString.h>
-#include <AK/Random.h>
-#include <AK/Span.h>
-#include <AK/Tuple.h>
-#include <AK/kmalloc.h>
-#include <LibWasm/AbstractMachine/Configuration.h>
-#include <LibWasm/Wasi.h>
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <time.h>
-#include <unistd.h>
-
-namespace Wasm::Wasi::ABI {
-
-template<typename T>
-Wasm::Value CompatibleValue<T>::to_wasm_value() const
-{
- return Wasm::Value(value);
-}
-
-template<typename T>
-T deserialize(CompatibleValue<T> const& data)
-{
- return deserialize<T>(Array { ReadonlyBytes { &data.value, sizeof(data.value) } });
-}
-
-template<typename T, size_t N>
-void serialize(T const& value, Array<Bytes, N> bytes)
-{
- if constexpr (IsEnum<T>)
- return serialize(to_underlying(value), move(bytes));
- else if constexpr (IsIntegral<T>)
- ReadonlyBytes { &value, sizeof(value) }.copy_to(bytes[0]);
- else if constexpr (IsSpecializationOf<T, DistinctNumeric>)
- return serialize(value.value(), move(bytes));
- else
- return value.serialize_into(move(bytes));
-}
-
-template<typename T, size_t N>
-T deserialize(Array<ReadonlyBytes, N> const& bytes)
-{
- if constexpr (IsEnum<T>) {
- return static_cast<T>(deserialize<UnderlyingType<T>>(bytes));
- } else if constexpr (IsIntegral<T>) {
- T value;
- ByteReader::load(bytes[0].data(), value);
- return value;
- } else if constexpr (IsSpecializationOf<T, DistinctNumeric>) {
- return deserialize<RemoveCVReference<decltype(T(0).value())>>(bytes);
- } else {
- return T::read_from(bytes);
- }
-}
-
-template<typename T>
-CompatibleValue<T> to_compatible_value(Wasm::Value const& value)
-{
- using Type = typename ToCompatibleValue<T>::Type;
- // Note: the type can't be something else, we've already checked before through the function type's runtime checker.
- auto converted_value = value.template to<Type>();
- return { .value = converted_value };
-}
-
-}
-
-namespace Wasm::Wasi {
-
-static ErrorOr<size_t> checked_byte_count(size_t element_size, Size count)
-{
- Checked<size_t> byte_count { static_cast<u32>(count) };
- byte_count *= element_size;
- if (byte_count.has_overflow())
- return Error::from_errno(ENOBUFS);
- return byte_count.value();
-}
-
-static bool memory_range_is_in_bounds(MemoryInstance const& memory, size_t address, size_t byte_count)
-{
- return address <= memory.size() && byte_count <= memory.size() - address;
-}
-
-static Optional<Bytes> contiguous_memory_bytes(MemoryInstance& memory, size_t address, size_t byte_count)
-{
- if (!memory_range_is_in_bounds(memory, address, byte_count))
- return {};
- if (memory.data().contiguous_bytes_from(address, byte_count) < byte_count)
- return {};
- return Bytes { memory.data().offset_pointer(address), byte_count };
-}
-
-void ArgsSizes::serialize_into(Array<Bytes, 2> bytes) const
-{
- ABI::serialize(count, Array { bytes[0] });
- ABI::serialize(size, Array { bytes[1] });
-}
-
-void EnvironSizes::serialize_into(Array<Bytes, 2> bytes) const
-{
- ABI::serialize(count, Array { bytes[0] });
- ABI::serialize(size, Array { bytes[1] });
-}
-
-void SockRecvResult::serialize_into(Array<Bytes, 2> bytes) const
-{
- ABI::serialize(size, Array { bytes[0] });
- ABI::serialize(roflags, Array { bytes[1] });
-}
-
-void ROFlags::serialize_into(Array<Bytes, 1> bytes) const
-{
- ABI::serialize(data, Array { bytes[0] });
-}
-
-template<typename T>
-void LittleEndian<T>::serialize_into(Array<Bytes, 1> bytes) const
-{
- ABI::serialize(m_value, move(bytes));
-}
-
-template<typename T>
-LittleEndian<T> LittleEndian<T>::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- auto swapped = ABI::deserialize<T>(bytes);
- return bit_cast<LittleEndian<T>>(swapped);
-}
-
-Rights Rights::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- Rights rights { .data = 0 };
- bytes[0].copy_to(rights.data.bytes());
- return rights;
-}
-
-void Rights::serialize_into(Array<Bytes, 1> bytes) const
-{
- data.bytes().copy_to(bytes[0]);
-}
-
-void FDFlags::serialize_into(Array<Bytes, 1> bytes) const
-{
- ReadonlyBytes { &data, sizeof(data) }.copy_to(bytes[0]);
-}
-
-FDFlags FDFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- FDFlags flags { .data = 0 };
- bytes[0].copy_to(flags.data.bytes());
- return flags;
-}
-
-FSTFlags FSTFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- FSTFlags flags { .data = 0 };
- bytes[0].copy_to(flags.data.bytes());
- return flags;
-}
-
-OFlags OFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- OFlags flags { .data = 0 };
- bytes[0].copy_to(flags.data.bytes());
- return flags;
-}
-
-SDFlags SDFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- SDFlags flags { .data = 0 };
- bytes[0].copy_to(flags.data.bytes());
- return flags;
-}
-
-void FDStat::serialize_into(Array<Bytes, 1> bytes) const
-{
- auto data = bytes[0];
- ABI::serialize(fs_filetype, Array { data.slice(offsetof(FDStat, fs_filetype), sizeof(fs_filetype)) });
- ABI::serialize(fs_flags, Array { data.slice(offsetof(FDStat, fs_flags), sizeof(fs_flags)) });
- ABI::serialize(fs_rights_base, Array { data.slice(offsetof(FDStat, fs_rights_base), sizeof(fs_rights_base)) });
- ABI::serialize(fs_rights_inheriting, Array { data.slice(offsetof(FDStat, fs_rights_inheriting), sizeof(fs_rights_inheriting)) });
-}
-
-void PreStat::serialize_into(Array<Bytes, 1> bytes) const
-{
- auto data = bytes[0];
- ABI::serialize(type, Array { data.slice(0, sizeof(type)) });
- if (type == PreOpenType::Dir)
- ABI::serialize(dir, Array { data.slice(offsetof(PreStat, dir), sizeof(dir)) });
- else
- VERIFY_NOT_REACHED();
-}
-
-void PreStatDir::serialize_into(Array<Bytes, 1> bytes) const
-{
- ABI::serialize(pr_name_len, move(bytes));
-}
-
-void FileStat::serialize_into(Array<Bytes, 1> bytes) const
-{
- auto data = bytes[0];
- ABI::serialize(dev, Array { data.slice(0, sizeof(dev)) });
- ABI::serialize(ino, Array { data.slice(offsetof(FileStat, ino), sizeof(ino)) });
- ABI::serialize(filetype, Array { data.slice(offsetof(FileStat, filetype), sizeof(filetype)) });
- ABI::serialize(nlink, Array { data.slice(offsetof(FileStat, nlink), sizeof(nlink)) });
- ABI::serialize(size, Array { data.slice(offsetof(FileStat, size), sizeof(size)) });
- ABI::serialize(atim, Array { data.slice(offsetof(FileStat, atim), sizeof(atim)) });
- ABI::serialize(mtim, Array { data.slice(offsetof(FileStat, mtim), sizeof(mtim)) });
- ABI::serialize(ctim, Array { data.slice(offsetof(FileStat, ctim), sizeof(ctim)) });
-}
-
-RIFlags RIFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- RIFlags flags { .data = 0 };
- bytes[0].copy_to(flags.data.bytes());
- return flags;
-}
-
-LookupFlags LookupFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- LookupFlags flags { .data = 0 };
- bytes[0].copy_to(flags.data.bytes());
- return flags;
-}
-
-CIOVec CIOVec::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- return CIOVec {
- .buf = ABI::deserialize<decltype(buf)>(Array { bytes[0].slice(offsetof(CIOVec, buf), sizeof(buf)) }),
- .buf_len = ABI::deserialize<decltype(buf_len)>(Array { bytes[0].slice(offsetof(CIOVec, buf_len), sizeof(buf_len)) }),
- };
-}
-
-IOVec IOVec::read_from(Array<ReadonlyBytes, 1> const& bytes)
-{
- return IOVec {
- .buf = ABI::deserialize<decltype(buf)>(Array { bytes[0].slice(offsetof(IOVec, buf), sizeof(buf)) }),
- .buf_len = ABI::deserialize<decltype(buf_len)>(Array { bytes[0].slice(offsetof(IOVec, buf_len), sizeof(buf_len)) }),
- };
-}
-
-template<typename T>
-ErrorOr<Vector<T>> copy_typed_array(Configuration& configuration, Pointer<T> source, Size count)
-{
- Vector<T> values;
- TRY(values.try_ensure_capacity(count));
- auto* memory = configuration.store().get(MemoryAddress { 0 });
- if (!memory)
- return Error::from_errno(ENOMEM);
-
- size_t address = source.value();
- auto byte_count = TRY(checked_byte_count(sizeof(T), count));
- if (!memory_range_is_in_bounds(*memory, address, byte_count))
- return Error::from_errno(ENOBUFS);
-
- for (Size i = 0; i < count; i += 1) {
- u8 bytes[sizeof(T)];
- memory->data().copy_to(address, { bytes, sizeof(bytes) });
- values.unchecked_append(T::read_from(Array { ReadonlyBytes { bytes, sizeof(bytes) } }));
- address += sizeof(T);
- }
-
- return values;
-}
-
-template<typename T>
-ErrorOr<void> copy_typed_value_to(Configuration& configuration, T const& value, Pointer<T> destination)
-{
- auto* memory = configuration.store().get(MemoryAddress { 0 });
- if (!memory)
- return Error::from_errno(ENOMEM);
-
- size_t address = destination.value();
- if (!memory_range_is_in_bounds(*memory, address, sizeof(T)))
- return Error::from_errno(ENOBUFS);
-
- u8 bytes[sizeof(T)];
- ABI::serialize(value, Array { Bytes { bytes, sizeof(bytes) } });
- memory->data().overwrite(address, bytes, sizeof(bytes));
- return {};
-}
-
-template<typename T>
-ErrorOr<Span<T>> slice_typed_memory(Configuration& configuration, Pointer<T> source, Size count)
-{
- auto* memory = configuration.store().get(MemoryAddress { 0 });
- if (!memory)
- return Error::from_errno(ENOMEM);
-
- size_t address = source.value();
- auto byte_count = TRY(checked_byte_count(sizeof(T), count));
- auto bytes = contiguous_memory_bytes(*memory, address, byte_count);
- if (!bytes.has_value())
- return Error::from_errno(ENOBUFS);
-
- return Span<T>(reinterpret_cast<T*>(bytes->data()), static_cast<size_t>(count));
-}
-
-template<typename T>
-ErrorOr<Span<T const>> slice_typed_memory(Configuration& configuration, ConstPointer<T> source, Size count)
-{
- auto* memory = configuration.store().get(MemoryAddress { 0 });
- if (!memory)
- return Error::from_errno(ENOMEM);
-
- size_t address = source.value();
- auto byte_count = TRY(checked_byte_count(sizeof(T), count));
- auto bytes = contiguous_memory_bytes(*memory, address, byte_count);
- if (!bytes.has_value())
- return Error::from_errno(ENOBUFS);
-
- return Span<T const>(reinterpret_cast<T const*>(bytes->data()), static_cast<size_t>(count));
-}
-
-static ErrorOr<size_t> copy_string_including_terminating_null(Configuration& configuration, StringView string, Pointer<u8> target)
-{
- auto slice = TRY(slice_typed_memory(configuration, target, string.bytes().size() + 1));
- string.bytes().copy_to(slice);
- slice[string.bytes().size()] = 0;
- return slice.size();
-}
-
-static ErrorOr<size_t> copy_string_excluding_terminating_null(Configuration& configuration, StringView string, Pointer<u8> target, Size target_length)
-{
- auto byte_count = min(string.bytes().size(), target_length);
- auto slice = TRY(slice_typed_memory(configuration, target, byte_count));
- string.bytes().copy_trimmed_to(slice);
- return byte_count;
-}
-
-static Errno errno_value_from_errno(int value);
-static FileType file_type_of(struct stat const& buf);
-static FDFlags fd_flags_of(struct stat const& buf);
-
-Vector<AK::String> const& Implementation::arguments() const
-{
- return cache.cached_arguments.ensure([&] {
- if (provide_arguments)
- return provide_arguments();
- return Vector<AK::String> {};
- });
-}
-
-Vector<AK::String> const& Implementation::environment() const
-{
- return cache.cached_environment.ensure([&] {
- if (provide_environment)
- return provide_environment();
- return Vector<AK::String> {};
- });
-}
-
-Vector<Implementation::MappedPath> const& Implementation::preopened_directories() const
-{
- return cache.cached_preopened_directories.ensure([&] {
- if (provide_preopened_directories)
- return provide_preopened_directories();
- return Vector<MappedPath> {};
- });
-}
-
-Implementation::Descriptor Implementation::map_fd(FD fd)
-{
- u32 fd_value = fd.value();
- if (auto* value = m_fd_map.find(fd_value))
- return value->downcast<Descriptor>();
-
- return UnmappedDescriptor(fd_value);
-}
-
-ErrorOr<Result<void>> Implementation::impl$args_get(Configuration& configuration, Pointer<Pointer<u8>> argv, Pointer<u8> argv_buf)
-{
- UnderlyingPointerType raw_argv_buffer = argv_buf.value();
- UnderlyingPointerType raw_argv = argv.value();
-
- for (auto& entry : arguments()) {
- auto ptr = Pointer<u8> { raw_argv_buffer };
- auto byte_count = TRY(copy_string_including_terminating_null(configuration, entry.bytes_as_string_view(), ptr));
- raw_argv_buffer += byte_count;
-
- TRY(copy_typed_value_to(configuration, ptr, Pointer<Pointer<u8>> { raw_argv }));
- raw_argv += sizeof(ptr);
- }
-
- return Result<void> {};
-}
-
-ErrorOr<Result<ArgsSizes>> Implementation::impl$args_sizes_get(Configuration&)
-{
- size_t count = 0;
- size_t total_size = 0;
- for (auto& entry : arguments()) {
- count += 1;
- total_size += entry.bytes().size() + 1; // 1 extra byte for terminating null.
- }
-
- return Result<ArgsSizes>(ArgsSizes {
- count,
- total_size,
- });
-}
-
-ErrorOr<Result<void>> Implementation::impl$environ_get(Configuration& configuration, Pointer<Pointer<u8>> environ, Pointer<u8> environ_buf)
-{
- UnderlyingPointerType raw_environ_buffer = environ_buf.value();
- UnderlyingPointerType raw_environ = environ.value();
-
- for (auto& entry : environment()) {
- auto ptr = Pointer<u8> { raw_environ_buffer };
- auto byte_count = TRY(copy_string_including_terminating_null(configuration, entry.bytes_as_string_view(), ptr));
- raw_environ_buffer += byte_count;
-
- TRY(copy_typed_value_to(configuration, ptr, Pointer<Pointer<u8>> { raw_environ }));
- raw_environ += sizeof(ptr);
- }
-
- return Result<void> {};
-}
-
-ErrorOr<Result<EnvironSizes>> Implementation::impl$environ_sizes_get(Configuration&)
-{
- size_t count = 0;
- size_t total_size = 0;
- for (auto& entry : environment()) {
- count += 1;
- total_size += entry.bytes().size() + 1; // 1 extra byte for terminating null.
- }
-
- return Result<EnvironSizes>(EnvironSizes {
- count,
- total_size,
- });
-}
-
-ErrorOr<void> Implementation::impl$proc_exit(Configuration&, ExitCode exit_code)
-{
- return Error::from_errno(-static_cast<i32>(exit_code + 1));
-}
-
-ErrorOr<Result<void>> Implementation::impl$fd_close(Configuration&, FD fd)
-{
- return map_fd(fd).visit(
- [&](u32 fd) -> Result<void> {
- if (close(bit_cast<i32>(fd)) != 0)
- return errno_value_from_errno(errno);
- return {};
- },
- [&](PreopenedDirectoryDescriptor) -> Result<void> {
- return errno_value_from_errno(EISDIR);
- },
- [&](UnmappedDescriptor) -> Result<void> {
- return errno_value_from_errno(EBADF);
- });
-}
-
-ErrorOr<Result<Size>> Implementation::impl$fd_write(Configuration& configuration, FD fd, Pointer<CIOVec> iovs, Size iovs_len)
-{
- auto mapped_fd = map_fd(fd);
- if (!mapped_fd.has<u32>())
- return errno_value_from_errno(EBADF);
-
- u32 fd_value = mapped_fd.get<u32>();
- Size bytes_written = 0;
- for (auto& iovec : TRY(copy_typed_array(configuration, iovs, iovs_len))) {
- auto slice = TRY(slice_typed_memory(configuration, iovec.buf, iovec.buf_len));
- auto result = write(fd_value, slice.data(), slice.size());
- if (result < 0)
- return errno_value_from_errno(errno);
- bytes_written += static_cast<Size>(result);
- }
- return bytes_written;
-}
-
-ErrorOr<Result<PreStat>> Implementation::impl$fd_prestat_get(Configuration&, FD fd)
-{
- auto& paths = preopened_directories();
- return map_fd(fd).visit(
- [&](UnmappedDescriptor unmapped_fd) -> Result<PreStat> {
- // Map the new fd to the next available directory.
- if (m_first_unmapped_preopened_directory_index >= paths.size())
- return errno_value_from_errno(EBADF);
-
- auto index = m_first_unmapped_preopened_directory_index++;
- m_fd_map.insert(unmapped_fd.value(), PreopenedDirectoryDescriptor(index));
- return PreStat {
- .type = PreOpenType::Dir,
- .dir = PreStatDir {
- .pr_name_len = paths[index].mapped_path.string().bytes().size(),
- },
- };
- },
- [&](u32) -> Result<PreStat> {
- return errno_value_from_errno(EBADF);
- },
- [&](PreopenedDirectoryDescriptor fd) -> Result<PreStat> {
- return PreStat {
- .type = PreOpenType::Dir,
- .dir = PreStatDir {
- .pr_name_len = paths[fd.value()].mapped_path.string().bytes().size(),
- },
- };
- });
-}
-
-ErrorOr<Result<void>> Implementation::impl$fd_prestat_dir_name(Configuration& configuration, FD fd, Pointer<u8> path, Size path_len)
-{
- auto mapped_fd = map_fd(fd);
- if (!mapped_fd.has<PreopenedDirectoryDescriptor>())
- return errno_value_from_errno(EBADF);
-
- auto& entry = preopened_directories()[mapped_fd.get<PreopenedDirectoryDescriptor>().value()];
- auto byte_count = TRY(copy_string_excluding_terminating_null(configuration, entry.mapped_path.string().view(), path, path_len));
- if (byte_count < path_len.value())
- return errno_value_from_errno(ENOBUFS);
-
- return Result<void> {};
-}
-
-ErrorOr<Result<FileStat>> Implementation::impl$path_filestat_get(Configuration& configuration, FD fd, LookupFlags flags, ConstPointer<u8> path, Size path_len)
-{
- auto dir_fd = AT_FDCWD;
-
- auto mapped_fd = map_fd(fd);
- mapped_fd.visit(
- [&](PreopenedDirectoryDescriptor descriptor) {
- auto& entry = preopened_directories()[descriptor.value()];
- dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
- ByteString path = entry.host_path.string();
- return open(path.characters(), O_DIRECTORY, 0);
- });
- entry.opened_fd = dir_fd;
- },
- [&](u32 fd) {
- dir_fd = fd;
- },
- [](UnmappedDescriptor) { });
-
- if (dir_fd < 0 && dir_fd != AT_FDCWD)
- return errno_value_from_errno(errno);
-
- int options = 0;
- if (!flags.bits.symlink_follow)
- options |= AT_SYMLINK_NOFOLLOW;
-
- auto slice = TRY(slice_typed_memory(configuration, path, path_len));
- auto null_terminated_string = ByteString::copy(slice);
-
- struct stat stat_buf;
- if (fstatat(dir_fd, null_terminated_string.characters(), &stat_buf, options) < 0)
- return errno_value_from_errno(errno);
-
- constexpr auto file_type_of = [](struct stat const& buf) {
- if (S_ISDIR(buf.st_mode))
- return FileType::Directory;
- if (S_ISCHR(buf.st_mode))
- return FileType::CharacterDevice;
- if (S_ISBLK(buf.st_mode))
- return FileType::BlockDevice;
- if (S_ISREG(buf.st_mode))
- return FileType::RegularFile;
- if (S_ISFIFO(buf.st_mode))
- return FileType::Unknown; // FIXME: FileType::Pipe is currently not present in WASI (but it should be) so we use Unknown for now.
- if (S_ISLNK(buf.st_mode))
- return FileType::SymbolicLink;
- if (S_ISSOCK(buf.st_mode))
- return FileType::SocketStream;
- return FileType::Unknown;
- };
-
- return Result(FileStat {
- .dev = stat_buf.st_dev,
- .ino = stat_buf.st_ino,
- .filetype = file_type_of(stat_buf),
- .nlink = stat_buf.st_nlink,
- .size = stat_buf.st_size,
- .atim = stat_buf.st_atime,
- .mtim = stat_buf.st_mtime,
- .ctim = stat_buf.st_ctime,
- });
-}
-
-ErrorOr<Result<void>> Implementation::impl$path_create_directory(Configuration& configuration, FD fd, Pointer<u8> path, Size path_len)
-{
- auto dir_fd = AT_FDCWD;
-
- auto mapped_fd = map_fd(fd);
- mapped_fd.visit(
- [&](PreopenedDirectoryDescriptor descriptor) {
- auto& entry = preopened_directories()[descriptor.value()];
- dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
- ByteString path = entry.host_path.string();
- return open(path.characters(), O_DIRECTORY, 0);
- });
- entry.opened_fd = dir_fd;
- },
- [&](u32 fd) {
- dir_fd = fd;
- },
- [](UnmappedDescriptor) { });
-
- if (dir_fd < 0 && dir_fd != AT_FDCWD)
- return errno_value_from_errno(errno);
-
- auto slice = TRY(slice_typed_memory(configuration, path, path_len));
- auto null_terminated_string = ByteString::copy(slice);
-
- if (mkdirat(dir_fd, null_terminated_string.characters(), 0755) < 0)
- return errno_value_from_errno(errno);
-
- return Result<void> {};
-}
-
-ErrorOr<Result<FD>> Implementation::impl$path_open(Configuration& configuration, FD fd, LookupFlags lookup_flags, Pointer<u8> path, Size path_len, OFlags o_flags, Rights, Rights, FDFlags fd_flags)
-{
- auto dir_fd = AT_FDCWD;
-
- auto mapped_fd = map_fd(fd);
- mapped_fd.visit(
- [&](PreopenedDirectoryDescriptor descriptor) {
- auto& entry = preopened_directories()[descriptor.value()];
- dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
- ByteString path = entry.host_path.string();
- return open(path.characters(), O_DIRECTORY, 0);
- });
- entry.opened_fd = dir_fd;
- },
- [&](u32 fd) {
- dir_fd = fd;
- },
- [](UnmappedDescriptor) { });
-
- if (dir_fd < 0 && dir_fd != AT_FDCWD)
- return errno_value_from_errno(errno);
-
- // FIXME: What should we do with dsync/rsync?
-
- int open_flags = 0;
- if (fd_flags.bits.append)
- open_flags |= O_APPEND;
- if (fd_flags.bits.nonblock)
- open_flags |= O_NONBLOCK;
- if (fd_flags.bits.sync)
- open_flags |= O_SYNC;
-
- if (o_flags.bits.trunc)
- open_flags |= O_TRUNC;
- if (o_flags.bits.creat)
- open_flags |= O_CREAT;
- if (o_flags.bits.directory)
- open_flags |= O_DIRECTORY;
- if (o_flags.bits.excl)
- open_flags |= O_EXCL;
-
- if (!lookup_flags.bits.symlink_follow)
- open_flags |= O_NOFOLLOW;
-
- auto path_data = TRY(slice_typed_memory(configuration, path, path_len));
- auto path_string = ByteString::copy(path_data);
-
- dbgln_if(WASI_FINE_GRAINED_DEBUG, "path_open: dir_fd={}, path={}, open_flags={}", dir_fd, path_string, open_flags);
-
- int opened_fd = openat(dir_fd, path_string.characters(), open_flags, 0644);
- if (opened_fd < 0)
- return errno_value_from_errno(errno);
-
- // FIXME: Implement Rights and RightsInheriting.
-
- m_fd_map.insert(opened_fd, static_cast<u32>(opened_fd));
-
- return FD(opened_fd);
-}
-
-ErrorOr<Result<Timestamp>> Implementation::impl$clock_time_get(Configuration&, ClockID id, Timestamp precision)
-{
- constexpr u64 nanoseconds_in_millisecond = 1000'000ull;
- constexpr u64 nanoseconds_in_second = 1000'000'000ull;
-
- clockid_t clock_id;
- switch (id) {
- case ClockID::Realtime:
- if (precision >= nanoseconds_in_millisecond)
- clock_id = CLOCK_REALTIME_COARSE;
- else
- clock_id = CLOCK_REALTIME;
- break;
- case ClockID::Monotonic:
- if (precision >= nanoseconds_in_millisecond)
- clock_id = CLOCK_MONOTONIC_COARSE;
- else
- clock_id = CLOCK_MONOTONIC;
- break;
- case ClockID::ProcessCPUTimeID:
- case ClockID::ThreadCPUTimeID:
- return Errno::NoSys;
- }
-
- struct timespec ts;
- if (clock_gettime(clock_id, &ts) < 0)
- return errno_value_from_errno(errno);
-
- return Result<Timestamp> { static_cast<u64>(ts.tv_sec) * nanoseconds_in_second + static_cast<u64>(ts.tv_nsec) };
-}
-
-ErrorOr<Result<FileStat>> Implementation::impl$fd_filestat_get(Configuration&, FD fd)
-{
- int resolved_fd = -1;
-
- auto mapped_fd = map_fd(fd);
- mapped_fd.visit(
- [&](PreopenedDirectoryDescriptor descriptor) {
- auto& entry = preopened_directories()[descriptor.value()];
- resolved_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
- ByteString path = entry.host_path.string();
- return open(path.characters(), O_DIRECTORY, 0);
- });
- entry.opened_fd = resolved_fd;
- },
- [&](u32 fd) {
- resolved_fd = fd;
- },
- [](UnmappedDescriptor) { });
-
- if (resolved_fd < 0)
- return errno_value_from_errno(errno);
-
- struct stat stat_buf;
- if (fstat(resolved_fd, &stat_buf) < 0)
- return errno_value_from_errno(errno);
-
- constexpr auto file_type_of = [](struct stat const& buf) {
- if (S_ISDIR(buf.st_mode))
- return FileType::Directory;
- if (S_ISCHR(buf.st_mode))
- return FileType::CharacterDevice;
- if (S_ISBLK(buf.st_mode))
- return FileType::BlockDevice;
- if (S_ISREG(buf.st_mode))
- return FileType::RegularFile;
- if (S_ISFIFO(buf.st_mode))
- return FileType::Unknown; // no Pipe? :yakfused:
- if (S_ISLNK(buf.st_mode))
- return FileType::SymbolicLink;
- if (S_ISSOCK(buf.st_mode))
- return FileType::SocketDGram; // :shrug:
- return FileType::Unknown;
- };
-
- return Result(FileStat {
- .dev = stat_buf.st_dev,
- .ino = stat_buf.st_ino,
- .filetype = file_type_of(stat_buf),
- .nlink = stat_buf.st_nlink,
- .size = stat_buf.st_size,
- .atim = stat_buf.st_atime,
- .mtim = stat_buf.st_mtime,
- .ctim = stat_buf.st_ctime,
- });
-}
-
-ErrorOr<Result<void>> Implementation::impl$random_get(Configuration& configuration, Pointer<u8> buf, Size buf_len)
-{
- auto buffer_slice = TRY(slice_typed_memory(configuration, buf, buf_len));
- fill_with_random(buffer_slice);
-
- return Result<void> {};
-}
-
-ErrorOr<Result<Size>> Implementation::impl$fd_read(Configuration& configuration, FD fd, Pointer<IOVec> iovs, Size iovs_len)
-{
- auto mapped_fd = map_fd(fd);
- if (!mapped_fd.has<u32>())
- return errno_value_from_errno(EBADF);
-
- u32 fd_value = mapped_fd.get<u32>();
- Size bytes_read = 0;
- for (auto& iovec : TRY(copy_typed_array(configuration, iovs, iovs_len))) {
- auto slice = TRY(slice_typed_memory(configuration, iovec.buf, iovec.buf_len));
- auto result = read(fd_value, slice.data(), slice.size());
- if (result < 0)
- return errno_value_from_errno(errno);
- bytes_read += static_cast<Size>(result);
- }
- return bytes_read;
-}
-
-ErrorOr<Result<FDStat>> Implementation::impl$fd_fdstat_get(Configuration&, FD fd)
-{
- auto mapped_fd = map_fd(fd);
- auto resolved_fd = -1;
- mapped_fd.visit(
- [&](PreopenedDirectoryDescriptor descriptor) {
- auto& entry = preopened_directories()[descriptor.value()];
- resolved_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
- ByteString path = entry.host_path.string();
- return open(path.characters(), O_DIRECTORY, 0);
- });
- entry.opened_fd = resolved_fd;
- },
- [&](u32 fd) {
- resolved_fd = fd;
- },
- [](UnmappedDescriptor) { });
- if (resolved_fd < 0)
- return errno_value_from_errno(errno);
-
- struct stat stat_buf;
- if (fstat(resolved_fd, &stat_buf) < 0)
- return errno_value_from_errno(errno);
-
- return FDStat {
- .fs_filetype = file_type_of(stat_buf),
- .fs_flags = fd_flags_of(stat_buf),
- .fs_rights_base = Rights { .data = 0 },
- .fs_rights_inheriting = Rights { .data = 0 },
- };
-}
-
-ErrorOr<Result<FileSize>> Implementation::impl$fd_seek(Configuration&, FD fd, FileDelta offset, Whence whence)
-{
- auto mapped_fd = map_fd(fd);
- if (!mapped_fd.has<u32>())
- return errno_value_from_errno(EBADF);
-
- u32 fd_value = mapped_fd.get<u32>();
- auto result = lseek(fd_value, offset, static_cast<int>(whence));
- if (result < 0)
- return errno_value_from_errno(errno);
- return FileSize(result);
-}
-
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wunused-parameter"
-
-ErrorOr<Result<Timestamp>> Implementation::impl$clock_res_get(Configuration&, ClockID id)
-{
- return Errno::NoSys;
-}
-ErrorOr<Result<void>> Implementation::impl$fd_advise(Configuration&, FD, FileSize offset, FileSize len, Advice) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_allocate(Configuration&, FD, FileSize offset, FileSize len) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_datasync(Configuration&, FD) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_flags(Configuration&, FD, FDFlags) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_rights(Configuration&, FD, Rights fs_rights_base, Rights fs_rights_inheriting) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_size(Configuration&, FD, FileSize) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_times(Configuration&, FD, Timestamp atim, Timestamp mtim, FSTFlags) { return Errno::NoSys; }
-ErrorOr<Result<Size>> Implementation::impl$fd_pread(Configuration&, FD, Pointer<IOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
-ErrorOr<Result<Size>> Implementation::impl$fd_pwrite(Configuration&, FD, Pointer<CIOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
-ErrorOr<Result<Size>> Implementation::impl$fd_readdir(Configuration&, FD, Pointer<u8> buf, Size buf_len, DirCookie cookie) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_renumber(Configuration&, FD from, FD to) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$fd_sync(Configuration&, FD) { return Errno::NoSys; }
-ErrorOr<Result<FileSize>> Implementation::impl$fd_tell(Configuration&, FD) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$path_filestat_set_times(Configuration&, FD, LookupFlags, Pointer<u8> path, Size path_len, Timestamp atim, Timestamp mtim, FSTFlags) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$path_link(Configuration&, FD, LookupFlags, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len) { return Errno::NoSys; }
-ErrorOr<Result<Size>> Implementation::impl$path_readlink(Configuration&, FD, LookupFlags, Pointer<u8> path, Size path_len, Pointer<u8> buf, Size buf_len) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$path_remove_directory(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$path_rename(Configuration&, FD, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$path_symlink(Configuration&, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$path_unlink_file(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
-ErrorOr<Result<Size>> Implementation::impl$poll_oneoff(Configuration&, ConstPointer<Subscription> in, Pointer<Event> out, Size nsubscriptions) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$proc_raise(Configuration&, Signal) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$sched_yield(Configuration&) { return Errno::NoSys; }
-ErrorOr<Result<FD>> Implementation::impl$sock_accept(Configuration&, FD fd, FDFlags fd_flags) { return Errno::NoSys; }
-ErrorOr<Result<SockRecvResult>> Implementation::impl$sock_recv(Configuration&, FD fd, Pointer<IOVec> ri_data, Size ri_data_len, RIFlags ri_flags) { return Errno::NoSys; }
-ErrorOr<Result<Size>> Implementation::impl$sock_send(Configuration&, FD fd, Pointer<CIOVec> si_data, Size si_data_len, SIFlags si_flags) { return Errno::NoSys; }
-ErrorOr<Result<void>> Implementation::impl$sock_shutdown(Configuration&, FD fd, SDFlags how) { return Errno::NoSys; }
-
-#pragma GCC diagnostic pop
-
-template<size_t N>
-static Array<Bytes, N> address_spans(Span<Value> values, Configuration& configuration)
-{
- Array<Bytes, N> result {};
- auto& memory = configuration.store().get(MemoryAddress { 0 })->data();
- for (size_t i = 0; i < N; ++i) {
- if (auto address = static_cast<size_t>(values[i].to<i32>()); address <= memory.size())
- result[i] = Bytes { memory.offset_pointer(address), memory.contiguous_bytes_from(address, memory.size() - address) };
- }
- return result;
-}
-
-#define ENUMERATE_FUNCTION_NAMES(M) \
- M(args_get) \
- M(args_sizes_get) \
- M(environ_get) \
- M(environ_sizes_get) \
- M(clock_res_get) \
- M(clock_time_get) \
- M(fd_advise) \
- M(fd_allocate) \
- M(fd_close) \
- M(fd_datasync) \
- M(fd_fdstat_get) \
- M(fd_fdstat_set_flags) \
- M(fd_fdstat_set_rights) \
- M(fd_filestat_get) \
- M(fd_filestat_set_size) \
- M(fd_filestat_set_times) \
- M(fd_pread) \
- M(fd_prestat_get) \
- M(fd_prestat_dir_name) \
- M(fd_pwrite) \
- M(fd_read) \
- M(fd_readdir) \
- M(fd_renumber) \
- M(fd_seek) \
- M(fd_sync) \
- M(fd_tell) \
- M(fd_write) \
- M(path_create_directory) \
- M(path_filestat_get) \
- M(path_filestat_set_times) \
- M(path_link) \
- M(path_open) \
- M(path_readlink) \
- M(path_remove_directory) \
- M(path_rename) \
- M(path_symlink) \
- M(path_unlink_file) \
- M(poll_oneoff) \
- M(proc_exit) \
- M(proc_raise) \
- M(sched_yield) \
- M(random_get) \
- M(sock_accept) \
- M(sock_recv) \
- M(sock_send) \
- M(sock_shutdown)
-
-struct Names {
- AK_ALLOC_WITH_KMALLOC;
-
-#define NAME(x) FlyString x;
- ENUMERATE_FUNCTION_NAMES(NAME)
-#undef NAME
-
- static ErrorOr<Names> construct()
- {
- return Names {
-#define NAME(x) .x = TRY(FlyString::from_utf8(#x##sv)),
- ENUMERATE_FUNCTION_NAMES(NAME)
-#undef NAME
- };
- }
-};
-
-ErrorOr<HostFunction> Implementation::function_by_name(StringView name)
-{
- auto name_for_comparison = TRY(FlyString::from_utf8(name));
- static auto& names = *new Names(TRY(Names::construct()));
-
-#define IMPL(x) \
- if (name_for_comparison == names.x) \
- return invocation_of<&Implementation::impl$##x>(#x##sv);
-
- ENUMERATE_FUNCTION_NAMES(IMPL)
-
-#undef IMPL
-
- return Error::from_string_literal("No such host function");
-}
-
-namespace ABI {
-
-template<typename T>
-struct HostTypeImpl {
- using Type = T;
-};
-
-template<Enum T>
-struct HostTypeImpl<T> {
- using Type = UnderlyingType<T>;
-};
-
-template<typename T>
-struct HostTypeImpl<LittleEndian<T>> {
- using Type = typename HostTypeImpl<T>::Type;
-};
-
-template<typename T, typename t, typename... Fs>
-struct HostTypeImpl<DistinctNumeric<T, t, Fs...>> {
- using Type = typename HostTypeImpl<T>::Type;
-};
-
-template<typename T>
-using HostType = typename HostTypeImpl<T>::Type;
-
-template<typename T>
-auto CompatibleValueType = IsOneOf<HostType<T>, char, i8, i16, i32, u8, u16>
- ? Wasm::ValueType(Wasm::ValueType::I32)
- : Wasm::ValueType(Wasm::ValueType::I64);
-
-template<typename RV, typename... Args, ErrorOr<RV> (Implementation::*impl)(Configuration&, Args...)>
-struct InvocationOf<impl> {
- HostFunction operator()(Implementation& self, StringView function_name)
- {
- using R = typename decltype([] {
- if constexpr (IsSame<RV, Result<void>>)
- return TypeWrapper<void> {};
- else if constexpr (IsSpecializationOf<RV, Result>)
- return TypeWrapper<RemoveCVReference<decltype(*declval<RV>().result())>> {};
- else
- return TypeWrapper<RV> {};
- }())::Type;
-
- Vector<ValueType> arguments_types { CompatibleValueType<typename ABI::ToCompatibleValue<Args>::Type>... };
- if constexpr (!IsVoid<R>) {
- if constexpr (requires { declval<typename R::SerializationComponents>(); }) {
- for_each_type<typename R::SerializationComponents>([&]<typename T>(TypeWrapper<T>) {
- arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<T>>::Type>);
- });
- } else {
- arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<R>>::Type>);
- }
- }
-
- Vector<ValueType> return_ty;
- if constexpr (IsSpecializationOf<RV, Result>)
- return_ty.append(ValueType(ValueType::I32));
-
- return HostFunction(
- [&self, function_name](Configuration& configuration, Span<Value> arguments) -> Wasm::Result {
- Tuple args = [&]<typename... Ts, auto... Is>(IndexSequence<Is...>) {
- return Tuple { ABI::deserialize(ABI::to_compatible_value<Ts>(arguments[Is]))... };
- }.template operator()<Args...>(MakeIndexSequence<sizeof...(Args)>());
-
- auto result = args.apply_as_args([&](auto&&... impl_args) { return (self.*impl)(configuration, impl_args...); });
- dbgln_if(WASI_DEBUG, "WASI: {}({}) = {}", function_name, arguments, result);
- if (result.is_error()) {
- auto error = result.release_error();
- if (error.is_errno())
- return Wasm::Trap { ByteString::formatted("exit:{}", error.code() + 1) };
- return Wasm::Trap { ByteString::formatted("Invalid call to {}() = {}", function_name, error) };
- }
-
- auto value = result.release_value();
- if constexpr (IsSpecializationOf<RV, Result>) {
- if (value.is_error())
- return Wasm::Result { Vector { Value { static_cast<u32>(to_underlying(value.error().value())) } } };
- }
-
- if constexpr (!IsVoid<R>) {
- // Return values are passed as pointers, after the arguments
- if constexpr (requires { &R::serialize_into; }) {
- constexpr auto ResultCount = []<auto N>(void (R::*)(Array<Bytes, N>) const) { return N; }(&R::serialize_into);
- ABI::serialize(*value.result(), address_spans<ResultCount>(arguments.slice(sizeof...(Args)), configuration));
- } else {
- ABI::serialize(*value.result(), address_spans<1>(arguments.slice(sizeof...(Args)), configuration));
- }
- }
- // Return value is errno, we have nothing to return.
- return Wasm::Result { Vector<Value> { Value(ValueType(ValueType::Kind::I32)) } };
- },
- FunctionType {
- move(arguments_types),
- return_ty,
- },
- function_name);
- }
-};
-
-};
-
-Errno errno_value_from_errno(int value)
-{
- switch (value) {
-#ifdef ESUCCESS
- case ESUCCESS:
- return Errno::Success;
-#endif
- case E2BIG:
- return Errno::TooBig;
- case EACCES:
- return Errno::Access;
- case EADDRINUSE:
- return Errno::AddressInUse;
- case EADDRNOTAVAIL:
- return Errno::AddressNotAvailable;
- case EAFNOSUPPORT:
- return Errno::AFNotSupported;
- case EAGAIN:
- return Errno::Again;
- case EALREADY:
- return Errno::Already;
- case EBADF:
- return Errno::BadF;
- case EBUSY:
- return Errno::Busy;
- case ECANCELED:
- return Errno::Canceled;
- case ECHILD:
- return Errno::Child;
- case ECONNABORTED:
- return Errno::ConnectionAborted;
- case ECONNREFUSED:
- return Errno::ConnectionRefused;
- case ECONNRESET:
- return Errno::ConnectionReset;
- case EDEADLK:
- return Errno::Deadlock;
- case EDESTADDRREQ:
- return Errno::DestinationAddressRequired;
- case EDOM:
- return Errno::Domain;
- case EEXIST:
- return Errno::Exist;
- case EFAULT:
- return Errno::Fault;
- case EFBIG:
- return Errno::FBig;
- case EHOSTUNREACH:
- return Errno::HostUnreachable;
- case EILSEQ:
- return Errno::IllegalSequence;
- case EINPROGRESS:
- return Errno::InProgress;
- case EINTR:
- return Errno::Interrupted;
- case EINVAL:
- return Errno::Invalid;
- case EIO:
- return Errno::IO;
- case EISCONN:
- return Errno::IsConnected;
- case EISDIR:
- return Errno::IsDirectory;
- case ELOOP:
- return Errno::Loop;
- case EMFILE:
- return Errno::MFile;
- case EMLINK:
- return Errno::MLink;
- case EMSGSIZE:
- return Errno::MessageSize;
- case ENAMETOOLONG:
- return Errno::NameTooLong;
- case ENETDOWN:
- return Errno::NetworkDown;
- case ENETRESET:
- return Errno::NetworkReset;
- case ENETUNREACH:
- return Errno::NetworkUnreachable;
- case ENFILE:
- return Errno::NFile;
- case ENOBUFS:
- return Errno::NoBufferSpace;
- case ENODEV:
- return Errno::NoDevice;
- case ENOENT:
- return Errno::NoEntry;
- case ENOEXEC:
- return Errno::NoExec;
- case ENOLCK:
- return Errno::NoLock;
- case ENOMEM:
- return Errno::NoMemory;
- case ENOPROTOOPT:
- return Errno::NoProtocolOption;
- case ENOSPC:
- return Errno::NoSpace;
- case ENOSYS:
- return Errno::NoSys;
- case ENOTCONN:
- return Errno::NotConnected;
- case ENOTDIR:
- return Errno::NotDirectory;
- case ENOTEMPTY:
- return Errno::NotEmpty;
- case ENOTRECOVERABLE:
- return Errno::NotRecoverable;
- case ENOTSOCK:
- return Errno::NotSocket;
- case ENOTSUP:
- return Errno::NotSupported;
- case ENOTTY:
- return Errno::NoTTY;
- case ENXIO:
- return Errno::NXIO;
- case EOVERFLOW:
- return Errno::Overflow;
- case EPERM:
- return Errno::Permission;
- case EPIPE:
- return Errno::Pipe;
- case EPROTO:
- return Errno::Protocol;
- case EPROTONOSUPPORT:
- return Errno::ProtocolNotSupported;
- case EPROTOTYPE:
- return Errno::ProtocolType;
- case ERANGE:
- return Errno::Range;
- case ESPIPE:
- return Errno::SPipe;
- case ESRCH:
- return Errno::SRCH;
- case ESTALE:
- return Errno::Stale;
- case ETIMEDOUT:
- return Errno::TimedOut;
- case ETXTBSY:
- return Errno::TextBusy;
- case EXDEV:
- return Errno::XDev;
- default:
- return Errno::Invalid;
- }
-}
-
-FileType file_type_of(struct stat const& buf)
-{
- switch (buf.st_mode & S_IFMT) {
- case S_IFDIR:
- return FileType::Directory;
- case S_IFCHR:
- return FileType::CharacterDevice;
- case S_IFBLK:
- return FileType::BlockDevice;
- case S_IFREG:
- return FileType::RegularFile;
- case S_IFIFO:
- return FileType::Unknown; // FIXME: FileType::Pipe is currently not present in WASI (but it should be) so we use Unknown for now.
- case S_IFLNK:
- return FileType::SymbolicLink;
- case S_IFSOCK:
- return FileType::SocketStream;
- default:
- return FileType::Unknown;
- }
-}
-FDFlags fd_flags_of(struct stat const&)
-{
- FDFlags::Bits result {};
- return FDFlags { result };
-}
-
-}
-
-namespace AK {
-
-// Don't remove, needed for dbgln_if WASI_DEBUG above to display arguments
-template<>
-struct Formatter<Wasm::Value> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Value const& value)
- {
- return Formatter<FormatString>::format(builder, "{}"sv, value.to<u128>());
- }
-};
-
-template<>
-struct Formatter<Wasm::Wasi::Errno> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Errno const& value)
- {
- return Formatter<FormatString>::format(builder, "{}"sv, to_underlying(value));
- }
-};
-
-template<>
-struct Formatter<Empty> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder&, Empty)
- {
- return {};
- }
-};
-
-template<typename T>
-struct Formatter<Wasm::Wasi::Result<T>> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Result<T> const& value)
- {
- if (value.is_error())
- return Formatter<FormatString>::format(builder, "Error({})"sv, *value.error());
-
- return Formatter<FormatString>::format(builder, "Ok({})"sv, *value.result());
- }
-};
-
-template<OneOf<Wasm::Wasi::ArgsSizes, Wasm::Wasi::EnvironSizes> T>
-struct Formatter<T> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, T const& value)
- {
- return Formatter<FormatString>::format(builder, "size={}, count={}"sv, value.size, value.count);
- }
-};
-
-template<>
-struct Formatter<Wasm::Wasi::FDStat> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FDStat const&)
- {
- return Formatter<FormatString>::format(builder, "(rights)"sv);
- }
-};
-
-template<>
-struct Formatter<Wasm::Wasi::FileStat> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FileStat const& value)
- {
- return Formatter<FormatString>::format(builder, "dev={}, ino={}, ft={}, nlink={}, size={}, atim={}, mtim={}, ctim={}"sv,
- value.dev, value.ino, to_underlying(value.filetype), value.nlink, value.size, value.atim, value.mtim, value.ctim);
- }
-};
-
-template<>
-struct Formatter<Wasm::Wasi::PreStat> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::PreStat const& value)
- {
- return Formatter<FormatString>::format(builder, "length={}"sv, value.dir.pr_name_len);
- }
-};
-
-template<>
-struct Formatter<Wasm::Wasi::SockRecvResult> : AK::Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::SockRecvResult const& value)
- {
- return Formatter<FormatString>::format(builder, "size={}"sv, value.size);
- }
-};
-
-}
diff --git a/Libraries/LibWasm/Wasi.h b/Libraries/LibWasm/Wasi.h
deleted file mode 100644
index 1da615b0b71..00000000000
--- a/Libraries/LibWasm/Wasi.h
+++ /dev/null
@@ -1,974 +0,0 @@
-/*
- * Copyright (c) 2023, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/DistinctNumeric.h>
-#include <AK/Endian.h>
-#include <AK/Function.h>
-#include <AK/LexicalPath.h>
-#include <AK/RedBlackTree.h>
-#include <AK/String.h>
-#include <AK/Vector.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/Export.h>
-#include <LibWasm/Forward.h>
-
-namespace Wasm::Wasi::ABI {
-
-// NOTE: The "real" ABI used in the wild is described by [api.h from libc-bottom-half](https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h)
-// This is *not* the same ABI as the one described in the WASI spec, nor is it the same ABI as api.h on wasi-libc/master.
-// The highlights of the ABI are:
-// - (most) structs are passed as pointers to heap.
-// - arrays are fat pointers splat across two arguments
-// - return object locations are also passed as arguments, the number of arguments depends on the return type itself:
-// - ArgsSizes / EnvironSizes / the return type of sock_recv use two arguments
-// - everything else is passed like a normal struct
-
-template<auto impl>
-struct InvocationOf {
- HostFunction operator()(Implementation&, StringView name);
-};
-
-template<typename T, size_t N>
-void serialize(T const&, Array<Bytes, N>);
-
-template<typename T, size_t N>
-T deserialize(Array<ReadonlyBytes, N> const&);
-
-template<typename T>
-struct ToCompatibleValue {
- using Type = void;
-};
-
-template<typename T>
-struct CompatibleValue {
- typename ToCompatibleValue<T>::Type value;
-
- Wasm::Value to_wasm_value() const;
-};
-
-template<typename T>
-CompatibleValue<T> to_compatible_value(Wasm::Value const&);
-
-template<typename T>
-T deserialize(CompatibleValue<T> const&);
-
-}
-
-namespace Wasm::Wasi {
-
-// NOTE: This is a copy of LittleEndian from Endian.h,
-// we can't use those because they have a packed attribute, and depend on it;
-// but we want proper alignment on these types.
-template<typename T>
-class alignas(T) LittleEndian {
-public:
- constexpr LittleEndian() = default;
-
- constexpr LittleEndian(T value)
- : m_value(AK::convert_between_host_and_little_endian(value))
- {
- }
-
- constexpr operator T() const { return AK::convert_between_host_and_little_endian(m_value); }
- constexpr T value() const { return AK::convert_between_host_and_little_endian(m_value); }
-
- LittleEndian& operator+=(T other)
- {
- m_value = AK::convert_between_host_and_little_endian(AK::convert_between_host_and_little_endian(m_value) + other);
- return *this;
- }
-
- // This returns the internal representation. In this case, that is the value stored in little endian format.
- constexpr Bytes bytes() LIFETIME_BOUND { return Bytes { &m_value, sizeof(m_value) }; }
- constexpr ReadonlyBytes bytes() const LIFETIME_BOUND { return ReadonlyBytes { &m_value, sizeof(m_value) }; }
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static LittleEndian read_from(Array<ReadonlyBytes, 1> const& bytes);
-
-private:
- T m_value { 0 };
-};
-
-using Size = LittleEndian<u32>;
-using FileSize = LittleEndian<u64>;
-using Timestamp = LittleEndian<u64>;
-
-namespace Detail {
-
-template<typename>
-struct __Pointer_tag;
-template<typename>
-struct __ConstPointer_tag;
-
-}
-
-// NOTE: Might need to be updated if WASI ever supports memory64.
-using UnderlyingPointerType = u32;
-
-template<typename T>
-using Pointer = DistinctNumeric<LittleEndian<UnderlyingPointerType>, Detail::__Pointer_tag<T>, AK::DistinctNumericFeature::Comparison>;
-template<typename T>
-using ConstPointer = DistinctNumeric<LittleEndian<UnderlyingPointerType>, Detail::__ConstPointer_tag<T>, AK::DistinctNumericFeature::Comparison>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L70
-enum class ClockID : u32 {
- Realtime,
- Monotonic,
- ProcessCPUTimeID,
- ThreadCPUTimeID,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L105
-enum class Errno : u16 {
- Success,
- TooBig,
- Access,
- AddressInUse,
- AddressNotAvailable,
- AFNotSupported,
- Again,
- Already,
- BadF,
- BadMessage,
- Busy,
- Canceled,
- Child,
- ConnectionAborted,
- ConnectionRefused,
- ConnectionReset,
- Deadlock,
- DestinationAddressRequired,
- Domain,
- DQuot, // Reserved, Unused.
- Exist,
- Fault,
- FBig,
- HostUnreachable,
- IdentifierRemoved,
- IllegalSequence,
- InProgress,
- Interrupted,
- Invalid,
- IO,
- IsConnected,
- IsDirectory,
- Loop,
- MFile,
- MLink,
- MessageSize,
- MultiHop, // Reserved, Unused.
- NameTooLong,
- NetworkDown,
- NetworkReset,
- NetworkUnreachable,
- NFile,
- NoBufferSpace,
- NoDevice,
- NoEntry,
- NoExec,
- NoLock,
- NoLink,
- NoMemory,
- NoMessage,
- NoProtocolOption,
- NoSpace,
- NoSys,
- NotConnected,
- NotDirectory,
- NotEmpty,
- NotRecoverable,
- NotSocket,
- NotSupported,
- NoTTY,
- NXIO,
- Overflow,
- OwnerDead,
- Permission,
- Pipe,
- Protocol,
- ProtocolNotSupported,
- ProtocolType,
- Range,
- ReadOnlyFS,
- SPipe,
- SRCH,
- Stale,
- TimedOut,
- TextBusy,
- XDev,
- NotCapable,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L498
-struct Rights {
- using CompatibleType = u64;
-
- struct Bits {
- bool fd_datasync : 1;
- bool fd_read : 1;
- bool fd_seek : 1;
- bool fd_fdstat_set_flags : 1;
- bool fd_sync : 1;
- bool fd_tell : 1;
- bool fd_write : 1;
- bool fd_advise : 1;
- bool fd_allocate : 1;
- bool path_create_directory : 1;
- bool path_create_file : 1;
- bool path_link_source : 1;
- bool path_link_target : 1;
- bool path_open : 1;
- bool fd_readdir : 1;
- bool path_readlink : 1;
- bool path_rename_source : 1;
- bool path_rename_target : 1;
- bool path_filestat_get : 1;
- bool path_filestat_set_size : 1;
- bool path_filestat_set_times : 1;
- bool fd_filestat_get : 1;
- bool fd_filestat_set_size : 1;
- bool fd_filestat_set_times : 1;
- bool path_symlink : 1;
- bool path_remove_directory : 1;
- bool path_unlink_file : 1;
- bool poll_fd_readwrite : 1;
- bool sock_shutdown : 1;
- bool sock_accept : 1;
-
- u8 _unused1 : 2;
- u32 _unused2 : 32;
- };
-
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static Rights read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L663
-using FD = DistinctNumeric<LittleEndian<u32>, struct __FD_tag, AK::DistinctNumericFeature::Comparison>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L671
-struct IOVec {
- Pointer<u8> buf;
- Size buf_len;
-
- static IOVec read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L692
-struct CIOVec {
- ConstPointer<u8> buf;
- Size buf_len;
-
- static CIOVec read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L713
-using FileDelta = LittleEndian<i64>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L721
-enum class Whence : u8 {
- Set,
- Cur,
- End,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L746
-using DirCookie = LittleEndian<u64>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L754
-using DirNameLen = LittleEndian<u32>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L762
-using INode = LittleEndian<u64>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L770
-enum class FileType : u8 {
- Unknown,
- BlockDevice,
- CharacterDevice,
- Directory,
- RegularFile,
- SocketDGram,
- SocketStream,
- SymbolicLink,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L818
-struct DirEnt {
- DirCookie d_next;
- INode d_ino;
- DirNameLen d_namlen;
- FileType d_type;
- u8 _padding[3] { 0 }; // Not part of the API, but the struct is required to be 24 bytes - even though it has no explicit padding.
-};
-static_assert(sizeof(DirEnt) == 24);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L851
-enum class Advice : u8 {
- Normal,
- Sequential,
- Random,
- WillNeed,
- DontNeed,
- NoReuse,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L889
-struct FDFlags {
- using CompatibleType = u16;
-
- struct Bits {
- bool append : 1;
- bool dsync : 1;
- bool nonblock : 1;
- bool rsync : 1;
- bool sync : 1;
-
- u8 _unused1 : 3;
- u8 _unused2 : 8;
- };
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static FDFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L924
-struct FDStat {
- FileType fs_filetype;
- u8 _padding1 { 0 }; // Not part of the API.
- FDFlags fs_flags;
- u8 _padding2[4] { 0 }; // Not part of the API.
- Rights fs_rights_base;
- Rights fs_rights_inheriting;
-
- void serialize_into(Array<Bytes, 1> bytes) const;
-};
-static_assert(sizeof(FDStat) == 24);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L959
-using Device = LittleEndian<u64>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L967
-struct FSTFlags {
- using CompatibleType = u16;
-
- struct Bits {
- bool atim : 1;
- bool atim_now : 1;
- bool mtim : 1;
- bool mtim_now : 1;
-
- u8 _unused1 : 4;
- u8 _unused2 : 8;
- };
-
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static FSTFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-static_assert(sizeof(FSTFlags) == 2);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L995
-struct LookupFlags {
- using CompatibleType = u32;
-
- struct Bits {
- bool symlink_follow : 1;
-
- u8 _unused1 : 7;
- u8 _unused2 : 8;
- u16 _unused3 : 16;
- };
-
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static LookupFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-static_assert(sizeof(LookupFlags) == 4);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1008
-struct OFlags {
- using CompatibleType = u16;
-
- struct Bits {
- bool creat : 1;
- bool directory : 1;
- bool excl : 1;
- bool trunc : 1;
-
- u8 _unused1 : 4;
- u8 _unused2 : 8;
- };
-
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- static OFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-static_assert(sizeof(OFlags) == 2);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1036
-using LinkCount = LittleEndian<u64>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1044
-struct FileStat {
- Device dev;
- INode ino;
- FileType filetype;
- u8 _padding1[7] { 0 }; // Not part of the API.
- LinkCount nlink;
- FileSize size;
- Timestamp atim;
- Timestamp mtim;
- Timestamp ctim;
-
- void serialize_into(Array<Bytes, 1> bytes) const;
-};
-static_assert(sizeof(FileStat) == 64);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1102
-using UserData = LittleEndian<u64>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1110
-enum class EventType : u8 {
- Clock,
- FDRead,
- FDWrite,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1137
-struct EventRWFlags {
- using CompatibleType = u16;
-
- struct Bits {
- bool fd_readwrite_hangup : 1;
-
- u8 _unused1 : 7;
- u8 _unused2 : 8;
- };
-
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static EventRWFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1151
-struct EventFDReadWrite {
- FileSize nbytes;
- u8 _padding[4] { 0 }; // Not part of the API.
- EventRWFlags flags;
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static EventFDReadWrite read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-static_assert(sizeof(EventFDReadWrite) == 16);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1186
-struct Event {
- UserData userdata;
- Errno errno_;
- EventType type;
- u8 _padding[5] { 0 }; // Not part of the API.
- EventFDReadWrite fd_readwrite;
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static Event read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-static_assert(sizeof(Event) == 32);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1220
-struct SubClockFlags {
- using CompatibleType = u16;
-
- struct Bits {
- bool subscription_clock_abstime : 1;
-
- u8 _unused1 : 7;
- u8 _unused2 : 8;
- };
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static SubClockFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1237
-struct SubscriptionClock {
- ClockID id;
- u8 _padding1[4] { 0 }; // Not part of the API.
- Timestamp timeout;
- Timestamp precision;
- SubClockFlags flags;
- u8 _padding2[4] { 0 }; // Not part of the API.
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static SubscriptionClock read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-static_assert(sizeof(SubscriptionClock) == 32);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1272
-struct SubscriptionFDReadWrite {
- FD file_descriptor;
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static SubscriptionFDReadWrite read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1287
-union SubscriptionU {
- SubscriptionClock clock;
- SubscriptionFDReadWrite fd_read;
- SubscriptionFDReadWrite fd_write;
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1306
-struct Subscription {
- UserData userdata;
- EventType type;
- u8 _padding[7] { 0 }; // Not part of the API.
- SubscriptionU u;
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static Subscription read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-static_assert(sizeof(Subscription) == 48);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1334
-using ExitCode = LittleEndian<u32>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1342
-enum class Signal : u8 {
- None,
- HUP,
- INT,
- QUIT,
- ILL,
- TRAP,
- ABRT,
- BUS,
- FPE,
- KILL,
- USR1,
- SEGV,
- USR2,
- PIPE,
- ALRM,
- TERM,
- CHLD,
- CONT,
- STOP,
- TSTP,
- TTIN,
- TTOU,
- URG,
- XCPU,
- XFSZ,
- VTALRM,
- PROF,
- WINCH,
- POLL,
- PWR,
- SYS,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1536
-struct RIFlags {
- using CompatibleType = u16;
-
- struct Bits {
- bool recv_peek : 1;
- bool recv_waitall : 1;
-
- u8 _unused1 : 6;
- u8 _unused2 : 8;
- };
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- static RIFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1554
-struct ROFlags {
- using CompatibleType = u16;
-
- struct Bits {
- bool recv_data_truncated : 1;
-
- u8 _unused1 : 7;
- u8 _unused2 : 8;
- };
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1568
-using SIFlags = LittleEndian<u16>;
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1576
-struct SDFlags {
- using CompatibleType = u8;
-
- struct Bits {
- bool rd : 1;
- bool wr : 1;
-
- u8 _unused : 6;
- };
- static_assert(sizeof(Bits) == sizeof(CompatibleType));
-
- union {
- Bits bits;
- LittleEndian<CompatibleType> data;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static SDFlags read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1594
-enum class PreOpenType : u8 {
- Dir,
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1607
-struct PreStatDir {
- Size pr_name_len;
-
- void serialize_into(Array<Bytes, 1> bytes) const;
- static PreStatDir read_from(Array<ReadonlyBytes, 1> const& bytes);
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1636
-struct PreStat {
- PreOpenType type;
- u8 _padding[3] { 0 }; // Not part of the API.
- union {
- PreStatDir dir;
- };
-
- void serialize_into(Array<Bytes, 1> bytes) const;
-};
-static_assert(sizeof(PreStat) == 8);
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1676
-struct ArgsSizes {
- Size count;
- Size size;
-
- using SerializationComponents = TypeList<Size, Size>;
-
- void serialize_into(Array<Bytes, 2> bytes) const;
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L1708
-struct EnvironSizes {
- Size count;
- Size size;
-
- using SerializationComponents = TypeList<Size, Size>;
-
- void serialize_into(Array<Bytes, 2> bytes) const;
-};
-
-// https://github.com/WebAssembly/wasi-libc/blob/2c2fc9a2fddd0927a66f1c142e65c8dab6f5c5d7/libc-bottom-half/headers/public/wasi/api.h#L2664
-struct SockRecvResult {
- Size size;
- ROFlags roflags;
- u8 _padding[2] { 0 }; // Not part of the API.
-
- using SerializationComponents = TypeList<Size, ROFlags>;
-
- void serialize_into(Array<Bytes, 2> bytes) const;
-};
-static_assert(sizeof(SockRecvResult) == 8);
-
-template<typename TResult, typename Tag = u32>
-struct Result {
- Result(TResult&& result)
- : m_result(result)
- , tag(0)
- {
- }
-
- Result(Errno&& error)
- : m_error(error)
- , tag(1)
- {
- }
-
- static_assert(IsTriviallyDestructible<TResult>);
- static_assert(IsTriviallyDestructible<Errno>);
-
- Optional<TResult const&> result() const
- {
- if (tag == 0)
- return m_result;
- return {};
- }
-
- Optional<Errno const&> error() const
- {
- if (tag == 1)
- return m_error;
- return {};
- }
-
- bool is_error() const { return tag == 1; }
-
- template<size_t N>
- Errno serialize_into(Array<Bytes, N>&& spans) const
- {
- if (tag == 1)
- return error().value();
-
- ABI::serialize(*result(), move(spans));
- return Errno::Success;
- }
-
-private:
- union {
- TResult m_result;
- Errno m_error;
- };
- LittleEndian<Tag> tag;
-};
-
-template<typename Tag>
-struct Result<void, Tag> {
- Result()
- : m_error()
- , tag(0)
- {
- }
-
- Result(Errno&& error)
- : m_error(error)
- , tag(1)
- {
- }
-
- Optional<Empty> result() const
- {
- if (tag == 0)
- return { Empty {} };
- return {};
- }
- Optional<Errno const&> error() const
- {
- if (tag == 1)
- return m_error;
- return {};
- }
- bool is_error() const { return tag == 1; }
-
-private:
- Errno m_error;
- LittleEndian<Tag> tag;
-};
-
-struct WASM_API Implementation {
- struct MappedPath {
- LexicalPath host_path;
- LexicalPath mapped_path;
- mutable Optional<int> opened_fd {};
- };
-
- struct Details {
- Function<Vector<AK::String>()> provide_arguments;
- Function<Vector<AK::String>()> provide_environment;
- Function<Vector<MappedPath>()> provide_preopened_directories;
- int stdin_fd { 0 };
- int stdout_fd { 1 };
- int stderr_fd { 2 };
- };
-
- explicit Implementation(Details&& details)
- : provide_arguments(move(details.provide_arguments))
- , provide_environment(move(details.provide_environment))
- , provide_preopened_directories(move(details.provide_preopened_directories))
- {
- // Map all of std{in,out,err} by default.
- m_fd_map.insert(0, details.stdin_fd);
- m_fd_map.insert(1, details.stdout_fd);
- m_fd_map.insert(2, details.stderr_fd);
- }
-
- ErrorOr<HostFunction> function_by_name(StringView);
-
-private:
- template<auto impl>
- HostFunction invocation_of(StringView name) { return ABI::InvocationOf<impl> {}(*this, name); }
-
- ErrorOr<Result<void>> impl$args_get(Configuration&, Pointer<Pointer<u8>> argv, Pointer<u8> argv_buf);
- ErrorOr<Result<ArgsSizes>> impl$args_sizes_get(Configuration&);
- ErrorOr<Result<void>> impl$environ_get(Configuration&, Pointer<Pointer<u8>> environ, Pointer<u8> environ_buf);
- ErrorOr<Result<EnvironSizes>> impl$environ_sizes_get(Configuration&);
- ErrorOr<Result<Timestamp>> impl$clock_res_get(Configuration&, ClockID id);
- ErrorOr<Result<Timestamp>> impl$clock_time_get(Configuration&, ClockID id, Timestamp precision);
- ErrorOr<Result<void>> impl$fd_advise(Configuration&, FD, FileSize offset, FileSize len, Advice);
- ErrorOr<Result<void>> impl$fd_allocate(Configuration&, FD, FileSize offset, FileSize len);
- ErrorOr<Result<void>> impl$fd_close(Configuration&, FD);
- ErrorOr<Result<void>> impl$fd_datasync(Configuration&, FD);
- ErrorOr<Result<FDStat>> impl$fd_fdstat_get(Configuration&, FD);
- ErrorOr<Result<void>> impl$fd_fdstat_set_flags(Configuration&, FD, FDFlags);
- ErrorOr<Result<void>> impl$fd_fdstat_set_rights(Configuration&, FD, Rights fs_rights_base, Rights fs_rights_inheriting);
- ErrorOr<Result<FileStat>> impl$fd_filestat_get(Configuration&, FD);
- ErrorOr<Result<void>> impl$fd_filestat_set_size(Configuration&, FD, FileSize);
- ErrorOr<Result<void>> impl$fd_filestat_set_times(Configuration&, FD, Timestamp atim, Timestamp mtim, FSTFlags);
- ErrorOr<Result<Size>> impl$fd_pread(Configuration&, FD, Pointer<IOVec> iovs, Size iovs_len, FileSize offset);
- ErrorOr<Result<PreStat>> impl$fd_prestat_get(Configuration&, FD);
- ErrorOr<Result<void>> impl$fd_prestat_dir_name(Configuration&, FD, Pointer<u8> path, Size path_len);
- ErrorOr<Result<Size>> impl$fd_pwrite(Configuration&, FD, Pointer<CIOVec> iovs, Size iovs_len, FileSize offset);
- ErrorOr<Result<Size>> impl$fd_read(Configuration&, FD, Pointer<IOVec> iovs, Size iovs_len);
- ErrorOr<Result<Size>> impl$fd_readdir(Configuration&, FD, Pointer<u8> buf, Size buf_len, DirCookie cookie);
- ErrorOr<Result<void>> impl$fd_renumber(Configuration&, FD from, FD to);
- ErrorOr<Result<FileSize>> impl$fd_seek(Configuration&, FD, FileDelta offset, Whence whence);
- ErrorOr<Result<void>> impl$fd_sync(Configuration&, FD);
- ErrorOr<Result<FileSize>> impl$fd_tell(Configuration&, FD);
- ErrorOr<Result<Size>> impl$fd_write(Configuration&, FD, Pointer<CIOVec> iovs, Size iovs_len);
- ErrorOr<Result<void>> impl$path_create_directory(Configuration&, FD, Pointer<u8> path, Size path_len);
- ErrorOr<Result<FileStat>> impl$path_filestat_get(Configuration&, FD, LookupFlags, ConstPointer<u8> path, Size path_len);
- ErrorOr<Result<void>> impl$path_filestat_set_times(Configuration&, FD, LookupFlags, Pointer<u8> path, Size path_len, Timestamp atim, Timestamp mtim, FSTFlags);
- ErrorOr<Result<void>> impl$path_link(Configuration&, FD, LookupFlags, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len);
- ErrorOr<Result<FD>> impl$path_open(Configuration&, FD, LookupFlags, Pointer<u8> path, Size path_len, OFlags, Rights fs_rights_base, Rights fs_rights_inheriting, FDFlags fd_flags);
- ErrorOr<Result<Size>> impl$path_readlink(Configuration&, FD, LookupFlags, Pointer<u8> path, Size path_len, Pointer<u8> buf, Size buf_len);
- ErrorOr<Result<void>> impl$path_remove_directory(Configuration&, FD, Pointer<u8> path, Size path_len);
- ErrorOr<Result<void>> impl$path_rename(Configuration&, FD, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len);
- ErrorOr<Result<void>> impl$path_symlink(Configuration&, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len);
- ErrorOr<Result<void>> impl$path_unlink_file(Configuration&, FD, Pointer<u8> path, Size path_len);
- ErrorOr<Result<Size>> impl$poll_oneoff(Configuration&, ConstPointer<Subscription> in, Pointer<Event> out, Size nsubscriptions);
- ErrorOr<void> impl$proc_exit(Configuration&, ExitCode);
- ErrorOr<Result<void>> impl$proc_raise(Configuration&, Signal);
- ErrorOr<Result<void>> impl$sched_yield(Configuration&);
- ErrorOr<Result<void>> impl$random_get(Configuration&, Pointer<u8> buf, Size buf_len);
- ErrorOr<Result<FD>> impl$sock_accept(Configuration&, FD fd, FDFlags fd_flags);
- ErrorOr<Result<SockRecvResult>> impl$sock_recv(Configuration&, FD fd, Pointer<IOVec> ri_data, Size ri_data_len, RIFlags ri_flags);
- ErrorOr<Result<Size>> impl$sock_send(Configuration&, FD fd, Pointer<CIOVec> si_data, Size ri_data_len, SIFlags si_flags);
- ErrorOr<Result<void>> impl$sock_shutdown(Configuration&, FD fd, SDFlags how);
-
- Vector<AK::String> const& arguments() const;
- Vector<AK::String> const& environment() const;
- Vector<MappedPath> const& preopened_directories() const;
-
- using PreopenedDirectoryDescriptor = DistinctNumeric<LittleEndian<size_t>, struct PreopenedDirectoryDescriptor_tag, AK::DistinctNumericFeature::Comparison, AK::DistinctNumericFeature::CastToUnderlying, AK::DistinctNumericFeature::Increment>;
- using UnmappedDescriptor = DistinctNumeric<LittleEndian<size_t>, struct UnmappedDescriptor_tag, AK::DistinctNumericFeature::Comparison, AK::DistinctNumericFeature::CastToUnderlying>;
- using MappedDescriptor = Variant<u32, PreopenedDirectoryDescriptor>;
- using Descriptor = Variant<u32, PreopenedDirectoryDescriptor, UnmappedDescriptor>;
-
- Descriptor map_fd(FD);
-
-public:
- Function<Vector<AK::String>()> provide_arguments;
- Function<Vector<AK::String>()> provide_environment;
- Function<Vector<MappedPath>()> provide_preopened_directories;
-
-private:
- struct Cache {
- Optional<Vector<AK::String>> cached_arguments;
- Optional<Vector<AK::String>> cached_environment;
- Optional<Vector<MappedPath>> cached_preopened_directories;
- };
-
- mutable Cache cache {};
-
- RedBlackTree<u32, MappedDescriptor> m_fd_map;
- size_t m_first_unmapped_preopened_directory_index { 0 };
-};
-
-#undef IMPL
-
-}
-
-namespace Wasm::Wasi::ABI {
-
-template<typename T, typename... Args>
-struct ToCompatibleValue<DistinctNumeric<T, Args...>> {
- using Type = typename ToCompatibleValue<T>::Type;
-};
-
-template<typename T>
-struct ToCompatibleValue<LittleEndian<T>> {
- using Type = MakeSigned<T>;
-};
-
-template<typename T>
-requires(requires { declval<typename T::CompatibleType>(); })
-struct ToCompatibleValue<T> {
- using Type = MakeSigned<typename T::CompatibleType>;
-};
-
-template<Integral T>
-struct ToCompatibleValue<T> {
- using Type = MakeSigned<T>;
-};
-
-template<Enum T>
-struct ToCompatibleValue<T> {
- using Type = MakeSigned<UnderlyingType<T>>;
-};
-
-}
-
-template<typename T>
-struct AK::Formatter<Wasm::Wasi::LittleEndian<T>> : AK::Formatter<T> {
- ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::LittleEndian<T> value)
- {
- return Formatter<T>::format(builder, value.operator T());
- }
-};
diff --git a/Libraries/LibWasmCompilerClient/CMakeLists.txt b/Libraries/LibWasmCompilerClient/CMakeLists.txt
deleted file mode 100644
index 0782598a00c..00000000000
--- a/Libraries/LibWasmCompilerClient/CMakeLists.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-set(SOURCES
- Client.cpp
- State.cpp
- ThreadedClient.cpp
-)
-
-compile_ipc(../../Services/WasmCompiler/WasmCompilerClient.ipc ../../Services/WasmCompiler/WasmCompilerClientEndpoint.h)
-compile_ipc(../../Services/WasmCompiler/WasmCompilerServer.ipc ../../Services/WasmCompiler/WasmCompilerServerEndpoint.h)
-
-set(GENERATED_SOURCES
- ../../Services/WasmCompiler/WasmCompilerClientEndpoint.h
- ../../Services/WasmCompiler/WasmCompilerServerEndpoint.h
-)
-
-ladybird_lib(LibWasmCompilerClient wasmcompilerclient)
-target_link_libraries(LibWasmCompilerClient PRIVATE LibCore LibIPC LibThreading)
-target_compile_definitions(LibWasmCompilerClient PUBLIC HAVE_WASM_COMPILER_SERVICE=1)
diff --git a/Libraries/LibWasmCompilerClient/Client.cpp b/Libraries/LibWasmCompilerClient/Client.cpp
deleted file mode 100644
index 56fa14341d5..00000000000
--- a/Libraries/LibWasmCompilerClient/Client.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ScopeGuard.h>
-#include <LibWasmCompilerClient/Client.h>
-
-namespace WasmCompilerClient {
-
-static constexpr auto COMPILE_TIMEOUT = AK::Duration::from_seconds(70);
-
-Client::Client(NonnullOwnPtr<IPC::Transport> transport)
- : IPC::ConnectionToServer<WasmCompilerClientEndpoint, WasmCompilerServerEndpoint>(*this, move(transport))
-{
-}
-
-Core::AnonymousBuffer Client::compile(Core::AnonymousBuffer const& buffer)
-{
- auto request_id = m_next_request_id.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);
- auto pending_compilation = adopt_ref(*new PendingCompilation);
- {
- MutexLocker locker(m_pending_compilations_mutex);
- if (!is_open())
- return {};
- m_pending_compilations.set(request_id, pending_compilation);
- }
-
- async_compile(buffer, request_id);
-
- ScopeGuard remove_pending_compilation = [&]() {
- MutexLocker locker(m_pending_compilations_mutex);
- m_pending_compilations.remove(request_id);
- };
-
- MutexLocker locker(pending_compilation->mutex);
- auto timeout_at = MonotonicTime::now() + COMPILE_TIMEOUT;
-
- while (!pending_compilation->result.has_value()) {
- auto now = MonotonicTime::now();
- if (now >= timeout_at)
- break;
- pending_compilation->condition.wait_for(timeout_at - now);
- }
-
- if (!pending_compilation->result.has_value())
- return {};
- return pending_compilation->result.release_value();
-}
-
-void Client::die()
-{
- HashMap<u64, NonnullRefPtr<PendingCompilation>> pending_compilations;
- {
- MutexLocker locker(m_pending_compilations_mutex);
- pending_compilations = move(m_pending_compilations);
- }
-
- for (auto& pending_compilation : pending_compilations) {
- MutexLocker locker(pending_compilation.value->mutex);
- pending_compilation.value->result = Core::AnonymousBuffer {};
- pending_compilation.value->condition.broadcast();
- }
-}
-
-void Client::did_compile(u64 request_id, Core::AnonymousBuffer output)
-{
- Optional<NonnullRefPtr<PendingCompilation>> pending_compilation;
- {
- MutexLocker locker(m_pending_compilations_mutex);
- pending_compilation = m_pending_compilations.take(request_id);
- }
-
- if (!pending_compilation.has_value())
- return;
-
- MutexLocker locker(pending_compilation.value()->mutex);
- pending_compilation.value()->result = move(output);
- pending_compilation.value()->condition.broadcast();
-}
-
-}
diff --git a/Libraries/LibWasmCompilerClient/Client.h b/Libraries/LibWasmCompilerClient/Client.h
deleted file mode 100644
index 3ba4ae17670..00000000000
--- a/Libraries/LibWasmCompilerClient/Client.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Atomic.h>
-#include <AK/AtomicRefCounted.h>
-#include <AK/ConditionVariable.h>
-#include <AK/Function.h>
-#include <AK/HashMap.h>
-#include <AK/Mutex.h>
-#include <AK/Optional.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibIPC/ConnectionToServer.h>
-#include <WasmCompiler/WasmCompilerClientEndpoint.h>
-#include <WasmCompiler/WasmCompilerServerEndpoint.h>
-
-namespace WasmCompilerClient {
-
-class Client final
- : public IPC::ConnectionToServer<WasmCompilerClientEndpoint, WasmCompilerServerEndpoint>
- , public WasmCompilerClientEndpoint {
- C_OBJECT_ABSTRACT(Client);
-
-public:
- explicit Client(NonnullOwnPtr<IPC::Transport>);
-
- Core::AnonymousBuffer compile(Core::AnonymousBuffer const&);
-
- Function<void()> on_death;
-
-private:
- struct PendingCompilation final : public AtomicRefCounted<PendingCompilation> {
- Mutex mutex;
- ConditionVariable condition { mutex };
- Optional<Core::AnonymousBuffer> result;
- };
-
- virtual void die() override;
- virtual void did_compile(u64 request_id, Core::AnonymousBuffer output) override;
-
- Atomic<u64> m_next_request_id { 0 };
-
- Mutex m_pending_compilations_mutex;
- HashMap<u64, NonnullRefPtr<PendingCompilation>> m_pending_compilations;
-};
-
-}
diff --git a/Libraries/LibWasmCompilerClient/Forward.h b/Libraries/LibWasmCompilerClient/Forward.h
deleted file mode 100644
index 452ac0f7d6e..00000000000
--- a/Libraries/LibWasmCompilerClient/Forward.h
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-namespace WasmCompilerClient {
-
-class Client;
-class ThreadedClient;
-
-}
diff --git a/Libraries/LibWasmCompilerClient/State.cpp b/Libraries/LibWasmCompilerClient/State.cpp
deleted file mode 100644
index 108fbcb3694..00000000000
--- a/Libraries/LibWasmCompilerClient/State.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NeverDestroyed.h>
-#include <LibIPC/Transport.h>
-#include <LibIPC/TransportHandle.h>
-#include <LibWasmCompilerClient/State.h>
-#include <LibWasmCompilerClient/ThreadedClient.h>
-
-namespace WasmCompilerClient {
-
-Core::AnonymousBuffer CompilerState::compile(Core::AnonymousBuffer const& buffer)
-{
- RefPtr<ThreadedClient> client;
- {
- MutexLocker locker(m_mutex);
- client = m_client;
- }
-
- return client ? client->compile(buffer) : Core::AnonymousBuffer {};
-}
-
-void CompilerState::replace_connection(IPC::TransportHandle handle)
-{
- RefPtr<ThreadedClient> new_client;
-
- if (auto result = ThreadedClient::create(move(handle)); result.is_error())
- dbgln("Failed to connect to WebAssembly compiler: {}", result.error());
- else
- new_client = result.release_value();
-
- RefPtr<ThreadedClient> old_client;
- {
- MutexLocker locker(m_mutex);
- old_client = move(m_client);
- m_client = move(new_client);
- }
-}
-
-CompilerState& compiler_state()
-{
- static NeverDestroyed<CompilerState> state;
- return *state;
-}
-
-}
diff --git a/Libraries/LibWasmCompilerClient/State.h b/Libraries/LibWasmCompilerClient/State.h
deleted file mode 100644
index 6bd310373fd..00000000000
--- a/Libraries/LibWasmCompilerClient/State.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Mutex.h>
-#include <AK/RefPtr.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibIPC/Forward.h>
-#include <LibWasmCompilerClient/Forward.h>
-
-namespace WasmCompilerClient {
-
-class CompilerState {
-public:
- Core::AnonymousBuffer compile(Core::AnonymousBuffer const&);
- void replace_connection(IPC::TransportHandle);
-
-private:
- RefPtr<ThreadedClient> m_client;
- Mutex m_mutex;
-};
-
-CompilerState& compiler_state();
-
-}
diff --git a/Libraries/LibWasmCompilerClient/ThreadedClient.cpp b/Libraries/LibWasmCompilerClient/ThreadedClient.cpp
deleted file mode 100644
index f4bdcf1695b..00000000000
--- a/Libraries/LibWasmCompilerClient/ThreadedClient.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ScopeGuard.h>
-#include <LibCore/EventLoop.h>
-#include <LibIPC/TransportHandle.h>
-#include <LibThreading/Thread.h>
-#include <LibWasmCompilerClient/Client.h>
-#include <LibWasmCompilerClient/ThreadedClient.h>
-
-namespace WasmCompilerClient {
-
-ErrorOr<NonnullRefPtr<ThreadedClient>> ThreadedClient::create(IPC::TransportHandle handle)
-{
- auto client = adopt_ref(*new ThreadedClient(move(handle)));
-
- Optional<Error> initialization_error;
- {
- MutexLocker locker(client->m_mutex);
- client->m_initialization_condition.wait_while([&]() { return !client->m_initialized; });
- initialization_error = move(client->m_initialization_error);
- }
-
- if (initialization_error.has_value())
- return initialization_error.release_value();
-
- return client;
-}
-
-ThreadedClient::ThreadedClient(IPC::TransportHandle handle)
- : m_thread(Threading::Thread::construct("WasmCompiler IPC"sv, [this, handle = move(handle)]() {
- return thread_main(handle);
- }))
-{
- m_thread->start();
-}
-
-ThreadedClient::~ThreadedClient()
-{
- RefPtr<Core::WeakEventLoopReference> event_loop;
- {
- MutexLocker locker(m_mutex);
- event_loop = m_event_loop;
- }
-
- if (event_loop) {
- if (auto strong_event_loop = event_loop->take()) {
- strong_event_loop->deferred_invoke([]() {
- Core::EventLoop::current().quit(0);
- });
- }
- }
-
- if (m_thread->needs_to_be_joined())
- (void)m_thread->join();
-}
-
-Core::AnonymousBuffer ThreadedClient::compile(Core::AnonymousBuffer const& buffer)
-{
- Client* client = nullptr;
- {
- MutexLocker locker(m_mutex);
- client = m_client;
- if (!client)
- return {};
- ++m_active_compilations;
- }
-
- ScopeGuard compilation_finished = [&]() {
- MutexLocker locker(m_mutex);
- VERIFY(m_active_compilations > 0);
-
- if (--m_active_compilations == 0)
- m_client_unused_condition.broadcast();
- };
-
- return client->compile(buffer);
-}
-
-// This must run on the IPC thread. On Windows, the socket's notifier is bound to the event loop of the thread that
-// creates the socket, and the connection must be serviced by that same thread.
-static ErrorOr<NonnullRefPtr<Client>> create_client(IPC::TransportHandle const& handle)
-{
- auto transport = TRY(handle.create_transport());
- auto client = TRY(try_make_ref_counted<Client>(move(transport)));
-
- return client;
-}
-
-intptr_t ThreadedClient::thread_main(IPC::TransportHandle const& handle)
-{
- Core::EventLoop event_loop;
- auto client_or_error = create_client(handle);
-
- if (client_or_error.is_error()) {
- MutexLocker locker(m_mutex);
- m_initialization_error = client_or_error.release_error();
- m_initialized = true;
- m_initialization_condition.broadcast();
- return 1;
- }
-
- auto client = client_or_error.release_value();
-
- {
- MutexLocker locker(m_mutex);
-
- m_event_loop = Core::EventLoop::current_weak();
- m_client = client.ptr();
- m_initialized = true;
- m_initialization_condition.broadcast();
- }
-
- auto result = event_loop.exec();
-
- {
- MutexLocker locker(m_mutex);
- m_client = nullptr;
- }
-
- if (client->is_open())
- client->shutdown();
-
- {
- MutexLocker locker(m_mutex);
- m_client_unused_condition.wait_while([&]() { return m_active_compilations != 0; });
- m_event_loop.clear();
- }
-
- return result;
-}
-
-}
diff --git a/Libraries/LibWasmCompilerClient/ThreadedClient.h b/Libraries/LibWasmCompilerClient/ThreadedClient.h
deleted file mode 100644
index 12c94ad6063..00000000000
--- a/Libraries/LibWasmCompilerClient/ThreadedClient.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/AtomicRefCounted.h>
-#include <AK/ConditionVariable.h>
-#include <AK/Error.h>
-#include <AK/Mutex.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/RefPtr.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibCore/Forward.h>
-#include <LibIPC/Forward.h>
-#include <LibThreading/Forward.h>
-
-namespace WasmCompilerClient {
-
-class Client;
-
-class ThreadedClient final : public AtomicRefCounted<ThreadedClient> {
- AK_MAKE_NONCOPYABLE(ThreadedClient);
- AK_MAKE_NONMOVABLE(ThreadedClient);
-
-public:
- static ErrorOr<NonnullRefPtr<ThreadedClient>> create(IPC::TransportHandle);
- ~ThreadedClient();
-
- Core::AnonymousBuffer compile(Core::AnonymousBuffer const&);
-
-private:
- explicit ThreadedClient(IPC::TransportHandle);
-
- intptr_t thread_main(IPC::TransportHandle const&);
-
- NonnullRefPtr<Threading::Thread> m_thread;
-
- Mutex m_mutex;
- ConditionVariable m_initialization_condition { m_mutex };
- ConditionVariable m_client_unused_condition { m_mutex };
-
- bool m_initialized { false };
- Optional<Error> m_initialization_error;
-
- RefPtr<Core::WeakEventLoopReference> m_event_loop;
- Client* m_client { nullptr };
-
- size_t m_active_compilations { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 48e4b7f064b..8a34d878912 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1145,7 +1145,7 @@ target_sources(LibWeb PRIVATE $<TARGET_OBJECTS:LibJSObjects>)
target_compile_definitions(LibWeb PRIVATE LibJS_EXPORTS)
target_link_libraries(LibWeb PUBLIC LibCompositing LibWebCommon LibJSHeaders)
-target_link_libraries(LibWeb PRIVATE LibCore LibCompress LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasmRuntime LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)
+target_link_libraries(LibWeb PRIVATE LibCore LibCompress LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasm LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)
# LibWeb still includes ANGLE's GLES headers for WebGL constants and types, but
# the actual GL entry points live in the Compositor. Copy only ANGLE's compile
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.h
index ada4d6a15d4..f61d7ae936d 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.h
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h
@@ -21,7 +21,7 @@
#include <LibJS/Runtime/NativeFunction.h>
#include <LibJS/Runtime/Value.h>
#include <LibURL/URL.h>
-#include <LibWasm/Runtime/Runtime.h>
+#include <LibWasm/Runtime.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/WebIDL/Buffers.h>
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index a57449e9eeb..11a5eb921a8 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -1106,9 +1106,6 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(
// The client's WebContentClient picks up this same session when it is created.
auto request_server_connection = TRY(connect_new_request_server_client(session_for_new_view(is_private), RequestServer::SiteBinding::Bound));
auto image_decoder = TRY(launch_image_decoder_process());
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- auto wasm_compiler_handle = TRY(connect_new_wasm_compiler_client());
-#endif
auto cross_process_id_allocator = allocate_cross_process_id_allocator();
auto root_navigable_id = navigable_to_adopt.has_value() ? *navigable_to_adopt : cross_process_id_allocator.allocate();
@@ -1139,9 +1136,6 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(
client->async_connect_to_request_server(move(request_server_connection.handle), request_server_connection.client_id);
client->async_set_site_compatibility_data(m_site_compatibility_data);
connect_to_image_decoder(*client, move(image_decoder));
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- client->async_connect_to_wasm_compiler(wasm_compiler_handle);
-#endif
if (m_content_blocker_list_buffer.has_value())
client->async_set_content_blockers(*m_content_blocker_list_buffer);
@@ -1755,9 +1749,6 @@ ErrorOr<void> Application::launch_services()
}
TRY(launch_request_server());
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- TRY(launch_wasm_compiler_server());
-#endif
TRY(launch_compositor_process());
if (m_browser_options.devtools_port.has_value()) {
@@ -1969,46 +1960,6 @@ void Application::set_image_decoder_exit_handler(u64 child_id, Function<void()>
m_image_decoder_exit_handlers.set(child_id, move(handler));
}
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-ErrorOr<void> Application::launch_wasm_compiler_server()
-{
- m_wasm_compiler_client = TRY(launch_wasm_compiler_process());
-
- m_wasm_compiler_client->on_death = [this]() {
- m_wasm_compiler_client = nullptr;
-
- if (Core::EventLoop::current().was_exit_requested())
- return;
-
- if (auto result = launch_wasm_compiler_server(); result.is_error()) {
- dbgln("Failed to restart WebAssembly compiler: {}", result.error());
- VERIFY_NOT_REACHED();
- }
-
- auto client_count = WebContentClient::client_count() + WorkerProcessManager::the().client_count();
-
- auto response = m_wasm_compiler_client->send_sync_but_allow_failure<Messages::WasmCompilerServer::ConnectNewClients>(client_count);
- if (!response || response->handles().size() != client_count) {
- dbgln("Failed to connect {} new clients to WasmCompiler", client_count);
- VERIFY_NOT_REACHED();
- }
-
- auto handles = response->take_handles();
-
- WebContentClient::for_each_client([&](WebContentClient& client) {
- client.async_connect_to_wasm_compiler(handles.take_last());
- return IterationDecision::Continue;
- });
- WorkerProcessManager::the().for_each_client([&](WebWorkerClient& client) {
- client.async_connect_to_wasm_compiler(handles.take_last());
- return IterationDecision::Continue;
- });
- };
-
- return {};
-}
-#endif
-
ErrorOr<void> Application::launch_devtools_server()
{
VERIFY(!m_devtools);
@@ -2197,15 +2148,6 @@ void Application::process_did_exit(Process&& process, Optional<int>)
on_request_server_died();
}
break;
- case ProcessType::WasmCompiler:
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- if (auto client = process.client<WasmCompilerClient::Client>()) {
- dbgln_if(WEBVIEW_PROCESS_DEBUG, "Restart WebAssembly compiler");
- if (auto on_death = move(client->on_death))
- on_death();
- }
-#endif
- break;
case ProcessType::WebContent:
if (auto client = process.client<WebContentClient>()) {
client->did_lose_process();
@@ -2740,7 +2682,6 @@ void Application::initialize_actions()
m_debug_menu->add_action(Action::create("Dump Cookies"sv, ActionID::DumpCookies, [this]() { m_default_session->cookie_jar->dump_cookies(); }));
m_debug_menu->add_action(Action::create("Dump Local Storage"sv, ActionID::DumpLocalStorage, debug_request("dump-local-storage"sv)));
m_debug_menu->add_action(Action::create("Dump Session Storage"sv, ActionID::DumpSessionStorage, debug_request("dump-session-storage"sv)));
- m_debug_menu->add_action(Action::create("Dump WASM Stats"sv, ActionID::DumpWasmStats, debug_request("dump-wasm-stats"sv)));
m_debug_menu->add_action(Action::create("Dump GC graph"sv, ActionID::DumpGCGraph, [this]() {
if (auto view = active_web_view(); view.has_value()) {
auto gc_graph_path = view->dump_gc_graph();
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 99d4c01fcc7..bac69405a73 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -65,10 +65,6 @@
# include <LibIPC/TransportBootstrapMach.h>
#endif
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-# include <LibWasmCompilerClient/Client.h>
-#endif
-
namespace Compositing {
struct KeyEvent;
@@ -124,9 +120,6 @@ public:
static ErrorOr<NonnullRefPtr<Requests::RequestClient>> request_server_client(IsPrivate = IsPrivate::No);
// The control connection of the default session's RequestServer with no site.
static Requests::RequestControlClient& request_server_control_client();
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- static WasmCompilerClient::Client& wasm_compiler_client() { return *the().m_wasm_compiler_client; }
-#endif
virtual bool supports_system_menu_bar() const { return false; }
virtual bool supports_vertical_tabs() const { return false; }
@@ -454,9 +447,6 @@ private:
void crash_compositor_process();
void offer_crash_report(ByteString const& report_name);
ErrorOr<void> launch_request_server();
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- ErrorOr<void> launch_wasm_compiler_server();
-#endif
ErrorOr<void> launch_devtools_server();
// Returns whether the combined rules changed.
ErrorOr<bool> load_content_blocker_lists();
@@ -626,9 +616,6 @@ private:
OwnPtr<RequestServerManager> m_request_server_manager;
HashMap<u64, Function<void()>> m_image_decoder_exit_handlers;
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- RefPtr<WasmCompilerClient::Client> m_wasm_compiler_client;
-#endif
RefPtr<CompositorClient> m_compositor_client;
bool m_reported_compositor_gpu_presentation_unavailable { false };
// The last identity a Compositor reported, which outlives that Compositor until its replacement reports.
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 3633093ce91..a10bd97e0b3 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -153,11 +153,6 @@ if (LINUX)
endif()
endif()
-if (ENABLE_CRANELIFT_JIT)
- target_link_libraries(LibWebView PRIVATE LibWasmCompilerClient)
- target_compile_definitions(LibWebView PUBLIC HAVE_WASM_COMPILER_SERVICE=1)
-endif()
-
if (APPLE)
target_link_libraries(LibWebView PRIVATE "-framework Carbon")
endif()
diff --git a/Libraries/LibWebView/CrashReportStore.cpp b/Libraries/LibWebView/CrashReportStore.cpp
index fca3a8af56e..81da143c751 100644
--- a/Libraries/LibWebView/CrashReportStore.cpp
+++ b/Libraries/LibWebView/CrashReportStore.cpp
@@ -66,8 +66,7 @@ bool CrashReportStore::is_saved_report_name(StringView name)
suffix = name.substring_view(timestamp_pattern.length());
}
for (auto type : { ProcessType::Browser, ProcessType::WebContent, ProcessType::WebWorker,
- ProcessType::RequestServer, ProcessType::ImageDecoder, ProcessType::MediaServer, ProcessType::AudioServer, ProcessType::VideoDecoderServer, ProcessType::Compositor,
- ProcessType::WasmCompiler }) {
+ ProcessType::RequestServer, ProcessType::ImageDecoder, ProcessType::MediaServer, ProcessType::AudioServer, ProcessType::VideoDecoderServer, ProcessType::Compositor }) {
auto prefix = ByteString::formatted("{}-", process_name_from_type(type));
if (!suffix.starts_with(prefix) || suffix.length() != prefix.length() + 10)
continue;
diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cpp
index 824b847fc49..44502de8fd6 100644
--- a/Libraries/LibWebView/HelperProcess.cpp
+++ b/Libraries/LibWebView/HelperProcess.cpp
@@ -498,23 +498,6 @@ void shut_down_video_decoder_servers()
s_video_decoder_servers->clear();
}
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-ErrorOr<NonnullRefPtr<WasmCompilerClient::Client>> launch_wasm_compiler_process()
-{
- auto const& browser_options = WebView::Application::browser_options();
-
- Vector<ByteString> arguments;
- if (browser_options.disable_sandbox == DisableSandbox::Yes)
- arguments.append("--disable-sandbox"sv);
- if (auto server = mach_server_name(); server.has_value()) {
- arguments.append("--mach-server-name"sv);
- arguments.append(server.value());
- }
-
- return launch_server_process<WasmCompilerClient::Client>("WasmCompiler"sv, arguments);
-}
-#endif
-
ErrorOr<NonnullRefPtr<WebView::CompositorClient>> launch_compositor_process()
{
auto const& browser_options = WebView::Application::browser_options();
@@ -730,18 +713,4 @@ ErrorOr<MediaServerClientConnection> connect_new_media_server_client(RefPtr<Medi
return MediaServerClientConnection { response->take_handle().release_value(), response->client_id() };
}
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-ErrorOr<IPC::TransportHandle> connect_new_wasm_compiler_client()
-{
- auto response = Application::wasm_compiler_client().send_sync_but_allow_failure<Messages::WasmCompilerServer::ConnectNewClients>(1);
- if (!response)
- return Error::from_string_literal("Failed to connect to WasmCompiler");
-
- auto handles = response->take_handles();
- if (handles.size() != 1)
- return Error::from_string_literal("Failed to connect to WasmCompiler");
- return handles.take_last();
-}
-#endif
-
}
diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.h
index 499a823a84f..900f12be412 100644
--- a/Libraries/LibWebView/HelperProcess.h
+++ b/Libraries/LibWebView/HelperProcess.h
@@ -21,10 +21,6 @@
#include <LibWebView/WebWorkerClient.h>
#include <RequestServer/SiteBinding.h>
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-# include <LibWasmCompilerClient/Client.h>
-#endif
-
namespace WebView {
WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebContentClient>> launch_web_content_process(IsPrivate, Web::PageId initial_page_id, Web::HTML::CrossProcessId root_navigable_id);
@@ -37,9 +33,6 @@ WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::CompositorClient>> launch_compositor_
WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebWorkerClient>> launch_web_worker_process(Web::HTML::AgentType, IsPrivate, Web::HTML::WorkerAgentId);
WEBVIEW_API ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, HTTPDiskCacheMode);
WEBVIEW_API void apply_dns_settings(Requests::RequestControlClient&);
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-WEBVIEW_API ErrorOr<NonnullRefPtr<WasmCompilerClient::Client>> launch_wasm_compiler_process();
-#endif
struct ImageDecoderConnection {
IPC::TransportHandle handle;
@@ -76,8 +69,5 @@ struct MediaServerClientConnection {
int client_id { -1 };
};
WEBVIEW_API ErrorOr<MediaServerClientConnection> connect_new_media_server_client(RefPtr<MediaClient::Client>& controller, Function<ErrorOr<IPC::TransportHandle>()> connect_audio_server);
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-WEBVIEW_API ErrorOr<IPC::TransportHandle> connect_new_wasm_compiler_client();
-#endif
}
diff --git a/Libraries/LibWebView/Menu.h b/Libraries/LibWebView/Menu.h
index a57db30cd1d..9b944dd0764 100644
--- a/Libraries/LibWebView/Menu.h
+++ b/Libraries/LibWebView/Menu.h
@@ -124,7 +124,6 @@ enum class ActionID {
DumpLocalStorage,
DumpSessionStorage,
DumpGCGraph,
- DumpWasmStats,
ShowLineBoxBorders,
ShowCaretHitTestDebugOverlay,
CollectGarbage,
diff --git a/Libraries/LibWebView/Process.cpp b/Libraries/LibWebView/Process.cpp
index ef8df365547..3f7f7269e99 100644
--- a/Libraries/LibWebView/Process.cpp
+++ b/Libraries/LibWebView/Process.cpp
@@ -109,7 +109,6 @@ Vector<ByteString> Process::helper_process_environment(ProcessType type)
};
static constexpr Array allowed_prefixes {
"ASAN_"sv,
- "CRANELIFT_"sv,
"LADYBIRD_"sv,
"LC_"sv,
"LIBGC_"sv,
diff --git a/Libraries/LibWebView/ProcessManager.cpp b/Libraries/LibWebView/ProcessManager.cpp
index f40ca7bb22a..9cd1a999ba9 100644
--- a/Libraries/LibWebView/ProcessManager.cpp
+++ b/Libraries/LibWebView/ProcessManager.cpp
@@ -33,8 +33,6 @@ ProcessType process_type_from_name(StringView name)
return ProcessType::AudioServer;
if (name == "VideoDecoderServer"sv)
return ProcessType::VideoDecoderServer;
- if (name == "WasmCompiler"sv)
- return ProcessType::WasmCompiler;
dbgln("Unknown process type: '{}'", name);
VERIFY_NOT_REACHED();
@@ -61,8 +59,6 @@ StringView process_name_from_type(ProcessType type)
return "AudioServer"sv;
case ProcessType::VideoDecoderServer:
return "VideoDecoderServer"sv;
- case ProcessType::WasmCompiler:
- return "WasmCompiler"sv;
}
VERIFY_NOT_REACHED();
}
diff --git a/Libraries/LibWebView/ProcessType.h b/Libraries/LibWebView/ProcessType.h
index a6ce6b70ad9..fcdb856e3b2 100644
--- a/Libraries/LibWebView/ProcessType.h
+++ b/Libraries/LibWebView/ProcessType.h
@@ -20,7 +20,6 @@ enum class ProcessType : u8 {
MediaServer,
AudioServer,
VideoDecoderServer,
- WasmCompiler,
};
}
diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cpp
index b1f4566fbea..728ade504e6 100644
--- a/Libraries/LibWebView/WorkerProcessManager.cpp
+++ b/Libraries/LibWebView/WorkerProcessManager.cpp
@@ -220,9 +220,6 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, O
request_server_instance = TRY(RequestServerManager::the().browser_instance(*session));
auto request_server_connection = TRY(RequestServerManager::the().connect_new_client(*request_server_instance, *session, RequestServer::SiteBinding::Bound));
auto image_decoder = TRY(launch_image_decoder_process());
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- auto wasm_compiler_handle = TRY(connect_new_wasm_compiler_client());
-#endif
client->request_server_site_bindings().did_connect(request_server_connection.client_id);
client->async_connect_to_request_server(move(request_server_connection.handle), request_server_connection.client_id);
@@ -234,9 +231,6 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, O
client->async_set_navigator_compatibility_mode(Application::the().navigator_compatibility_mode());
client->async_set_preferred_languages(Application::settings().languages());
connect_to_image_decoder(*client, move(image_decoder));
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- client->async_connect_to_wasm_compiler(wasm_compiler_handle);
-#endif
if (auto compositor_handle = Application::the().connect_new_compositor_canvas_client(); !compositor_handle.is_error())
client->async_connect_to_compositor(compositor_handle.release_value());
diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmake
index b6d776d1e13..adbd60a14e7 100644
--- a/Meta/CMake/all_the_debug_macros.cmake
+++ b/Meta/CMake/all_the_debug_macros.cmake
@@ -68,12 +68,6 @@ set(URL_PATTERN_DEBUG ON)
set(UTF8_DEBUG ON)
set(VIDEO_FRAME_POOL_DEBUG ON)
set(VULKAN_VALIDATION_LAYERS_DEBUG ON)
-set(WASI_DEBUG ON)
-set(WASI_FINE_GRAINED_DEBUG ON)
-set(WASM_BINPARSER_DEBUG ON)
-set(WASM_CRANELIFT_DEBUG ON)
-set(WASM_TRACE_DEBUG ON)
-set(WASM_VALIDATOR_DEBUG ON)
set(WEBDRIVER_DEBUG ON)
set(WEBDRIVER_ROUTE_DEBUG ON)
set(VIDEO_PRESENTATION_CHANNEL_DEBUG ON)
diff --git a/Meta/CMake/cmake_options.cmake b/Meta/CMake/cmake_options.cmake
index 7a122bcbb5a..16584e6e42d 100644
--- a/Meta/CMake/cmake_options.cmake
+++ b/Meta/CMake/cmake_options.cmake
@@ -7,7 +7,6 @@ option(UNDEFINED_BEHAVIOR_IS_FATAL "Make undefined behavior sanitizer errors non
option(ENABLE_ALL_THE_DEBUG_MACROS "Enable all debug macros to validate they still compile" OFF)
option(INCLUDE_WASM_SPEC_TESTS "Download and include the WebAssembly spec testsuite" OFF)
-option(ENABLE_CRANELIFT_JIT "Enable Cranelift-based AOT compilation for WebAssembly" ON)
# The optimizing JIT for JavaScript generates code for x86-64 and AArch64 with the calling conventions of Linux and
# macOS. Elsewhere, LibJS runs JavaScript in its interpreter alone.
diff --git a/Meta/CMake/flatpak/cargo-sources.json b/Meta/CMake/flatpak/cargo-sources.json
index a8de51947c8..0c000334fa1 100644
--- a/Meta/CMake/flatpak/cargo-sources.json
+++ b/Meta/CMake/flatpak/cargo-sources.json
@@ -75,13 +75,6 @@
"sha256": "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470",
"dest": "cargo/vendor/anyhow-1.0.104"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/arbitrary/arbitrary-1.4.2.crate",
- "sha256": "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1",
- "dest": "cargo/vendor/arbitrary-1.4.2"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -117,13 +110,6 @@
"sha256": "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af",
"dest": "cargo/vendor/bitflags-2.11.0"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/bumpalo/bumpalo-3.20.2.crate",
- "sha256": "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb",
- "dest": "cargo/vendor/bumpalo-3.20.2"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -208,104 +194,6 @@
"sha256": "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30",
"dest": "cargo/vendor/core_maths-0.1.1"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-assembler-x64/cranelift-assembler-x64-0.136.3.crate",
- "sha256": "f6d504c8c7ba3f3accaf8e98b7096beb98e1a271404357744c7e9e730c6865ff",
- "dest": "cargo/vendor/cranelift-assembler-x64-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-assembler-x64-meta/cranelift-assembler-x64-meta-0.136.3.crate",
- "sha256": "c065757905596bc06e82969ebd7b92d691b7fd710a7e9e8181ae0c30dab588d0",
- "dest": "cargo/vendor/cranelift-assembler-x64-meta-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-bforest/cranelift-bforest-0.136.3.crate",
- "sha256": "5ca7162cd4d4fc5f9f2f88d1459d939882203d93a8c5a19ef2c405b2e82ef13f",
- "dest": "cargo/vendor/cranelift-bforest-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-bitset/cranelift-bitset-0.136.3.crate",
- "sha256": "0ec2ba2d4f3d959ec4023a10266c3dcfb28381d1938d507a9a5e1abb78bbcc88",
- "dest": "cargo/vendor/cranelift-bitset-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-codegen/cranelift-codegen-0.136.3.crate",
- "sha256": "51a64cb821d5fed56bdd6053acd36fa928cd82b70bf6b19b8b14b8b27d047b9a",
- "dest": "cargo/vendor/cranelift-codegen-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-codegen-meta/cranelift-codegen-meta-0.136.3.crate",
- "sha256": "142be1e267a7497ba3c2b5a829eaf5387b92b9bcdba6e0a6020f1ffccae7f2b8",
- "dest": "cargo/vendor/cranelift-codegen-meta-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-codegen-shared/cranelift-codegen-shared-0.136.3.crate",
- "sha256": "0e41f75410da6cce8601330137d73718f679db81cb790a33de3871b5c90a0de3",
- "dest": "cargo/vendor/cranelift-codegen-shared-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-control/cranelift-control-0.136.3.crate",
- "sha256": "0c2616c6d01c14921ac9289ef65eb7702d9c760dfdc4537a8ee5bf38ea2832c6",
- "dest": "cargo/vendor/cranelift-control-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-entity/cranelift-entity-0.136.3.crate",
- "sha256": "a03e8b44c4877cf2fb21e5788d514af6fd291a066ed9ae37adf114a25fecb4aa",
- "dest": "cargo/vendor/cranelift-entity-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-frontend/cranelift-frontend-0.136.3.crate",
- "sha256": "366ff7cb014bd08752210eba55a650969f8db9b52670d69d2ea0b23e1e9e3edf",
- "dest": "cargo/vendor/cranelift-frontend-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-isle/cranelift-isle-0.136.3.crate",
- "sha256": "9ea6526ebf9064fff8ce3b1e26afad7027f9e6bb0e45d2b9200e4cbab8343345",
- "dest": "cargo/vendor/cranelift-isle-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-module/cranelift-module-0.136.3.crate",
- "sha256": "d9d429c66b47fc0482e2398f660bda8f4cae30e5ae4e82a281b04f9beaefe1cf",
- "dest": "cargo/vendor/cranelift-module-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-native/cranelift-native-0.136.3.crate",
- "sha256": "b44d323f3e5108a8a5bc61f3acd227285ece066e19afe9aece211d66b34a64ea",
- "dest": "cargo/vendor/cranelift-native-0.136.3"
- },
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/cranelift-srcgen/cranelift-srcgen-0.136.3.crate",
- "sha256": "fc173168f291ff3b95b5d0769d6a05b1eaef5e6d74c2600affab8396b4e7b420",
- "dest": "cargo/vendor/cranelift-srcgen-0.136.3"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -369,13 +257,6 @@
"sha256": "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3",
"dest": "cargo/vendor/flatbuffers-25.12.19"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/fnv/fnv-1.0.7.crate",
- "sha256": "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1",
- "dest": "cargo/vendor/fnv-1.0.7"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -404,13 +285,6 @@
"sha256": "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555",
"dest": "cargo/vendor/getrandom-0.4.2"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/gimli/gimli-0.33.0.crate",
- "sha256": "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c",
- "dest": "cargo/vendor/gimli-0.33.0"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -775,13 +649,6 @@
"sha256": "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf",
"dest": "cargo/vendor/r-efi-6.0.0"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/regalloc2/regalloc2-0.15.2.crate",
- "sha256": "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85",
- "dest": "cargo/vendor/regalloc2-0.15.2"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -950,13 +817,6 @@
"sha256": "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2",
"dest": "cargo/vendor/synstructure-0.13.2"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/target-lexicon/target-lexicon-0.13.5.crate",
- "sha256": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca",
- "dest": "cargo/vendor/target-lexicon-0.13.5"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -1097,13 +957,6 @@
"sha256": "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe",
"dest": "cargo/vendor/wasmparser-0.244.0"
},
- {
- "type": "archive",
- "archive-type": "tar-gzip",
- "url": "https://static.crates.io/crates/wasmtime-internal-core/wasmtime-internal-core-49.0.3.crate",
- "sha256": "ba00c5db77adb0749ee059068e5a417bfac3d8969f5a3479d9bd1ca8c1ba248d",
- "dest": "cargo/vendor/wasmtime-internal-core-49.0.3"
- },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -1257,13 +1110,11 @@
"echo '{\"files\": {}, \"package\": \"40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc\"}' > cargo/vendor/anstyle-query-1.1.5/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d\"}' > cargo/vendor/anstyle-wincon-3.0.11/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470\"}' > cargo/vendor/anyhow-1.0.104/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1\"}' > cargo/vendor/arbitrary-1.4.2/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc\"}' > cargo/vendor/array-init-2.1.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50\"}' > cargo/vendor/arrayvec-0.7.6/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8\"}' > cargo/vendor/autocfg-1.5.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6\"}' > cargo/vendor/base64-0.22.1/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af\"}' > cargo/vendor/bitflags-2.11.0/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb\"}' > cargo/vendor/bumpalo-3.20.2/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b\"}' > cargo/vendor/byteorder-1.5.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26\"}' > cargo/vendor/calendrical_calculations-0.2.4/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"befbfd072a8e81c02f8c507aefce431fe5e7d051f83d48a23ffc9b9fe5a11799\"}' > cargo/vendor/cbindgen-0.29.2/.cargo-checksum.json",
@@ -1276,20 +1127,6 @@
"echo '{\"files\": {}, \"package\": \"1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570\"}' > cargo/vendor/colorchoice-1.0.5/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48\"}' > cargo/vendor/core_detect-1.0.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30\"}' > cargo/vendor/core_maths-0.1.1/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"f6d504c8c7ba3f3accaf8e98b7096beb98e1a271404357744c7e9e730c6865ff\"}' > cargo/vendor/cranelift-assembler-x64-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"c065757905596bc06e82969ebd7b92d691b7fd710a7e9e8181ae0c30dab588d0\"}' > cargo/vendor/cranelift-assembler-x64-meta-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"5ca7162cd4d4fc5f9f2f88d1459d939882203d93a8c5a19ef2c405b2e82ef13f\"}' > cargo/vendor/cranelift-bforest-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"0ec2ba2d4f3d959ec4023a10266c3dcfb28381d1938d507a9a5e1abb78bbcc88\"}' > cargo/vendor/cranelift-bitset-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"51a64cb821d5fed56bdd6053acd36fa928cd82b70bf6b19b8b14b8b27d047b9a\"}' > cargo/vendor/cranelift-codegen-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"142be1e267a7497ba3c2b5a829eaf5387b92b9bcdba6e0a6020f1ffccae7f2b8\"}' > cargo/vendor/cranelift-codegen-meta-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"0e41f75410da6cce8601330137d73718f679db81cb790a33de3871b5c90a0de3\"}' > cargo/vendor/cranelift-codegen-shared-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"0c2616c6d01c14921ac9289ef65eb7702d9c760dfdc4537a8ee5bf38ea2832c6\"}' > cargo/vendor/cranelift-control-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"a03e8b44c4877cf2fb21e5788d514af6fd291a066ed9ae37adf114a25fecb4aa\"}' > cargo/vendor/cranelift-entity-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"366ff7cb014bd08752210eba55a650969f8db9b52670d69d2ea0b23e1e9e3edf\"}' > cargo/vendor/cranelift-frontend-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"9ea6526ebf9064fff8ce3b1e26afad7027f9e6bb0e45d2b9200e4cbab8343345\"}' > cargo/vendor/cranelift-isle-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"d9d429c66b47fc0482e2398f660bda8f4cae30e5ae4e82a281b04f9beaefe1cf\"}' > cargo/vendor/cranelift-module-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"b44d323f3e5108a8a5bc61f3acd227285ece066e19afe9aece211d66b34a64ea\"}' > cargo/vendor/cranelift-native-0.136.3/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"fc173168f291ff3b95b5d0769d6a05b1eaef5e6d74c2600affab8396b4e7b420\"}' > cargo/vendor/cranelift-srcgen-0.136.3/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0\"}' > cargo/vendor/displaydoc-0.2.5/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e\"}' > cargo/vendor/either-1.16.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679\"}' > cargo/vendor/encoding_rs-0.8.42/.cargo-checksum.json",
@@ -1299,12 +1136,10 @@
"echo '{\"files\": {}, \"package\": \"a043dc74da1e37d6afe657061213aa6f425f855399a11d3463c6ecccc4dfda1f\"}' > cargo/vendor/fastrand-2.4.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484\"}' > cargo/vendor/find-msvc-tools-0.1.14/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3\"}' > cargo/vendor/flatbuffers-25.12.19/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1\"}' > cargo/vendor/fnv-1.0.7/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2\"}' > cargo/vendor/foldhash-0.1.5/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb\"}' > cargo/vendor/foldhash-0.2.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf\"}' > cargo/vendor/form_urlencoded-1.2.2/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555\"}' > cargo/vendor/getrandom-0.4.2/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c\"}' > cargo/vendor/gimli-0.33.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1\"}' > cargo/vendor/hashbrown-0.15.5/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100\"}' > cargo/vendor/hashbrown-0.16.1/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a\"}' > cargo/vendor/hashbrown-0.17.1/.cargo-checksum.json",
@@ -1357,7 +1192,6 @@
"echo '{\"files\": {}, \"package\": \"33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac\"}' > cargo/vendor/psl-types-2.0.11/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924\"}' > cargo/vendor/quote-1.0.45/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf\"}' > cargo/vendor/r-efi-6.0.0/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85\"}' > cargo/vendor/regalloc2-0.15.2/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276\"}' > cargo/vendor/regex-1.12.3/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f\"}' > cargo/vendor/regex-automata-0.4.14/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a\"}' > cargo/vendor/regex-syntax-0.8.10/.cargo-checksum.json",
@@ -1382,7 +1216,6 @@
"echo '{\"files\": {}, \"package\": \"e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99\"}' > cargo/vendor/syn-2.0.117/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f\"}' > cargo/vendor/syn-3.0.4/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2\"}' > cargo/vendor/synstructure-0.13.2/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca\"}' > cargo/vendor/target-lexicon-0.13.5/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd\"}' > cargo/vendor/tempfile-3.27.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52\"}' > cargo/vendor/thiserror-1.0.69/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f\"}' > cargo/vendor/thiserror-2.0.20/.cargo-checksum.json",
@@ -1403,7 +1236,6 @@
"echo '{\"files\": {}, \"package\": \"990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319\"}' > cargo/vendor/wasm-encoder-0.244.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909\"}' > cargo/vendor/wasm-metadata-0.244.0/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe\"}' > cargo/vendor/wasmparser-0.244.0/.cargo-checksum.json",
- "echo '{\"files\": {}, \"package\": \"ba00c5db77adb0749ee059068e5a417bfac3d8969f5a3479d9bd1ca8c1ba248d\"}' > cargo/vendor/wasmtime-internal-core-49.0.3/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5\"}' > cargo/vendor/windows-link-0.2.1/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc\"}' > cargo/vendor/windows-sys-0.61.2/.cargo-checksum.json",
"echo '{\"files\": {}, \"package\": \"df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945\"}' > cargo/vendor/winnow-0.7.15/.cargo-checksum.json",
diff --git a/Meta/CMake/ladybird_helper_processes.cmake b/Meta/CMake/ladybird_helper_processes.cmake
index 89889f098df..a41ccef1947 100644
--- a/Meta/CMake/ladybird_helper_processes.cmake
+++ b/Meta/CMake/ladybird_helper_processes.cmake
@@ -9,17 +9,13 @@ set(ladybird_helper_processes
WebWorker
)
-if (ENABLE_CRANELIFT_JIT)
- list(APPEND ladybird_helper_processes WasmCompiler)
-endif()
-
# Kills the helpers when the Browser is gone, which the kernel cannot do on macOS.
if (APPLE)
list(APPEND ladybird_helper_processes ProcessReaper)
endif()
# On macOS, helpers run with the hardened runtime, so the kernel refuses to run code from memory that was writable, except
-# in the MAP_JIT regions where the renderers put the WebAssembly code that Cranelift compiles. Library validation stays
+# in the MAP_JIT regions where the renderers put the code that their JIT compilers generate. Library validation stays
# off, since development builds sign their libraries ad hoc, without a team identifier. Every build of the helper signs
# it, so that targeted builds keep these protections too.
function(ladybird_sign_helper_process target)
diff --git a/Meta/Fuzzers/FuzzWasmParser.cpp b/Meta/Fuzzers/FuzzWasmParser.cpp
index cd396988b13..2875ce7106a 100644
--- a/Meta/Fuzzers/FuzzWasmParser.cpp
+++ b/Meta/Fuzzers/FuzzWasmParser.cpp
@@ -4,16 +4,14 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/MemoryStream.h>
-#include <LibWasm/Types.h>
+#include <LibWasm/Runtime.h>
#include <stddef.h>
#include <stdint.h>
extern "C" int LLVMFuzzerTestOneInput(uint8_t const* data, size_t size)
{
AK::set_debug_enabled(false);
- ReadonlyBytes bytes { data, size };
- FixedMemoryStream stream { bytes };
- [[maybe_unused]] auto result = Wasm::Module::parse(stream);
+ // Compiling a module decodes and validates it.
+ [[maybe_unused]] auto result = Wasm::Runtime::Module::compile(ReadonlyBytes { data, size });
return 0;
}
diff --git a/Meta/Generators/generate-build-information.py b/Meta/Generators/generate-build-information.py
index d2a0aa71b3d..1d7b82fd751 100755
--- a/Meta/Generators/generate-build-information.py
+++ b/Meta/Generators/generate-build-information.py
@@ -19,7 +19,6 @@ HELPERS = (
"MediaServer",
"RequestServer",
"VideoDecoderServer",
- "WasmCompiler",
"WebContent",
"WebWorker",
)
diff --git a/Services/CMakeLists.txt b/Services/CMakeLists.txt
index 14d5fdaf2e7..654e395180e 100644
--- a/Services/CMakeLists.txt
+++ b/Services/CMakeLists.txt
@@ -7,9 +7,6 @@ if (APPLE)
endif()
add_subdirectory(RequestServer)
add_subdirectory(VideoDecoderServer)
-if (ENABLE_CRANELIFT_JIT)
- add_subdirectory(WasmCompiler)
-endif()
add_subdirectory(WebContent)
add_subdirectory(WebDriver)
add_subdirectory(WebWorker)
diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cpp
index 6a2c9987353..b2ac2ddcf22 100644
--- a/Services/RequestServer/ConnectionFromClient.cpp
+++ b/Services/RequestServer/ConnectionFromClient.cpp
@@ -877,23 +877,6 @@ Messages::RequestServer::RetrieveCacheAssociatedDataResponse ConnectionFromClien
return Optional<Core::AnonymousBuffer> { buffer.release_value() };
}
-Messages::RequestServer::CreateSyntheticCacheEntryResponse ConnectionFromClient::create_synthetic_cache_entry(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method)
-{
- if (network_isolation_key.has_value() && !may_use_network_isolation_key(*network_isolation_key))
- return false;
-
- auto partition = network_isolation_key.has_value() ? network_isolation_key->disk_cache_partition() : OptionalNone {};
- if (!m_disk_cache.has_value() || !partition.has_value())
- return false;
-
- auto result = m_disk_cache->create_synthetic_entry(*partition, url, method);
- if (result.is_error()) {
- dbgln("Failed to create synthetic cache entry for {}: {}", url, result.error());
- return false;
- }
- return result.value();
-}
-
size_t ConnectionFromClient::websocket_count() const
{
return m_pending_websockets.size() + m_websockets.size();
diff --git a/Services/RequestServer/ConnectionFromClient.h b/Services/RequestServer/ConnectionFromClient.h
index 2df46700c53..675be55f1a3 100644
--- a/Services/RequestServer/ConnectionFromClient.h
+++ b/Services/RequestServer/ConnectionFromClient.h
@@ -97,8 +97,6 @@ private:
virtual Messages::RequestServer::StoreCacheAssociatedDataResponse store_cache_associated_data(Optional<HTTP::NetworkIsolationKey>, URL::URL, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData, Core::AnonymousBuffer) override;
virtual Messages::RequestServer::RetrieveCacheAssociatedDataResponse retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey>, URL::URL, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData) override;
- virtual Messages::RequestServer::CreateSyntheticCacheEntryResponse create_synthetic_cache_entry(Optional<HTTP::NetworkIsolationKey>, URL::URL, ByteString method) override;
-
virtual void websocket_connect(u64 websocket_id, URL::URL, Optional<HTTP::NetworkIsolationKey>, ByteString, Vector<ByteString>, Vector<ByteString>, Vector<HTTP::Header>) override;
virtual void websocket_send(u64 websocket_id, bool, ByteBuffer) override;
virtual void websocket_send_shared(u64 websocket_id, bool, Core::AnonymousBuffer) override;
diff --git a/Services/RequestServer/RequestServer.ipc b/Services/RequestServer/RequestServer.ipc
index d73b66a7a4d..b7e3d7825a5 100644
--- a/Services/RequestServer/RequestServer.ipc
+++ b/Services/RequestServer/RequestServer.ipc
@@ -32,7 +32,6 @@ endpoint RequestServer
store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data, Core::AnonymousBuffer data) => (Optional<IPC::File> file, u64 size)
retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data) => (Optional<Core::AnonymousBuffer> data)
- create_synthetic_cache_entry(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method) => (bool created)
// Websocket Connection API
websocket_connect(u64 websocket_id, URL::URL url, Optional<HTTP::NetworkIsolationKey> network_isolation_key, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers) =|
diff --git a/Services/WasmCompiler/CMakeLists.txt b/Services/WasmCompiler/CMakeLists.txt
deleted file mode 100644
index d5f1fe06185..00000000000
--- a/Services/WasmCompiler/CMakeLists.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-set(SOURCES
- Compiler.cpp
- ConnectionFromClient.cpp
-)
-
-add_library(wasmcompilerservice STATIC ${SOURCES})
-add_executable(WasmCompiler main.cpp)
-
-if (LINUX)
- target_sources(WasmCompiler PRIVATE SandboxLinux.cpp)
-elseif (APPLE)
- target_sources(WasmCompiler PRIVATE SandboxMacOS.cpp)
-else()
- target_sources(WasmCompiler PRIVATE SandboxUnimplemented.cpp)
-endif()
-
-add_dependencies(wasmcompilerservice
- generate_WasmCompilerClientEndpoint.h
- generate_WasmCompilerServerEndpoint.h
-)
-
-target_include_directories(wasmcompilerservice PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/../..)
-target_include_directories(wasmcompilerservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)
-
-target_link_libraries(WasmCompiler PRIVATE wasmcompilerservice LibCore LibMain LibSandbox LibThreading)
-target_link_libraries(wasmcompilerservice PRIVATE LibCore LibCrypto LibIPC LibThreading LibWasm LibWasmCompilerClient)
-
-if (WIN32)
- ladybird_windows_bin(WasmCompiler CONSOLE)
-endif()
-
-ladybird_sign_helper_process(WasmCompiler)
diff --git a/Services/WasmCompiler/Compiler.cpp b/Services/WasmCompiler/Compiler.cpp
deleted file mode 100644
index 4ba7053d78d..00000000000
--- a/Services/WasmCompiler/Compiler.cpp
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NumericLimits.h>
-#include <LibCore/EventLoop.h>
-#include <LibCore/Process.h>
-#include <LibCrypto/Hash/SHA2.h>
-#include <LibThreading/ThreadPool.h>
-#include <LibWasm/Types.h>
-#include <WasmCompiler/Compiler.h>
-#include <WasmCompiler/ConnectionFromClient.h>
-
-namespace WasmCompiler {
-
-static constexpr size_t MAXIMUM_INPUT_BYTES = 512 * MiB;
-static constexpr size_t MAXIMUM_PENDING_INPUT_BYTES = 1 * GiB;
-static constexpr size_t MAXIMUM_PENDING_JOBS = 32;
-static constexpr size_t MAXIMUM_PENDING_REQUESTS = 256;
-static constexpr size_t MAXIMUM_PENDING_REQUESTS_PER_CLIENT = 8;
-static constexpr size_t MAXIMUM_CONCURRENT_COMPILATIONS = 2;
-static constexpr auto MAXIMUM_JOB_DURATION = AK::Duration::from_seconds(60);
-
-void Compiler::compile(ConnectionFromClient& client, u64 request_id, Core::AnonymousBuffer const& input)
-{
- auto client_id = client.client_id();
-
- if (m_pending_requests >= MAXIMUM_PENDING_REQUESTS || !client_has_capacity(client_id)) {
- warnln("WasmCompiler: Pending request limit reached");
- client.async_did_compile(request_id, {});
- return;
- }
-
- if (!input.is_valid() || input.size() > MAXIMUM_INPUT_BYTES) {
- warnln("WasmCompiler: Rejecting {}-byte input buffer", input.size());
- client.async_did_compile(request_id, {});
- return;
- }
-
- auto private_input = input.snapshot(Core::AnonymousBuffer::Sealability::Sealable);
- if (private_input.is_error()) {
- warnln("WasmCompiler: Failed to snapshot input buffer: {}", private_input.error());
- client.async_did_compile(request_id, {});
- return;
- }
-
- Optional<ByteString> digest;
-
- for (auto& job : m_jobs) {
- if (job.value->input.size() != private_input.value().size())
- continue;
-
- if (!digest.has_value())
- digest = ByteString { Crypto::Hash::SHA256::hash(private_input.value().bytes()).bytes() };
- if (!job.value->digest.has_value())
- job.value->digest = ByteString { Crypto::Hash::SHA256::hash(job.value->input.bytes()).bytes() };
-
- if (*job.value->digest == *digest && job.value->input.bytes() == private_input.value().bytes()) {
- dbgln_if(WASM_CRANELIFT_DEBUG, "WasmCompiler: Coalesced an in-flight compilation request");
- job.value->requests.empend(client.make_weak_ptr<ConnectionFromClient>(), client_id, request_id);
- add_pending_request(client_id);
- return;
- }
- }
-
- if (m_jobs.size() >= MAXIMUM_PENDING_JOBS
- || m_next_job_id == NumericLimits<u64>::max()
- || private_input.value().size() > MAXIMUM_PENDING_INPUT_BYTES - m_pending_input_bytes) {
- warnln("WasmCompiler: Pending compilation limit reached");
- client.async_did_compile(request_id, {});
- return;
- }
-
- auto job = make<Job>(MonotonicTime::now());
- job->digest = move(digest);
- job->input = private_input.release_value();
- job->requests.empend(client.make_weak_ptr<ConnectionFromClient>(), client_id, request_id);
-
- auto job_id = m_next_job_id++;
- m_pending_jobs.enqueue(job_id);
- m_pending_input_bytes += job->input.size();
- m_jobs.set(job_id, move(job));
-
- add_pending_request(client_id);
- start_pending_jobs();
-}
-
-bool Compiler::client_has_capacity(int client_id) const
-{
- return m_pending_requests_per_client.get(client_id).value_or(0) < MAXIMUM_PENDING_REQUESTS_PER_CLIENT;
-}
-
-void Compiler::add_pending_request(int client_id)
-{
- VERIFY(m_pending_requests < MAXIMUM_PENDING_REQUESTS);
- ++m_pending_requests;
-
- m_pending_requests_per_client.set(client_id, m_pending_requests_per_client.get(client_id).value_or(0) + 1);
-}
-
-void Compiler::remove_pending_request(int client_id)
-{
- VERIFY(m_pending_requests > 0);
- --m_pending_requests;
-
- auto count = m_pending_requests_per_client.get(client_id);
- VERIFY(count.has_value() && *count > 0);
-
- if (*count == 1)
- m_pending_requests_per_client.remove(client_id);
- else
- m_pending_requests_per_client.set(client_id, *count - 1);
-}
-
-void Compiler::start_pending_jobs()
-{
- while (m_active_jobs < MAXIMUM_CONCURRENT_COMPILATIONS && !m_pending_jobs.is_empty()) {
- auto job_id = m_pending_jobs.dequeue();
- auto job = m_jobs.get(job_id);
- VERIFY(job.has_value());
-
- auto time_in_queue = MonotonicTime::now() - job.value()->enqueued_at;
- if (time_in_queue >= MAXIMUM_JOB_DURATION) {
- expire_job(job_id);
- continue;
- }
-
- dbgln_if(WASM_CRANELIFT_DEBUG, "WasmCompiler: Compiling a {}-byte batch", job.value()->input.size());
- ++m_active_jobs;
-
- job.value()->watchdog = Core::Timer::create_single_shot(MAXIMUM_JOB_DURATION, [this, job_id] {
- Core::EventLoop::current().deferred_invoke([this, job_id] {
- if (!m_jobs.contains(job_id))
- return;
- warnln("WasmCompiler: Compilation request exceeded {} seconds", MAXIMUM_JOB_DURATION.to_seconds());
- Core::Process::terminate_immediately(1);
- });
- });
- job.value()->watchdog->start();
-
- Threading::ThreadPool::the().submit([this, main_thread_event_loop = Core::EventLoop::current_weak(), job_id, input = job.value()->input]() mutable {
- Core::AnonymousBuffer output;
- auto start = MonotonicTime::now();
-
- if (auto result = ::Wasm::compile_cranelift_buffer(input); result.is_error())
- warnln("WasmCompiler: Compilation failed: {}", result.error());
- else
- output = result.release_value();
-
- auto compilation_duration = MonotonicTime::now() - start;
-
- if (auto event_loop = main_thread_event_loop->take()) {
- event_loop->deferred_invoke([this, job_id, output = move(output), compilation_duration]() mutable {
- complete_job(job_id, move(output), compilation_duration);
- });
- }
- });
- }
-}
-
-void Compiler::expire_job(u64 job_id)
-{
- warnln("WasmCompiler: Compilation request expired in the queue");
- finish_job(job_id, {}, MonotonicTime::now() - m_jobs.get(job_id).value()->enqueued_at);
-}
-
-void Compiler::complete_job(u64 job_id, Core::AnonymousBuffer output, AK::Duration compilation_duration)
-{
- VERIFY(m_active_jobs > 0);
- --m_active_jobs;
-
- finish_job(job_id, move(output), compilation_duration);
- start_pending_jobs();
-}
-
-void Compiler::finish_job(u64 job_id, Core::AnonymousBuffer output, AK::Duration compilation_duration)
-{
- auto job = m_jobs.take(job_id);
- VERIFY(job.has_value());
-
- if (job.value()->watchdog)
- job.value()->watchdog->stop();
-
- VERIFY(m_pending_input_bytes >= job.value()->input.size());
- m_pending_input_bytes -= job.value()->input.size();
-
- dbgln_if(WASM_CRANELIFT_DEBUG, "WasmCompiler: Completed request in {} ms ({})",
- compilation_duration.to_milliseconds(), output.is_valid() ? "success"sv : "failure"sv);
- auto single_recipient = job.value()->requests.size() == 1;
-
- for (auto const& request : job.value()->requests) {
- remove_pending_request(request.client_id);
-
- if (auto client = request.client.strong_ref()) {
- Core::AnonymousBuffer shared_output;
-
- if (output.is_valid()) {
- if (single_recipient)
- shared_output = move(output);
- else if (auto result = output.snapshot(Core::AnonymousBuffer::Sealability::Sealable); !result.is_error())
- shared_output = result.release_value();
- }
-
- client->async_did_compile(request.request_id, shared_output);
- }
- }
-}
-
-}
diff --git a/Services/WasmCompiler/Compiler.h b/Services/WasmCompiler/Compiler.h
deleted file mode 100644
index d749e6ae4c2..00000000000
--- a/Services/WasmCompiler/Compiler.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteString.h>
-#include <AK/HashMap.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/Optional.h>
-#include <AK/Queue.h>
-#include <AK/Time.h>
-#include <AK/WeakPtr.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibCore/Timer.h>
-#include <WasmCompiler/Forward.h>
-
-namespace WasmCompiler {
-
-class Compiler {
-public:
- void compile(ConnectionFromClient&, u64 request_id, Core::AnonymousBuffer const&);
-
-private:
- struct Request {
- WeakPtr<ConnectionFromClient> client;
- int client_id { 0 };
- u64 request_id { 0 };
- };
-
- struct Job {
- AK_ALLOC_WITH_KMALLOC;
-
- explicit Job(MonotonicTime enqueued_at)
- : enqueued_at(enqueued_at)
- {
- }
-
- Optional<ByteString> digest;
- Core::AnonymousBuffer input;
- Vector<Request> requests;
- MonotonicTime enqueued_at;
- RefPtr<Core::Timer> watchdog;
- };
-
- bool client_has_capacity(int client_id) const;
- void add_pending_request(int client_id);
- void remove_pending_request(int client_id);
- void start_pending_jobs();
- void expire_job(u64 job_id);
- void complete_job(u64 job_id, Core::AnonymousBuffer, AK::Duration);
- void finish_job(u64 job_id, Core::AnonymousBuffer, AK::Duration);
-
- HashMap<u64, NonnullOwnPtr<Job>> m_jobs;
- u64 m_next_job_id { 1 };
- size_t m_active_jobs { 0 };
-
- Queue<u64> m_pending_jobs;
- HashMap<int, size_t> m_pending_requests_per_client;
- size_t m_pending_input_bytes { 0 };
- size_t m_pending_requests { 0 };
-};
-
-}
diff --git a/Services/WasmCompiler/ConnectionFromClient.cpp b/Services/WasmCompiler/ConnectionFromClient.cpp
deleted file mode 100644
index d91bc3e33c6..00000000000
--- a/Services/WasmCompiler/ConnectionFromClient.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NeverDestroyed.h>
-#include <AK/NumericLimits.h>
-#include <LibCore/Process.h>
-#include <WasmCompiler/Compiler.h>
-#include <WasmCompiler/ConnectionFromClient.h>
-
-namespace WasmCompiler {
-
-static NeverDestroyed<HashMap<int, NonnullRefPtr<ConnectionFromClient>>> s_connections;
-static int s_next_client_id { 1 };
-
-static int allocate_client_id()
-{
- VERIFY(s_next_client_id != NumericLimits<int>::max());
- return s_next_client_id++;
-}
-
-ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, Compiler& compiler, Role role)
- : IPC::ConnectionFromClient<WasmCompilerClientEndpoint, WasmCompilerServerEndpoint>(*this, move(transport), allocate_client_id())
- , m_compiler(compiler)
- , m_role(role)
-{
- s_connections->set(client_id(), *this);
-}
-
-void ConnectionFromClient::die()
-{
- auto terminate = m_role == Role::Controller;
- s_connections->remove(client_id());
-
- if (terminate)
- Core::Process::terminate_immediately(0);
-}
-
-ErrorOr<IPC::TransportHandle> ConnectionFromClient::create_client()
-{
- auto paired_transports = TRY(IPC::Transport::create_paired());
- auto handle = move(paired_transports.remote_handle);
-
- // The static connection map owns this connection until its peer disconnects.
- auto client = adopt_ref(*new ConnectionFromClient(move(paired_transports.local), m_compiler, Role::Renderer));
-
- return handle;
-}
-
-Messages::WasmCompilerServer::ConnectNewClientsResponse ConnectionFromClient::connect_new_clients(size_t count)
-{
- if (m_role != Role::Controller)
- return Vector<IPC::TransportHandle> {};
-
- Vector<IPC::TransportHandle> handles;
- handles.ensure_capacity(count);
-
- for (size_t i = 0; i < count; ++i) {
- auto handle = create_client();
- if (handle.is_error()) {
- dbgln("Failed to connect a WebAssembly compiler client: {}", handle.error());
- return Vector<IPC::TransportHandle> {};
- }
- handles.unchecked_append(handle.release_value());
- }
-
- return handles;
-}
-
-void ConnectionFromClient::compile(Core::AnonymousBuffer input, u64 request_id)
-{
- if (m_role != Role::Renderer) {
- async_did_compile(request_id, {});
- return;
- }
-
- m_compiler.compile(*this, request_id, input);
-}
-
-}
diff --git a/Services/WasmCompiler/ConnectionFromClient.h b/Services/WasmCompiler/ConnectionFromClient.h
deleted file mode 100644
index 1faa69ff8f6..00000000000
--- a/Services/WasmCompiler/ConnectionFromClient.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibCore/AnonymousBuffer.h>
-#include <LibIPC/ConnectionFromClient.h>
-#include <LibIPC/TransportHandle.h>
-#include <WasmCompiler/Forward.h>
-#include <WasmCompiler/WasmCompilerClientEndpoint.h>
-#include <WasmCompiler/WasmCompilerServerEndpoint.h>
-
-namespace WasmCompiler {
-
-class ConnectionFromClient final
- : public IPC::ConnectionFromClient<WasmCompilerClientEndpoint, WasmCompilerServerEndpoint> {
- C_OBJECT(ConnectionFromClient);
-
-public:
- enum class Role {
- Controller,
- Renderer,
- };
-
- ConnectionFromClient(NonnullOwnPtr<IPC::Transport>, Compiler&, Role);
-
-private:
- virtual void die() override;
- virtual Messages::WasmCompilerServer::ConnectNewClientsResponse connect_new_clients(size_t count) override;
- virtual void compile(Core::AnonymousBuffer, u64 request_id) override;
-
- ErrorOr<IPC::TransportHandle> create_client();
-
- Compiler& m_compiler;
- Role m_role { Role::Renderer };
-};
-
-}
diff --git a/Services/WasmCompiler/Forward.h b/Services/WasmCompiler/Forward.h
deleted file mode 100644
index b92e8acbd9f..00000000000
--- a/Services/WasmCompiler/Forward.h
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-namespace WasmCompiler {
-
-class Compiler;
-class ConnectionFromClient;
-
-}
diff --git a/Services/WasmCompiler/Sandbox.h b/Services/WasmCompiler/Sandbox.h
deleted file mode 100644
index b702828de19..00000000000
--- a/Services/WasmCompiler/Sandbox.h
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Error.h>
-#include <AK/StringView.h>
-
-namespace WasmCompiler {
-
-ErrorOr<void> apply_sandbox(StringView mach_server_name);
-
-}
diff --git a/Services/WasmCompiler/SandboxLinux.cpp b/Services/WasmCompiler/SandboxLinux.cpp
deleted file mode 100644
index 7eb98caeda9..00000000000
--- a/Services/WasmCompiler/SandboxLinux.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCore/System.h>
-#include <LibSandbox/Sandbox.h>
-#include <LibSandbox/Seccomp.h>
-#include <LibWasm/Types.h>
-#include <WasmCompiler/Sandbox.h>
-
-namespace WasmCompiler {
-
-ErrorOr<void> apply_sandbox(StringView)
-{
- TRY(Sandbox::install_no_new_privileges());
- TRY(Sandbox::configure_runtime());
-
- Vector<Sandbox::LandlockPath> paths;
- TRY(Sandbox::add_landlock_path_if_exists(paths, TRY(Core::System::current_executable_path()), Sandbox::LandlockPath::Access::ReadOnly));
- TRY(Sandbox::add_landlock_path_if_exists(paths, Wasm::cranelift_compiler_path(), Sandbox::LandlockPath::Access::ReadAndExecute));
-#if ARCH(X86_64)
- TRY(Sandbox::add_landlock_path_if_exists(paths, "/lib64/ld-linux-x86-64.so.2"sv, Sandbox::LandlockPath::Access::ReadAndExecute));
-#elif ARCH(AARCH64)
- TRY(Sandbox::add_landlock_path_if_exists(paths, "/lib/ld-linux-aarch64.so.1"sv, Sandbox::LandlockPath::Access::ReadAndExecute));
-#elif ARCH(RISCV64)
- TRY(Sandbox::add_landlock_path_if_exists(paths, "/lib/ld-linux-riscv64-lp64d.so.1"sv, Sandbox::LandlockPath::Access::ReadAndExecute));
-#endif
- TRY(Sandbox::add_landlock_path_if_exists(paths, "/lib"sv, Sandbox::LandlockPath::Access::ReadOnly));
- TRY(Sandbox::add_landlock_path_if_exists(paths, "/lib64"sv, Sandbox::LandlockPath::Access::ReadOnly));
- TRY(Sandbox::add_landlock_path_if_exists(paths, "/usr/lib"sv, Sandbox::LandlockPath::Access::ReadOnly));
- TRY(Sandbox::add_landlock_path_if_exists(paths, "/usr/local/lib"sv, Sandbox::LandlockPath::Access::ReadOnly));
- TRY(Sandbox::restrict_filesystem_with_landlock(paths.span()));
-
- Sandbox::SeccompPolicy policy;
- policy.allow_readonly_file_opens();
- policy.allow_filesystem_metadata_queries();
- policy.allow_file_descriptor_operations();
- policy.allow_process_creation();
- policy.allow_ipc();
- policy.allow_socket_pairs();
- policy.allow_common_runtime();
- policy.allow_executable_memory_mappings();
- TRY(policy.install());
-
- return {};
-}
-
-}
diff --git a/Services/WasmCompiler/SandboxMacOS.cpp b/Services/WasmCompiler/SandboxMacOS.cpp
deleted file mode 100644
index 8d807c11f15..00000000000
--- a/Services/WasmCompiler/SandboxMacOS.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ByteString.h>
-#include <LibSandbox/Sandbox.h>
-#include <LibWasm/Types.h>
-#include <WasmCompiler/Sandbox.h>
-#include <errno.h>
-#include <limits.h>
-#include <stdlib.h>
-
-namespace WasmCompiler {
-
-ErrorOr<void> apply_sandbox(StringView mach_server_name)
-{
- TRY(Sandbox::configure_runtime());
-
- auto const& compiler_path = Wasm::cranelift_compiler_path();
-
- Vector<Sandbox::SeatbeltPath> paths;
- TRY(Sandbox::add_seatbelt_path_if_exists(paths, compiler_path, Sandbox::SeatbeltPath::Access::ReadAndExecute));
-
- return Sandbox::apply_macos_sandbox({
- .paths = paths.span(),
- .executable_paths = { { compiler_path } },
- .mach_server_name = mach_server_name,
- });
-}
-
-}
diff --git a/Services/WasmCompiler/SandboxUnimplemented.cpp b/Services/WasmCompiler/SandboxUnimplemented.cpp
deleted file mode 100644
index 34a69330771..00000000000
--- a/Services/WasmCompiler/SandboxUnimplemented.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <WasmCompiler/Sandbox.h>
-
-namespace WasmCompiler {
-
-ErrorOr<void> apply_sandbox(StringView)
-{
- return {};
-}
-
-}
diff --git a/Services/WasmCompiler/WasmCompilerClient.ipc b/Services/WasmCompiler/WasmCompilerClient.ipc
deleted file mode 100644
index 2d7c369e346..00000000000
--- a/Services/WasmCompiler/WasmCompilerClient.ipc
+++ /dev/null
@@ -1,6 +0,0 @@
-#include <LibCore/AnonymousBuffer.h>
-
-endpoint WasmCompilerClient
-{
- did_compile(u64 request_id, Core::AnonymousBuffer output) =|
-}
diff --git a/Services/WasmCompiler/WasmCompilerServer.ipc b/Services/WasmCompiler/WasmCompilerServer.ipc
deleted file mode 100644
index 4bee2ae1999..00000000000
--- a/Services/WasmCompiler/WasmCompilerServer.ipc
+++ /dev/null
@@ -1,9 +0,0 @@
-#include <LibCore/AnonymousBuffer.h>
-#include <LibIPC/TransportHandle.h>
-
-endpoint WasmCompilerServer
-{
- connect_new_clients(size_t count) => (Vector<IPC::TransportHandle> handles)
-
- compile(Core::AnonymousBuffer input, u64 request_id) =|
-}
diff --git a/Services/WasmCompiler/main.cpp b/Services/WasmCompiler/main.cpp
deleted file mode 100644
index b9c0b339cb5..00000000000
--- a/Services/WasmCompiler/main.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCore/ArgsParser.h>
-#include <LibCore/CrashHandler.h>
-#include <LibCore/EventLoop.h>
-#include <LibCore/Platform/TaskRole.h>
-#include <LibCore/Platform/ThreadQoS.h>
-#include <LibCore/Process.h>
-#include <LibCore/StatsLog.h>
-#include <LibIPC/SingleServer.h>
-#include <LibMain/Main.h>
-#include <WasmCompiler/Compiler.h>
-#include <WasmCompiler/ConnectionFromClient.h>
-#include <WasmCompiler/Sandbox.h>
-
-ErrorOr<int> ladybird_main(Main::Arguments arguments)
-{
- AK::set_rich_debug_enabled(true);
-
- int crash_report_fd = -1;
- StringView stats_log_directory;
- Core::ArgsParser args_parser;
- args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");
- args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");
- StringView mach_server_name;
- bool wait_for_debugger = false;
- bool disable_sandbox = false;
-
- args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");
- args_parser.add_option(wait_for_debugger, "Wait for debugger", "wait-for-debugger");
- args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");
- args_parser.parse(arguments);
-
- auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "WasmCompiler"sv));
-
- if (crash_report_fd >= 0) {
- if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())
- warnln("Could not install crash report handler: {}", result.error());
- }
-
- if (wait_for_debugger)
- Core::Process::wait_for_debugger_and_break();
-
- if (auto result = Core::Platform::adopt_foreground_application_task_role(); result.is_error())
- warnln("Could not adopt the foreground application task role: {}", result.error());
- if (auto result = Core::Platform::set_current_thread_qos(Core::Platform::ThreadQoS::UserInitiated); result.is_error())
- warnln("Could not set main thread QoS: {}", result.error());
-
- auto& event_loop = Core::EventLoop::initialize_for_current_thread();
-
- if (!disable_sandbox)
- TRY(WasmCompiler::apply_sandbox(mach_server_name));
-
- WasmCompiler::Compiler compiler;
- auto client = TRY(IPC::take_over_accepted_client_from_system_server<WasmCompiler::ConnectionFromClient>(
- mach_server_name, compiler, WasmCompiler::ConnectionFromClient::Role::Controller));
-
- if (stats_log)
- stats_log->start_sampling();
-
- return event_loop.exec();
-}
diff --git a/Services/WebContent/CMakeLists.txt b/Services/WebContent/CMakeLists.txt
index 914ca29783f..024122ddac7 100644
--- a/Services/WebContent/CMakeLists.txt
+++ b/Services/WebContent/CMakeLists.txt
@@ -32,9 +32,6 @@ target_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${LADYBIRD
target_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${LADYBIRD_SOURCE_DIR}/Services/>)
target_link_libraries(webcontentservice PUBLIC LibCompositing LibCore LibCrypto LibDevTools LibFileSystem LibGfx LibHTTP LibIPC LibJS LibMain LibAudio LibMedia LibWasm LibWeb LibRequests LibImageDecoderClient LibMediaClient LibGC)
-if (ENABLE_CRANELIFT_JIT)
- target_link_libraries(webcontentservice PUBLIC LibWasmCompilerClient)
-endif()
target_link_libraries(webcontentservice PRIVATE OpenSSL::Crypto OpenSSL::SSL)
target_compile_options(webcontentservice PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,Clang,AppleClang>:-Wexit-time-destructors>)
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 1da8b1c7ffb..0f96a7d5354 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -32,7 +32,6 @@
#include <LibJS/Runtime/ConsoleObject.h>
#include <LibJS/Runtime/Date.h>
#include <LibUnicode/TimeZone.h>
-#include <LibWasm/Types.h>
#include <LibWeb/ARIA/RoleType.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/CSS/CustomPropertyData.h>
@@ -433,14 +432,6 @@ void ConnectionFromClient::connect_to_image_decoder(IPC::TransportHandle handle)
on_image_decoder_connection(handle);
}
-void ConnectionFromClient::connect_to_wasm_compiler([[maybe_unused]] IPC::TransportHandle handle)
-{
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- if (on_wasm_compiler_connection)
- on_wasm_compiler_connection(move(handle));
-#endif
-}
-
void ConnectionFromClient::connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle)
{
auto transport = MUST(handle.create_transport());
@@ -1089,11 +1080,6 @@ void ConnectionFromClient::debug_request(Web::PageId page_id, ByteString request
return;
}
- if (request == "dump-wasm-stats") {
- Wasm::dump_module_stats();
- return;
- }
-
if (request == "collect-garbage") {
// NOTE: We use deferred_invoke here to ensure that GC runs with as little on the stack as possible.
Core::deferred_invoke([] {
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index a2e91ca98d2..7cc19930dde 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -75,9 +75,6 @@ public:
// Asks the Browser to spawn this process's MediaServer if it has none, and to connect a client to it.
ErrorOr<NonnullOwnPtr<IPC::Transport>> request_media_server_transport();
ErrorOr<NonnullOwnPtr<IPC::Transport>> request_audio_server_transport();
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- Function<void(IPC::TransportHandle)> on_wasm_compiler_connection;
-#endif
// Null outside test mode: the UI process connects the test endpoint only when it runs tests.
TestConnection* test_connection();
@@ -115,7 +112,6 @@ private:
virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id) override;
virtual void connect_to_test_endpoint(IPC::TransportHandle handle) override;
virtual void connect_to_image_decoder(IPC::TransportHandle handle) override;
- virtual void connect_to_wasm_compiler(IPC::TransportHandle handle) override;
virtual void connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) override;
virtual void set_site_compatibility_data(JsonValue data) override;
virtual void compositor_process_reconnected() override;
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index 1d5353ba892..851e8b2d2ef 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -87,7 +87,6 @@ endpoint WebContentServer routed by Web::PageId page_id
connect_to_request_server(IPC::TransportHandle handle, int client_id) =|
connect_to_test_endpoint(IPC::TransportHandle handle) =|
connect_to_image_decoder(IPC::TransportHandle handle) =|
- connect_to_wasm_compiler(IPC::TransportHandle handle) =|
connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) =|
compositor_process_reconnected() =|
set_site_compatibility_data(JsonValue data) =|
diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cpp
index 2a49b3db558..ce8e0bb79cc 100644
--- a/Services/WebContent/main.cpp
+++ b/Services/WebContent/main.cpp
@@ -48,11 +48,6 @@
#include <WebContent/WebContentCompositorHost.h>
#include <WebContent/WebDriverConnection.h>
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-# include <LibWasm/Types.h>
-# include <LibWasmCompilerClient/State.h>
-#endif
-
#include <openssl/thread.h>
#include <LibIPC/SingleServer.h>
@@ -314,16 +309,6 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
return webcontent_client->request_audio_server_transport();
});
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- Wasm::set_cranelift_compile_callback([](Core::AnonymousBuffer const& buffer) {
- return WasmCompilerClient::compiler_state().compile(buffer);
- });
-
- webcontent_client->on_wasm_compiler_connection = [](auto handle) {
- WasmCompilerClient::compiler_state().replace_connection(move(handle));
- };
-#endif
-
if (stats_log) {
stats_log->start_sampling([&heap](JsonObject& values) {
heap.add_stats(values);
diff --git a/Services/WebWorker/CMakeLists.txt b/Services/WebWorker/CMakeLists.txt
index c2489da3ce6..fe84711d673 100644
--- a/Services/WebWorker/CMakeLists.txt
+++ b/Services/WebWorker/CMakeLists.txt
@@ -15,9 +15,6 @@ target_include_directories(webworkerservice PRIVATE ${LADYBIRD_SOURCE_DIR})
target_include_directories(webworkerservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)
target_link_libraries(webworkerservice PUBLIC LibCore LibFileSystem LibGfx LibHTTP LibIPC LibJS LibRequests LibCompositing LibWeb LibUnicode LibImageDecoderClient LibMain LibMediaClient LibURL LibGC)
-if (ENABLE_CRANELIFT_JIT)
- target_link_libraries(webworkerservice PUBLIC LibWasm LibWasmCompilerClient)
-endif()
target_link_libraries(webworkerservice PRIVATE OpenSSL::Crypto OpenSSL::SSL)
add_executable(WebWorker main.cpp)
diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cpp
index ec8a506c635..cf445e71bc0 100644
--- a/Services/WebWorker/ConnectionFromClient.cpp
+++ b/Services/WebWorker/ConnectionFromClient.cpp
@@ -52,14 +52,6 @@ ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_media_serve
return response->take_handle()->create_transport();
}
-void ConnectionFromClient::connect_to_wasm_compiler([[maybe_unused]] IPC::TransportHandle handle)
-{
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- if (on_wasm_compiler_connection)
- on_wasm_compiler_connection(move(handle));
-#endif
-}
-
void ConnectionFromClient::connect_to_compositor(IPC::TransportHandle handle)
{
auto transport = MUST(handle.create_transport());
diff --git a/Services/WebWorker/ConnectionFromClient.h b/Services/WebWorker/ConnectionFromClient.h
index 34f534d520d..56fa50e217c 100644
--- a/Services/WebWorker/ConnectionFromClient.h
+++ b/Services/WebWorker/ConnectionFromClient.h
@@ -47,9 +47,6 @@ public:
// Asks the Browser to spawn this process's MediaServer if it has none, and to connect a client to it.
ErrorOr<NonnullOwnPtr<IPC::Transport>> request_media_server_transport();
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- Function<void(IPC::TransportHandle)> on_wasm_compiler_connection;
-#endif
private:
ConnectionFromClient(NonnullOwnPtr<IPC::Transport>, bool enable_test_mode);
@@ -60,7 +57,6 @@ private:
virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id) override;
virtual void simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id) override;
virtual void connect_to_image_decoder(IPC::TransportHandle handle) override;
- virtual void connect_to_wasm_compiler(IPC::TransportHandle handle) override;
virtual void connect_to_compositor(IPC::TransportHandle handle) override;
virtual void set_site_compatibility_data(JsonValue data) override;
virtual void set_user_agent(String user_agent) override;
diff --git a/Services/WebWorker/WebWorkerServer.ipc b/Services/WebWorker/WebWorkerServer.ipc
index 356a64061aa..6e07427f9b6 100644
--- a/Services/WebWorker/WebWorkerServer.ipc
+++ b/Services/WebWorker/WebWorkerServer.ipc
@@ -16,7 +16,6 @@ endpoint WebWorkerServer {
connect_to_request_server(IPC::TransportHandle handle, int client_id) =|
simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id) => ()
connect_to_image_decoder(IPC::TransportHandle handle) =|
- connect_to_wasm_compiler(IPC::TransportHandle handle) =|
connect_to_compositor(IPC::TransportHandle handle) =|
set_site_compatibility_data(JsonValue data) =|
set_user_agent(String user_agent) =|
diff --git a/Services/WebWorker/main.cpp b/Services/WebWorker/main.cpp
index e3b4142996a..86df525081e 100644
--- a/Services/WebWorker/main.cpp
+++ b/Services/WebWorker/main.cpp
@@ -34,11 +34,6 @@
#include <Services/RendererSandbox.h>
#include <WebWorker/ConnectionFromClient.h>
-#if defined(HAVE_WASM_COMPILER_SERVICE)
-# include <LibWasm/Types.h>
-# include <LibWasmCompilerClient/State.h>
-#endif
-
#include <openssl/thread.h>
static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id);
@@ -158,16 +153,6 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
return client->request_media_server_transport();
});
-#if defined(HAVE_WASM_COMPILER_SERVICE)
- Wasm::set_cranelift_compile_callback([](Core::AnonymousBuffer const& buffer) {
- return WasmCompilerClient::compiler_state().compile(buffer);
- });
-
- client->on_wasm_compiler_connection = [](auto handle) {
- WasmCompilerClient::compiler_state().replace_connection(move(handle));
- };
-#endif
-
if (stats_log)
stats_log->start_sampling([&heap](JsonObject& values) { heap.add_stats(values); });
diff --git a/Tests/LibSandbox/TestHelperSandboxes.cpp b/Tests/LibSandbox/TestHelperSandboxes.cpp
index fb36344b421..7317737fd1a 100644
--- a/Tests/LibSandbox/TestHelperSandboxes.cpp
+++ b/Tests/LibSandbox/TestHelperSandboxes.cpp
@@ -193,7 +193,7 @@ TEST_CASE(helpers_run_with_the_hardened_runtime)
{
// With the hardened runtime, the kernel refuses to run code from memory that was writable, unless the process may
// map JIT memory. Only the renderers run code that they compile at runtime.
- for (auto name : { "AudioServer"sv, "Compositor"sv, "ImageDecoder"sv, "MediaServer"sv, "ProcessReaper"sv, "RequestServer"sv, "WasmCompiler"sv, "WebContent"sv, "WebWorker"sv }) {
+ for (auto name : { "AudioServer"sv, "Compositor"sv, "ImageDecoder"sv, "MediaServer"sv, "ProcessReaper"sv, "RequestServer"sv, "WebContent"sv, "WebWorker"sv }) {
auto signature = signature_of_helper(name);
if (!signature.has_value()) {
warnln("Skipping {}, which was not built", name);
diff --git a/Tests/LibWasm/CMakeLists.txt b/Tests/LibWasm/CMakeLists.txt
index 62795aed71e..9099050d121 100644
--- a/Tests/LibWasm/CMakeLists.txt
+++ b/Tests/LibWasm/CMakeLists.txt
@@ -1,8 +1,5 @@
-ladybird_test(TestWasmMemory.cpp LibWasm LIBS LibGC LibWasm)
-ladybird_test(TestWasmExecution.cpp LibWasm LIBS LibGC LibWasm)
-
add_executable(test-wasm test-wasm.cpp)
-target_link_libraries(test-wasm AK LibCore LibFileSystem JavaScriptTestRunnerMain LibTest LibWasmRuntime LibJSStandalone LibCrypto LibGC)
+target_link_libraries(test-wasm AK LibCore LibFileSystem JavaScriptTestRunnerMain LibTest LibWasm LibJSStandalone LibCrypto LibGC)
set(wasm_test_root "${LADYBIRD_SOURCE_DIR}")
if (INCLUDE_WASM_SPEC_TESTS)
set(wasm_test_root "${CMAKE_BINARY_DIR}")
diff --git a/Tests/LibWasm/Fixtures/label-stack-cleanup.wat b/Tests/LibWasm/Fixtures/label-stack-cleanup.wat
index f694ad50261..43d0e2a933a 100644
--- a/Tests/LibWasm/Fixtures/label-stack-cleanup.wat
+++ b/Tests/LibWasm/Fixtures/label-stack-cleanup.wat
@@ -1,8 +1,8 @@
(module
(import "test" "label_stack_size" (func $label_stack_size (result i32)))
- ;; A reference local keeps this function in the direct-threaded interpreter
- ;; when its caller has been compiled by Cranelift.
+ ;; Branches out of an if; the caller then asks the host how deep its label
+ ;; stack is.
(func $callee (local externref)
(if (i32.const 1)
(then (br 0))
diff --git a/Tests/LibWasm/TestWasmExecution.cpp b/Tests/LibWasm/TestWasmExecution.cpp
deleted file mode 100644
index ff59d3ce747..00000000000
--- a/Tests/LibWasm/TestWasmExecution.cpp
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Hex.h>
-#include <AK/LEB128.h>
-#include <AK/MemoryStream.h>
-#include <LibCore/File.h>
-#include <LibTest/TestCase.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/AbstractMachine/Configuration.h>
-#include <LibWasm/AbstractMachine/Validator.h>
-#include <LibWasm/Constants.h>
-
-TEST_CASE(element_segments_require_reference_types)
-{
- auto bytes = MUST(decode_hex("0061736d01000000040401700001090801060041000b7f00"sv));
- FixedMemoryStream stream { bytes.bytes() };
- auto module = MUST(Wasm::Module::parse(stream));
-
- Wasm::AbstractMachine machine;
- EXPECT(machine.validate(*module, {}, Wasm::CompileToNative::No).is_error());
-}
-
-TEST_CASE(function_import_requires_function_type)
-{
- auto bytes = MUST(decode_hex("0061736d010000000106025f00600000020701016d01660000"sv));
- FixedMemoryStream stream { bytes.bytes() };
- auto module = MUST(Wasm::Module::parse(stream));
-
- Wasm::AbstractMachine machine;
- EXPECT(machine.validate(*module, {}, Wasm::CompileToNative::No).is_error());
-}
-
-TEST_CASE(interpreter_preserves_large_alias_chain)
-{
- constexpr i32 chain_length = 4096;
- auto bytes = MUST(decode_hex("0061736d0100000001060160017f017f030201000707010372756e0000"sv));
- auto body = MUST(decode_hex("002000"sv));
- for (i32 i = 0; i < chain_length; ++i) {
- body.append(0x41); // i32.const 1
- body.append(1);
- body.append(0x6a); // i32.add
- }
- body.append(0x0b);
-
- ByteBuffer code;
- code.append(1);
- LEB128<u32>::append_to(code, static_cast<u32>(body.size()));
- code.append(body.bytes());
- bytes.append(10);
- LEB128<u32>::append_to(bytes, static_cast<u32>(code.size()));
- bytes.append(code.bytes());
-
- FixedMemoryStream stream { bytes.bytes() };
- auto module = MUST(Wasm::Module::parse(stream));
- Wasm::AbstractMachine machine;
- MUST(machine.validate(*module, {}, Wasm::CompileToNative::No));
- auto instance = MUST(machine.instantiate(*module, {}));
- auto run = instance->exports()[0].value().get<Wasm::FunctionAddress>();
- EXPECT(!module->has_attempted_cranelift_compilation());
-
- for (auto input : { 41, -chain_length }) {
- auto result = machine.invoke(run, { Wasm::Value(static_cast<i32>(input)) });
- EXPECT(!result.is_trap());
- EXPECT_EQ(result.values().size(), 1u);
- EXPECT_EQ(result.values()[0].to<i32>(), input + chain_length);
- }
-}
-
-TEST_CASE(compiled_to_interpreter_call_restores_label_stack)
-{
- auto file = MUST(Core::File::open("Fixtures/label-stack-cleanup.wasm"sv, Core::File::OpenMode::Read));
- auto bytes = MUST(file->read_until_eof());
- FixedMemoryStream stream { bytes.bytes() };
- auto module = MUST(Wasm::Module::parse(stream));
-
- Wasm::AbstractMachine machine;
- Wasm::FunctionType label_stack_size_type { {}, { Wasm::ValueType(Wasm::ValueType::I32) } };
- auto label_stack_size = machine.store().allocate(Wasm::HostFunction {
- [](Wasm::Configuration& configuration, Span<Wasm::Value>) -> Wasm::Result {
- Vector<Wasm::Value> result;
- result.append(Wasm::Value(static_cast<i32>(configuration.label_stack().size())));
- return Wasm::Result { move(result) };
- },
- label_stack_size_type,
- "label_stack_size" });
- VERIFY(label_stack_size.has_value());
-
- Vector<Wasm::ExternValue> imports;
- imports.append(*label_stack_size);
- auto instance = MUST(machine.instantiate(*module, move(imports)));
-
- Optional<Wasm::FunctionAddress> run;
- for (auto const& export_ : instance->exports()) {
- if (export_.name() == "run"sv)
- run = export_.value().get<Wasm::FunctionAddress>();
- }
- VERIFY(run.has_value());
-
- auto result = machine.invoke(*run, {});
- EXPECT(!result.is_trap());
- EXPECT_EQ(result.values().size(), 1u);
- EXPECT_EQ(result.values()[0].to<i32>(), 1);
-}
-
-TEST_CASE(reentrant_invoke_uses_independent_execution_state)
-{
- auto file = MUST(Core::File::open("Fixtures/label-stack-cleanup.wasm"sv, Core::File::OpenMode::Read));
- auto bytes = MUST(file->read_until_eof());
- FixedMemoryStream stream { bytes.bytes() };
- auto module = MUST(Wasm::Module::parse(stream));
-
- Wasm::AbstractMachine machine;
- Optional<Wasm::FunctionAddress> run;
- bool should_reenter { true };
- Wasm::FunctionType label_stack_size_type { {}, { Wasm::ValueType(Wasm::ValueType::I32) } };
- auto label_stack_size = machine.store().allocate(Wasm::HostFunction {
- [&](Wasm::Configuration& configuration, Span<Wasm::Value>) -> Wasm::Result {
- if (should_reenter) {
- should_reenter = false;
- return machine.invoke(*run, {});
- }
-
- Vector<Wasm::Value> result;
- result.append(Wasm::Value(static_cast<i32>(configuration.label_stack().size())));
- return Wasm::Result { move(result) };
- },
- label_stack_size_type,
- "label_stack_size" });
- VERIFY(label_stack_size.has_value());
-
- Vector<Wasm::ExternValue> imports;
- imports.append(*label_stack_size);
- auto instance = MUST(machine.instantiate(*module, move(imports)));
-
- for (auto const& export_ : instance->exports()) {
- if (export_.name() == "run"sv)
- run = export_.value().get<Wasm::FunctionAddress>();
- }
- VERIFY(run.has_value());
-
- auto result = machine.invoke(*run, {});
- EXPECT(!result.is_trap());
- EXPECT_EQ(result.values().size(), 1u);
- EXPECT_EQ(result.values()[0].to<i32>(), 1);
-}
-
-TEST_CASE(reentrant_compiled_memory_fault_uses_innermost_recovery_context)
-{
- auto parse_fixture = [](StringView path) {
- auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
- auto bytes = MUST(file->read_until_eof());
- FixedMemoryStream stream { bytes.bytes() };
- return MUST(Wasm::Module::parse(stream));
- };
-
- Wasm::AbstractMachine machine;
-
- auto inner_module = parse_fixture("Fixtures/memory-guard-trap.wasm"sv);
- auto inner_instance = MUST(machine.instantiate(*inner_module, {}));
- Optional<Wasm::FunctionAddress> load_high;
- for (auto const& export_ : inner_instance->exports()) {
- if (export_.name() == "load_high"sv)
- load_high = export_.value().get<Wasm::FunctionAddress>();
- }
- VERIFY(load_high.has_value());
-
- Wasm::FunctionType host_type { {}, { Wasm::ValueType(Wasm::ValueType::I32) } };
- auto call_inner = machine.store().allocate(Wasm::HostFunction {
- [&](Wasm::Configuration&, Span<Wasm::Value>) -> Wasm::Result {
- return machine.invoke(*load_high, { Wasm::Value(static_cast<i32>(0)) });
- },
- host_type,
- "call_inner" });
- VERIFY(call_inner.has_value());
-
- auto outer_module = parse_fixture("Fixtures/label-stack-cleanup.wasm"sv);
- Vector<Wasm::ExternValue> imports;
- imports.append(*call_inner);
- auto outer_instance = MUST(machine.instantiate(*outer_module, move(imports)));
- Optional<Wasm::FunctionAddress> run;
- for (auto const& export_ : outer_instance->exports()) {
- if (export_.name() == "run"sv)
- run = export_.value().get<Wasm::FunctionAddress>();
- }
- VERIFY(run.has_value());
-
- auto result = machine.invoke(*run, {});
- EXPECT(result.is_trap());
- EXPECT_EQ(result.trap().format(), "Memory access out of bounds"sv);
-}
-
-TEST_CASE(compiled_indirect_call_preserves_arguments_and_result)
-{
- auto file = MUST(Core::File::open("Fixtures/indirect-call.wasm"sv, Core::File::OpenMode::Read));
- auto bytes = MUST(file->read_until_eof());
- FixedMemoryStream stream { bytes.bytes() };
- auto module = MUST(Wasm::Module::parse(stream));
-
- Wasm::AbstractMachine machine;
- auto instance = MUST(machine.instantiate(*module, {}));
-
- Optional<Wasm::FunctionAddress> run;
- for (auto const& export_ : instance->exports()) {
- if (export_.name() == "run"sv)
- run = export_.value().get<Wasm::FunctionAddress>();
- }
- VERIFY(run.has_value());
-
- auto result = machine.invoke(*run, { Wasm::Value(static_cast<i32>(41)) });
- EXPECT(!result.is_trap());
- EXPECT_EQ(result.values().size(), 1u);
- EXPECT_EQ(result.values()[0].to<i32>(), 42);
-}
-
-TEST_CASE(compiled_memory_access_traps_out_of_bounds)
-{
- auto file = MUST(Core::File::open("Fixtures/memory-guard-trap.wasm"sv, Core::File::OpenMode::Read));
- auto bytes = MUST(file->read_until_eof());
- FixedMemoryStream stream { bytes.bytes() };
- auto module = MUST(Wasm::Module::parse(stream));
-
- Wasm::AbstractMachine machine;
- auto instance = MUST(machine.instantiate(*module, {}));
-
- auto find_export = [&](StringView name) {
- Optional<Wasm::FunctionAddress> address;
- for (auto const& export_ : instance->exports()) {
- if (export_.name() == name)
- address = export_.value().get<Wasm::FunctionAddress>();
- }
- VERIFY(address.has_value());
- return *address;
- };
- auto load = find_export("load"sv);
- auto store = find_export("store"sv);
- auto load_high = find_export("load_high"sv);
-
- auto invoke = [&](Wasm::FunctionAddress address, Vector<Wasm::Value> arguments) {
- return machine.invoke(address, move(arguments));
- };
-
- // The memory starts at one page; accesses fully inside it should succeed.
- auto in_bounds = invoke(load, { Wasm::Value(static_cast<i32>(0)) });
- EXPECT(!in_bounds.is_trap());
- EXPECT_EQ(in_bounds.values()[0].to<i32>(), 0);
-
- auto store_in_bounds = invoke(store, { Wasm::Value(static_cast<i32>(Wasm::Constants::page_size - 4)), Wasm::Value(static_cast<i32>(0x1337)) });
- EXPECT(!store_in_bounds.is_trap());
- auto load_back = invoke(load, { Wasm::Value(static_cast<i32>(Wasm::Constants::page_size - 4)) });
- EXPECT(!load_back.is_trap());
- EXPECT_EQ(load_back.values()[0].to<i32>(), 0x1337);
-
- auto expect_oob_trap = [](Wasm::Result const& result) {
- EXPECT(result.is_trap());
- EXPECT_EQ(result.trap().format(), "Memory access out of bounds"sv);
- };
-
- // Loads and stores just-or-partially past the boundary should trap.
- expect_oob_trap(invoke(load, { Wasm::Value(static_cast<i32>(Wasm::Constants::page_size - 1)) }));
- expect_oob_trap(invoke(load, { Wasm::Value(static_cast<i32>(Wasm::Constants::page_size)) }));
- // A store just past the committed boundary must not write outside the memory either.
- expect_oob_trap(invoke(store, { Wasm::Value(static_cast<i32>(Wasm::Constants::page_size)), Wasm::Value(static_cast<i32>(0x42)) }));
-
- // base + offset can reach high into the guarded reservation; those accesses must trap too.
- expect_oob_trap(invoke(load_high, { Wasm::Value(static_cast<i32>(0)) }));
- expect_oob_trap(invoke(load_high, { Wasm::Value(static_cast<i32>(0xffffffff)) }));
-}
diff --git a/Tests/LibWasm/TestWasmMemory.cpp b/Tests/LibWasm/TestWasmMemory.cpp
deleted file mode 100644
index 61779f18ac8..00000000000
--- a/Tests/LibWasm/TestWasmMemory.cpp
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/PrimitiveStorage.h>
-#include <LibTest/TestCase.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-
-static size_t memory_capacity(Wasm::MemoryInstance const& memory)
-{
- return GC::PrimitiveStorage::the().capacity(memory.data().primitive_storage_handle());
-}
-
-TEST_CASE(wasm32_memory_reserves_full_guarded_span)
-{
- auto memory = MUST(Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I32, 1) }));
- auto* data = memory.data().data();
- auto handle = memory.data().primitive_storage_handle();
-
- EXPECT_EQ(memory.size(), Wasm::Constants::page_size);
- EXPECT_EQ(memory_capacity(memory), static_cast<size_t>(Wasm::Constants::wasm32_max_pages * Wasm::Constants::page_size));
-
- // Unchecked compiled accesses can reach base (u32) + offset (u32) past the memory's base;
- // that whole span must belong to this memory's reservation so an out-of-bounds access
- // faults instead of landing in a neighboring allocation.
- EXPECT(GC::PrimitiveStorage::the().contains(handle, data + Wasm::Constants::wasm32_guarded_reservation_size - 1));
- EXPECT(!GC::PrimitiveStorage::the().contains(handle, data + Wasm::Constants::wasm32_guarded_reservation_size));
-}
-
-TEST_CASE(wasm32_memory_without_max_grows_in_place)
-{
- auto memory = MUST(Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I32, 1) }));
- auto* data_before_grow = memory.data().data();
- auto capacity_before_grow = memory_capacity(memory);
-
- // Compiled code caches the memory base address, so growth may never move the storage; grow
- // well past the old geometric-reservation boundary and make sure everything stays put.
- EXPECT(memory.grow(static_cast<size_t>(Wasm::Constants::default_memory_reservation_size)));
-
- EXPECT_EQ(memory.size(), Wasm::Constants::default_memory_reservation_size + Wasm::Constants::page_size);
- EXPECT_EQ(memory_capacity(memory), capacity_before_grow);
- EXPECT_EQ(memory.data().data(), data_before_grow);
-}
-
-TEST_CASE(wasm32_memory_with_max_still_reserves_full_guarded_span)
-{
- auto memory = MUST(Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I32, 1, 3) }));
- auto* data = memory.data().data();
- auto handle = memory.data().primitive_storage_handle();
-
- EXPECT_EQ(memory.size(), Wasm::Constants::page_size);
- EXPECT_EQ(memory_capacity(memory), 3uz * Wasm::Constants::page_size);
- EXPECT(GC::PrimitiveStorage::the().contains(handle, data + Wasm::Constants::wasm32_guarded_reservation_size - 1));
- EXPECT(!GC::PrimitiveStorage::the().contains(handle, data + Wasm::Constants::wasm32_guarded_reservation_size));
-}
-
-TEST_CASE(wasm32_memory_reservations_do_not_overlap)
-{
- auto first = MUST(Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I32, 1) }));
- auto second = MUST(Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I32, 1) }));
-
- auto first_handle = first.data().primitive_storage_handle();
- auto second_handle = second.data().primitive_storage_handle();
-
- // Neither memory's base can lie anywhere within the other's guarded reservation.
- EXPECT(!GC::PrimitiveStorage::the().contains(first_handle, second.data().data()));
- EXPECT(!GC::PrimitiveStorage::the().contains(second_handle, first.data().data()));
-
- auto first_base = bit_cast<FlatPtr>(first.data().data());
- auto second_base = bit_cast<FlatPtr>(second.data().data());
- auto distance = first_base < second_base ? second_base - first_base : first_base - second_base;
- EXPECT(distance >= Wasm::Constants::wasm32_guarded_reservation_size);
-}
-
-TEST_CASE(memory64_memory_without_max_can_grow)
-{
- auto memory = MUST(Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I64, 0) }));
-
- EXPECT_EQ(memory.size(), 0u);
-
- EXPECT(memory.grow(Wasm::Constants::page_size));
- EXPECT_EQ(memory.size(), Wasm::Constants::page_size);
-
- EXPECT(memory.grow(4uz * Wasm::Constants::page_size));
- EXPECT_EQ(memory.size(), 5uz * Wasm::Constants::page_size);
-}
-
-TEST_CASE(memory64_memory_without_max_cannot_grow_past_current_compiled_address_width)
-{
- static_assert(Wasm::Constants::wasm64_max_pages == Wasm::Constants::wasm32_max_pages);
- constexpr auto maximum_supported_size = static_cast<size_t>(Wasm::Constants::wasm64_max_pages * Wasm::Constants::page_size);
-
- auto memory = MUST(Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I64, 0) }));
-
- EXPECT(!memory.grow(maximum_supported_size + Wasm::Constants::page_size));
- EXPECT_EQ(memory.size(), 0u);
-}
-
-TEST_CASE(memory64_memory_initial_size_cannot_exceed_current_compiled_address_width)
-{
- auto memory = Wasm::MemoryInstance::create(Wasm::MemoryType { Wasm::Limits(Wasm::AddressType::I64, Wasm::Constants::wasm64_max_pages + 1) });
- EXPECT(memory.is_error());
-}
-
-TEST_CASE(memory_buffer_failed_resize_and_reserve_preserves_backing_storage)
-{
- Wasm::MemoryBuffer buffer;
- MUST(buffer.try_resize(Wasm::Constants::page_size));
- auto handle = buffer.primitive_storage_handle();
- auto offset = GC::PrimitiveStorage::the().offset(handle);
- auto capacity = buffer.capacity();
- auto* data = buffer.data();
- buffer[0] = 0x42;
- buffer[Wasm::Constants::page_size - 1] = 0x24;
-
- auto result = buffer.try_resize(2uz * Wasm::Constants::page_size, GC::PrimitiveStorage::default_cage_size + Wasm::Constants::page_size);
-
- EXPECT(result.is_error());
- EXPECT_EQ(buffer.primitive_storage_handle().index, handle.index);
- EXPECT_EQ(buffer.primitive_storage_handle().generation, handle.generation);
- EXPECT_EQ(GC::PrimitiveStorage::the().offset(handle), offset);
- EXPECT_EQ(buffer.size(), Wasm::Constants::page_size);
- EXPECT_EQ(buffer.capacity(), capacity);
- EXPECT_EQ(buffer.data(), data);
- EXPECT_EQ(buffer[0], 0x42);
- EXPECT_EQ(buffer[Wasm::Constants::page_size - 1], 0x24);
-}
-
-TEST_CASE(memory_buffer_copy_fill_and_move_helpers)
-{
- Wasm::MemoryBuffer source;
- Wasm::MemoryBuffer destination;
- MUST(source.try_resize(32));
- MUST(destination.try_resize(32));
-
- for (u8 i = 0; i < 16; ++i)
- source[i] = i;
-
- destination.fill(0, 0xaa, 32);
- for (size_t i = 0; i < 32; ++i)
- EXPECT_EQ(destination[i], 0xaa);
-
- destination.copy_from(source, 4, 8, 8);
- for (size_t i = 0; i < 8; ++i)
- EXPECT_EQ(destination[8 + i], source[4 + i]);
-
- destination.move_data(10, 8, 8);
- EXPECT_EQ(destination[10], 4);
- EXPECT_EQ(destination[11], 5);
- EXPECT_EQ(destination[16], 10);
- EXPECT_EQ(destination[17], 11);
-
- u8 replacement[] = { 1, 2, 3, 4 };
- destination.overwrite(28, replacement, sizeof(replacement));
- EXPECT_EQ(destination[28], 1);
- EXPECT_EQ(destination[29], 2);
- EXPECT_EQ(destination[30], 3);
- EXPECT_EQ(destination[31], 4);
-}
diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cpp
index 140fc8a50e5..5068aba50ad 100644
--- a/Tests/LibWasm/test-wasm.cpp
+++ b/Tests/LibWasm/test-wasm.cpp
@@ -23,7 +23,7 @@
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibTest/JavaScriptTestHost.h>
-#include <LibWasm/Runtime/Runtime.h>
+#include <LibWasm/Runtime.h>
#include <string.h>
#include <sys/resource.h>
@@ -289,18 +289,6 @@ TESTJS_GLOBAL_FUNCTION(validate_webassembly_module, validateWebAssemblyModule)
return JS::js_undefined();
}
-// FIXME: These ask about the Cranelift JIT, which is gone; the tests that use them return early when nothing is
-// eligible.
-TESTJS_GLOBAL_FUNCTION(is_cranelift_compiled, isCraneliftCompiled)
-{
- return JS::Value(false);
-}
-
-TESTJS_GLOBAL_FUNCTION(is_cranelift_eligible, isCraneliftEligible)
-{
- return JS::Value(false);
-}
-
// The most memory the process has had resident, in bytes.
TESTJS_GLOBAL_FUNCTION(peak_resident_memory_size, peakResidentMemorySize)
{
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index d38dca32406..da518088c17 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -71,7 +71,7 @@ target_link_libraries(TestFetchURL PRIVATE LibURL)
target_link_libraries(TestImageData PRIVATE LibGC LibJS)
target_link_libraries(TestWebIDLBuffers PRIVATE LibGC LibJS)
target_link_libraries(TestStructuredSerializeCorpus PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
-target_link_libraries(TestStructuredSerializeDurability PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC LibWasmRuntime)
+target_link_libraries(TestStructuredSerializeDurability PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC LibWasm)
target_link_libraries(TestStructuredSerializeFormat PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
target_link_libraries(TestStructuredSerializeHardening PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
target_link_libraries(TestStructuredSerializeSharedArrayBuffer PRIVATE LibGC LibJS LibIPC)
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index 64ec79a0ee3..c7ec1b3aeeb 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -295,9 +295,6 @@ if (BUILD_TESTING AND NOT WIN32)
)
set_tests_properties(TestWebDriverBrowserCrashRecovery PROPERTIES TIMEOUT 120)
set(crash_report_helpers WebWorker RequestServer ImageDecoder Compositor)
- if (ENABLE_CRANELIFT_JIT)
- list(APPEND crash_report_helpers WasmCompiler)
- endif()
foreach(helper IN LISTS crash_report_helpers)
add_test(
NAME Test${helper}CrashReport
diff --git a/Tests/LibWebView/TestCrashReport.cpp b/Tests/LibWebView/TestCrashReport.cpp
index 312ae13f599..9c2679972bf 100644
--- a/Tests/LibWebView/TestCrashReport.cpp
+++ b/Tests/LibWebView/TestCrashReport.cpp
@@ -323,12 +323,12 @@ TEST_CASE(helper_process_names)
{
cleanup();
ScopeGuard guard = cleanup;
- for (auto type : { WebView::ProcessType::WebContent, WebView::ProcessType::WebWorker, WebView::ProcessType::RequestServer, WebView::ProcessType::ImageDecoder, WebView::ProcessType::MediaServer, WebView::ProcessType::Compositor, WebView::ProcessType::WasmCompiler }) {
+ for (auto type : { WebView::ProcessType::WebContent, WebView::ProcessType::WebWorker, WebView::ProcessType::RequestServer, WebView::ProcessType::ImageDecoder, WebView::ProcessType::MediaServer, WebView::ProcessType::Compositor }) {
auto report = MUST(WebView::CrashReport::create(type));
MUST(report->save(SIGSEGV, test_directory()));
}
auto paths = report_paths();
- EXPECT_EQ(paths.size(), 7u);
+ EXPECT_EQ(paths.size(), 6u);
for (auto const& path : paths) {
auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
auto contents = MUST(file->read_until_eof());
diff --git a/Tests/LibWebView/TestHelperProcessEnvironment.cpp b/Tests/LibWebView/TestHelperProcessEnvironment.cpp
index 72bd538b9b1..d0e7b2ae36c 100644
--- a/Tests/LibWebView/TestHelperProcessEnvironment.cpp
+++ b/Tests/LibWebView/TestHelperProcessEnvironment.cpp
@@ -41,7 +41,7 @@ TEST_CASE(helper_environment_keeps_loader_and_session_variables_out)
MUST(Core::Environment::set("OPENSSL_CONF"sv, "/tmp/openssl.cnf"sv, Core::Environment::Overwrite::Yes));
MUST(Core::Environment::set("XDG_RUNTIME_DIR"sv, "/run/user/1000"sv, Core::Environment::Overwrite::Yes));
- for (auto type : { WebView::ProcessType::Compositor, WebView::ProcessType::WebContent, WebView::ProcessType::WebWorker, WebView::ProcessType::RequestServer, WebView::ProcessType::ImageDecoder, WebView::ProcessType::MediaServer, WebView::ProcessType::AudioServer, WebView::ProcessType::WasmCompiler }) {
+ for (auto type : { WebView::ProcessType::Compositor, WebView::ProcessType::WebContent, WebView::ProcessType::WebWorker, WebView::ProcessType::RequestServer, WebView::ProcessType::ImageDecoder, WebView::ProcessType::MediaServer, WebView::ProcessType::AudioServer }) {
auto environment = WebView::Process::helper_process_environment(type);
EXPECT(!environment.contains_slow("LD_PRELOAD=/tmp/evil.so"sv));
EXPECT(!environment.contains_slow("LD_LIBRARY_PATH=/tmp"sv));
diff --git a/Tests/LibWebView/test-webdriver-crash-report.py b/Tests/LibWebView/test-webdriver-crash-report.py
index 48f5e84d7c5..0742d08f085 100755
--- a/Tests/LibWebView/test-webdriver-crash-report.py
+++ b/Tests/LibWebView/test-webdriver-crash-report.py
@@ -149,7 +149,7 @@ if __name__ == "__main__":
parser.add_argument(
"--process",
default="WebContent",
- choices=["WebContent", "WebWorker", "RequestServer", "ImageDecoder", "Compositor", "WasmCompiler"],
+ choices=["WebContent", "WebWorker", "RequestServer", "ImageDecoder", "Compositor"],
)
args = parser.parse_args()
run_test(args.webdriver_binary, args.process)
diff --git a/Tests/RequestServer/TestCookieResponses.cpp b/Tests/RequestServer/TestCookieResponses.cpp
index c67dc8cfd17..119426c92c3 100644
--- a/Tests/RequestServer/TestCookieResponses.cpp
+++ b/Tests/RequestServer/TestCookieResponses.cpp
@@ -465,7 +465,7 @@ TEST_CASE(unknown_cache_associated_data_kind_is_rejected)
TestServer server;
TestConnection connection { server };
- connection.store_cache_associated_data(HTTP::CacheEntryAssociatedData::WebAssemblyCompiledCode);
+ connection.store_cache_associated_data(HTTP::CacheEntryAssociatedData::JavaScriptBytecode);
EXPECT(connection.is_open());
}
diff --git a/Tests/RequestServer/TestSiteBinding.cpp b/Tests/RequestServer/TestSiteBinding.cpp
index 1a6a347ef43..1849e806c44 100644
--- a/Tests/RequestServer/TestSiteBinding.cpp
+++ b/Tests/RequestServer/TestSiteBinding.cpp
@@ -83,19 +83,20 @@ struct TestServer {
VERIFY(response);
}
- // Asks RequestServer to create a cache entry in the partition of the key, and returns whether the entry exists.
- bool create_synthetic_cache_entry(HTTP::NetworkIsolationKey const& network_isolation_key)
+ // Puts associated data in the cache partition of the key, and returns whether RequestServer reads it back.
+ bool can_use_cache_partition(HTTP::NetworkIsolationKey const& network_isolation_key)
{
auto url = URL::Parser::basic_parse("https://cdn.example/library.js"sv).release_value();
- auto message = make<Messages::RequestServer::CreateSyntheticCacheEntry>(network_isolation_key, url, ByteString { "GET" });
- VERIFY(MUST(static_cast<RequestServerEndpoint::Stub&>(*connection).handle(move(message))));
-
- // NB: Associated data can be stored only for an entry that exists.
+ auto partition = *network_isolation_key.disk_cache_partition();
+ (void)MUST(disk_cache->create_synthetic_entry(partition, url, "GET"sv));
auto request_headers = HTTP::HeaderList::create();
- auto stored = MUST(disk_cache->store_associated_data(*network_isolation_key.disk_cache_partition(), url, "GET"sv, *request_headers, 0, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, "data"sv.bytes()));
- if (stored.has_value())
- (void)Core::System::close(stored->fd);
- return stored.has_value();
+ auto stored = MUST(disk_cache->store_associated_data(partition, url, "GET"sv, *request_headers, 0, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, "data"sv.bytes()));
+ VERIFY(stored.has_value());
+ (void)Core::System::close(stored->fd);
+
+ auto& stub = static_cast<RequestServerEndpoint::Stub&>(*connection);
+ auto response = stub.retrieve_cache_associated_data(network_isolation_key, url, ByteString { "GET" }, {}, 0u, HTTP::CacheEntryAssociatedData::JavaScriptBytecode);
+ return response.data().has_value();
}
void start_request(u64 request_id, StringView url, HTTP::NetworkIsolationKey const& network_isolation_key)
@@ -144,18 +145,18 @@ TEST_CASE(bound_client_uses_only_the_cache_partitions_of_its_sites)
{
TestServer server;
- EXPECT(!server.create_synthetic_cache_entry(key("https://a.example"sv, "https://a.example"sv)));
+ EXPECT(!server.can_use_cache_partition(key("https://a.example"sv, "https://a.example"sv)));
server.bind_to_site("https://a.example"sv, "https://a.example"sv);
- EXPECT(server.create_synthetic_cache_entry(key("https://a.example"sv, "https://a.example"sv)));
+ EXPECT(server.can_use_cache_partition(key("https://a.example"sv, "https://a.example"sv)));
// Neither another top-level site nor another frame site under the bound one is reachable.
- EXPECT(!server.create_synthetic_cache_entry(key("https://b.example"sv, "https://b.example"sv)));
- EXPECT(!server.create_synthetic_cache_entry(key("https://b.example"sv, "https://a.example"sv)));
- EXPECT(!server.create_synthetic_cache_entry(key("https://a.example"sv, "https://b.example"sv)));
+ EXPECT(!server.can_use_cache_partition(key("https://b.example"sv, "https://b.example"sv)));
+ EXPECT(!server.can_use_cache_partition(key("https://b.example"sv, "https://a.example"sv)));
+ EXPECT(!server.can_use_cache_partition(key("https://a.example"sv, "https://b.example"sv)));
server.bind_to_site("https://a.example"sv, "https://b.example"sv);
- EXPECT(server.create_synthetic_cache_entry(key("https://a.example"sv, "https://b.example"sv)));
+ EXPECT(server.can_use_cache_partition(key("https://a.example"sv, "https://b.example"sv)));
}
TEST_CASE(bound_client_requests_only_for_its_sites)
diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt
index e422f3ff676..8fcce1e2a4e 100644
--- a/Utilities/CMakeLists.txt
+++ b/Utilities/CMakeLists.txt
@@ -2,7 +2,7 @@ ladybird_utility(js SOURCES js.cpp LIBS LibJSStandalone LibMain)
if (NOT WIN32 AND NOT ANDROID)
target_link_libraries(js PRIVATE PkgConfig::LIBEDIT)
endif()
-ladybird_utility(wasm SOURCES wasm.cpp LIBS LibFileSystem LibWasmRuntime LibMain LibJSStandalone LibCrypto LibGC)
+ladybird_utility(wasm SOURCES wasm.cpp LIBS LibFileSystem LibWasm LibMain LibJSStandalone LibCrypto LibGC)
ladybird_utility(xml SOURCES xml.cpp LIBS LibFileSystem LibMain LibXML LibURL)
ladybird_utility(dns SOURCES dns.cpp LIBS LibDNS LibMain LibTLS LibCrypto)
diff --git a/Utilities/wasm.cpp b/Utilities/wasm.cpp
index d9a2cef54f1..b494fddba44 100644
--- a/Utilities/wasm.cpp
+++ b/Utilities/wasm.cpp
@@ -29,7 +29,7 @@
#include <LibJS/Runtime/VM.h>
#include <LibJS/Script.h>
#include <LibMain/Main.h>
-#include <LibWasm/Runtime/Runtime.h>
+#include <LibWasm/Runtime.h>
#include <math.h>
using Wasm::Runtime::Entity;