/*
 * Copyright (C) 2016-2025 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WasmOMGIRGenerator.h"

#if ENABLE(WEBASSEMBLY_OMGJIT)

#include "AirCode.h"
#include "AllowMacroScratchRegisterUsageIf.h"
#include "B3AbstractHeapRepository.h"
#include "B3BasicBlockInlines.h"
#include "B3CCallValue.h"
#include "B3Const128Value.h"
#include "B3ConstPtrValue.h"
#include "B3EstimateStaticExecutionCounts.h"
#include "B3FixSSA.h"
#include "B3Generate.h"
#include "B3InsertionSet.h"
#include "B3SIMDValue.h"
#include "B3StackmapGenerationParams.h"
#include "B3SwitchValue.h"
#include "B3UpsilonValue.h"
#include "B3Validate.h"
#include "B3ValueInlines.h"
#include "B3ValueKey.h"
#include "B3Variable.h"
#include "B3VariableValue.h"
#include "B3WasmAddressValue.h"
#include "B3WasmArrayGetValue.h"
#include "B3WasmArrayLengthValue.h"
#include "B3WasmArrayNewValue.h"
#include "B3WasmArraySetValue.h"
#include "B3WasmBoundsCheckValue.h"
#include "B3WasmRefTypeCheckValue.h"
#include "B3WasmStructGetValue.h"
#include "B3WasmStructNewValue.h"
#include "B3WasmStructSetValue.h"
#include "CompilerTimingScope.h"
#include "FunctionAllowlist.h"
#include "JSCJSValueInlines.h"
#include "JSWebAssemblyArrayInlines.h"
#include "JSWebAssemblyInstance.h"
#include "JSWebAssemblyStruct.h"
#include "ProbeContext.h"
#include "ProfilerSupport.h"
#include "SIMDShuffle.h"
#include "ScratchRegisterAllocator.h"
#include "WasmBaselineData.h"
#include "WasmBranchHints.h"
#include "WasmCallProfile.h"
#include "WasmCallingConvention.h"
#include "WasmContext.h"
#include "WasmExceptionType.h"
#include "WasmFaultSignalHandler.h"
#include "WasmFunctionParser.h"
#include "WasmIRGeneratorHelpers.h"
#include "WasmInliningDecision.h"
#include "WasmMemory.h"
#include "WasmMergedProfile.h"
#include "WasmOSREntryData.h"
#include "WasmOpcodeOrigin.h"
#include "WasmOperations.h"
#include "WasmSIMDOpcodes.h"
#include "WasmThunks.h"
#include "WasmTypeDefinitionInlines.h"
#include "WebAssemblyFunctionBase.h"
#include <limits>
#include <wtf/CheckedArithmetic.h>
#include <wtf/FastMalloc.h>
#include <wtf/RecursableLambda.h>
#include <wtf/StdLibExtras.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/MakeString.h>

#if !ENABLE(WEBASSEMBLY)
#error ENABLE(WEBASSEMBLY_OMGJIT) is enabled, but ENABLE(WEBASSEMBLY) is not.
#endif

WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN

void dumpProcedure(void* ptr)
{
    JSC::B3::Procedure* proc = static_cast<JSC::B3::Procedure*>(ptr);
    proc->dump(WTF::dataFile());
}

namespace JSC { namespace Wasm {

using namespace B3;

namespace {
namespace WasmOMGIRGeneratorInternal {
static constexpr bool verbose = false;
static constexpr bool verboseInlining = false;
static constexpr bool traceExecution = false;
static constexpr bool traceStackValues = false;
static constexpr bool verboseTailCalls = false;
#if ASSERT_ENABLED
static constexpr bool traceExecutionIncludesConstructionSite = false;
#endif

}
}

#define TRACE_VALUE(...) do { if constexpr (WasmOMGIRGeneratorInternal::traceExecution) { traceValue(__VA_ARGS__); } } while (0)

#define TRACE_CF(...) do { if constexpr (WasmOMGIRGeneratorInternal::traceExecution) { traceCF(__VA_ARGS__); } } while (0)

// ExpressionType for OMGIRGenerator. Typically, will be a B3::Value* but when encountering
// Try/TryTable or loop with OSR, the wasm expression stack will be "materialized" to B3::Variables
// so that the catch or loop OSR entrypoints have a location to restore into without needing
// to determine Phi placement during this single pass parsing. Phi placement for these variables
// will be handled by fixSSA.
// FIXME: Ideally this would have WTF_MAKE_NONCOPYABLE(OMGExpression), rdar://166822445
class OMGExpression {
    static constexpr uintptr_t isMaterializedMask = 0x1;
public:
    OMGExpression() = default;

    OMGExpression(Value* value)
        : m_storage(reinterpret_cast<uintptr_t>(value))
    {
        ASSERT(!isEmpty() && !isMaterialized() && b3Value() == value);
    }

    bool NODELETE isEmpty() const
    {
        return !m_storage;
    }

    bool NODELETE isMaterialized() const
    {
        return m_storage & isMaterializedMask;
    }

    void NODELETE setMaterialized(B3::Variable* var)
    {
        ASSERT(!isMaterialized());
        m_storage = reinterpret_cast<uintptr_t>(var) | isMaterializedMask;
        ASSERT(isMaterialized() && b3Variable() == var);
    }

    // Not named value() to disambiguate with TypedExpression::value()
    B3::Value* NODELETE b3Value() const
    {
        ASSERT(!isMaterialized());
        // No need to mask in this common case since the isMaterialized bit will be 0
        return reinterpret_cast<B3::Value*>(m_storage);
    }

    B3::Variable* NODELETE b3Variable() const
    {
        ASSERT(isMaterialized());
        return reinterpret_cast<B3::Variable*>(m_storage & ~isMaterializedMask);
    }

    B3::Type NODELETE type() const
    {
        if (isMaterialized()) [[unlikely]]
            return b3Variable()->type();
        return b3Value()->type();
    }

    void dump(PrintStream& out) const
    {
        if (isMaterialized())
            out.print(*b3Variable());
        else
            out.print(*b3Value());
    }

private:
    uintptr_t m_storage;
};

class OMGIRGenerator {
    WTF_MAKE_TZONE_ALLOCATED(OMGIRGenerator);
public:
    using ExpressionType = OMGExpression;
    using ResultList = Vector<ExpressionType, 8>;
    using CallType = CallLinkInfo::CallType;
    using CallPatchpointData = std::tuple<B3::PatchpointValue*, RefPtr<PatchpointExceptionHandle>, RefPtr<B3::StackmapGenerator>>;
    using WasmConstRefValue = Const64Value;

    static constexpr bool shouldFuseBranchCompare = false;
    static constexpr bool NODELETE tierSupportsSIMD() { return true; }
    static constexpr bool validateFunctionBodySize = true;

    struct ControlData {
        ControlData(Procedure& proc, Origin origin, BlockSignature&& signature, BlockType type, BasicBlock* continuation, BasicBlock* special = nullptr)
            : controlBlockType(type)
            , m_signature(WTF::move(signature))
            , continuation(continuation)
            , special(special)
        {
            ASSERT(type != BlockType::Try && type != BlockType::Catch);

            if (type == BlockType::Loop) {
                for (unsigned i = 0; i < m_signature.argumentCount(); ++i)
                    phis.append(proc.add<Value>(Phi, toB3Type(m_signature.argumentType(i)), origin));
            } else {
                for (unsigned i = 0; i < m_signature.returnCount(); ++i)
                    phis.append(proc.add<Value>(Phi, toB3Type(m_signature.returnType(i)), origin));
            }
        }

        ControlData(Procedure& proc, Origin origin, BlockSignature&& signature, BlockType type, BasicBlock* continuation, unsigned tryStart, unsigned tryDepth)
            : controlBlockType(type)
            , m_signature(WTF::move(signature))
            , continuation(continuation)
            , special(nullptr)
            , m_tryStart(tryStart)
            , m_tryCatchDepth(tryDepth)
        {
            ASSERT(type == BlockType::Try || type == BlockType::TryTable);
            for (unsigned i = 0; i < m_signature.returnCount(); ++i)
                phis.append(proc.add<Value>(Phi, toB3Type(m_signature.returnType(i)), origin));
        }

        ControlData()
        {
        }

        static bool NODELETE isIf(const ControlData& control) { return control.blockType() == BlockType::If; }
        static bool NODELETE isElse(const ControlData& control) { return control.blockType() == BlockType::Else; }
        static bool NODELETE isTry(const ControlData& control) { return control.blockType() == BlockType::Try; }
        static bool NODELETE isTryTable(const ControlData& control) { return control.blockType() == BlockType::TryTable; }
        static bool NODELETE isAnyCatch(const ControlData& control) { return control.blockType() == BlockType::Catch; }
        static bool NODELETE isTopLevel(const ControlData& control) { return control.blockType() == BlockType::TopLevel; }
        static bool NODELETE isLoop(const ControlData& control) { return control.blockType() == BlockType::Loop; }
        static bool NODELETE isBlock(const ControlData& control) { return control.blockType() == BlockType::Block; }
        static bool NODELETE isCatch(const ControlData& control)
        {
            if (control.blockType() != BlockType::Catch)
                return false;
            return control.catchKind() == CatchKind::Catch;
        }

        void dump(PrintStream& out) const
        {
            switch (blockType()) {
            case BlockType::If:
                out.print("If:       ");
                break;
            case BlockType::Else:
                out.print("Else:     ");
                break;
            case BlockType::Block:
                out.print("Block:    ");
                break;
            case BlockType::Loop:
                out.print("Loop:     ");
                break;
            case BlockType::TopLevel:
                out.print("TopLevel: ");
                break;
            case BlockType::Try:
                out.print("Try: ");
                break;
            case BlockType::TryTable:
                out.print("TryTable: ");
                break;
            case BlockType::Catch:
                out.print("Catch: ");
                break;
            }
            out.print("Continuation: ", *continuation, ", Special: ");
            if (special)
                out.print(*special);
            else
                out.print("None");
        }

        BlockType NODELETE blockType() const { return controlBlockType; }

        const BlockSignature& NODELETE signature() const { return m_signature; }

        bool hasNonVoidresult() const { return m_signature.returnCount() > 0; }

        BasicBlock* NODELETE targetBlockForBranch()
        {
            if (blockType() == BlockType::Loop)
                return special;
            return continuation;
        }

        void NODELETE convertIfToBlock()
        {
            ASSERT(blockType() == BlockType::If);
            controlBlockType = BlockType::Block;
            special = nullptr;
        }

        void NODELETE convertTryToCatch(unsigned tryEndCallSiteIndex, Variable* exception)
        {
            ASSERT(blockType() == BlockType::Try);
            controlBlockType = BlockType::Catch;
            m_catchKind = CatchKind::Catch;
            m_tryEnd = tryEndCallSiteIndex;
            m_exception = exception;
        }

        void NODELETE convertTryToCatchAll(unsigned tryEndCallSiteIndex, Variable* exception)
        {
            ASSERT(blockType() == BlockType::Try);
            controlBlockType = BlockType::Catch;
            m_catchKind = CatchKind::CatchAll;
            m_tryEnd = tryEndCallSiteIndex;
            m_exception = exception;
        }

        struct TryTableTarget {
            CatchKind type;
            uint32_t tag;
            const RTT* exceptionSignature;
            ControlRef target;
        };
        using TargetList = Vector<TryTableTarget>;

        void setTryTableTargets(TargetList&& targets)
        {
            m_tryTableTargets = WTF::move(targets);
        }

        void NODELETE endTryTable(unsigned tryEndCallSiteIndex)
        {
            ASSERT(blockType() == BlockType::TryTable);
            m_tryEnd = tryEndCallSiteIndex;
        }

        FunctionArgCount branchTargetArity() const
        {
            if (blockType() == BlockType::Loop)
                return m_signature.argumentCount();
            return m_signature.returnCount();
        }

        Type branchTargetType(unsigned i) const
        {
            ASSERT(i < branchTargetArity());
            if (blockType() == BlockType::Loop)
                return m_signature.argumentType(i);
            return m_signature.returnType(i);
        }

        unsigned NODELETE tryStart() const
        {
            ASSERT(controlBlockType == BlockType::Try || controlBlockType == BlockType::TryTable || controlBlockType == BlockType::Catch);
            return m_tryStart;
        }

        unsigned NODELETE tryEnd() const
        {
            ASSERT(controlBlockType == BlockType::Catch || controlBlockType == BlockType::TryTable);
            return m_tryEnd;
        }

        unsigned NODELETE tryDepth() const
        {
            ASSERT(controlBlockType == BlockType::Try || controlBlockType == BlockType::TryTable || controlBlockType == BlockType::Catch);
            return m_tryCatchDepth;
        }

        CatchKind NODELETE catchKind() const
        {
            ASSERT(controlBlockType == BlockType::Catch);
            return m_catchKind;
        }

        Variable* NODELETE exception() const
        {
            ASSERT(controlBlockType == BlockType::Catch || controlBlockType == BlockType::TryTable);
            return m_exception;
        }

    private:
        // FIXME: Compress OMGIRGenerator::ControlData fields using an union
        // https://bugs.webkit.org/show_bug.cgi?id=231212
        friend class OMGIRGenerator;
        BlockType controlBlockType;
        BlockSignature m_signature;
        BasicBlock* continuation;
        BasicBlock* special;
        Vector<Value*> phis;
        unsigned m_tryStart;
        unsigned m_tryEnd;
        unsigned m_tryCatchDepth;
        CatchKind m_catchKind;
        Variable* m_exception;
        TargetList m_tryTableTargets;
    };

    using ControlType = ControlData;
    using ExpressionList = Vector<ExpressionType, 1>;

    using ControlEntry = FunctionParser<OMGIRGenerator>::ControlEntry;
    using ControlStack = FunctionParser<OMGIRGenerator>::ControlStack;
    using Stack = FunctionParser<OMGIRGenerator>::Stack;
    using TypedExpression = FunctionParser<OMGIRGenerator>::TypedExpression;
    using CatchHandler = FunctionParser<OMGIRGenerator>::CatchHandler;
    using ArgumentList = FunctionParser<OMGIRGenerator>::ArgumentList;

    static_assert(std::is_same_v<ResultList, FunctionParser<OMGIRGenerator>::ResultList>);

    typedef String ErrorType;
    typedef std::unexpected<ErrorType> UnexpectedResult;
    typedef Expected<std::unique_ptr<InternalFunction>, ErrorType> Result;
    typedef Expected<void, ErrorType> PartialResult;

    static ExpressionType NODELETE emptyExpression() { return { }; };

    enum class CastKind { Cast, Test };

    template <typename ...Args>
    [[nodiscard]] NEVER_INLINE UnexpectedResult fail(Args... args) const
    {
        using namespace FailureHelper; // See ADL comment in WasmParser.h.
        return UnexpectedResult(makeString("WebAssembly.Module failed compiling: "_s, makeString(args)...));
    }
#define WASM_COMPILE_FAIL_IF(condition, ...) do { \
        if (condition) [[unlikely]]                  \
            return fail(__VA_ARGS__);             \
    } while (0)

    unsigned NODELETE advanceCallSiteIndex()
    {
        if (m_inlineParent)
            return m_inlineRoot->advanceCallSiteIndex();
        return ++m_callSiteIndex;
    }

    unsigned NODELETE callSiteIndex() const
    {
        if (m_inlineParent)
            return m_inlineRoot->callSiteIndex();
        return m_callSiteIndex;
    }

    OMGIRGenerator(AbstractHeapRepository&, CompilationContext&, Module&, CalleeGroup&, const ModuleInformation&, IPIntCallee&, InliningNode*, OptimizingJITCallee&, Procedure&, Vector<UnlinkedWasmToWasmCall>&, FixedBitVector& outgoingDirectCallees, unsigned& osrEntryScratchBufferSize, MemoryMode, CompilationMode, unsigned functionIndex, unsigned loopIndexForOSREntry);
    OMGIRGenerator(AbstractHeapRepository&, CompilationContext&, OMGIRGenerator& inlineCaller, OMGIRGenerator& inlineRoot, Module&, CalleeGroup&, unsigned functionIndex, IPIntCallee&, InliningNode*, BasicBlock* returnContinuation, Vector<Value*> args);

    void computeStackCheckSize(bool& needsOverflowCheck, int32_t& checkSize);

    Value* NODELETE wasmRefOfCell(Value* cell)
    {
        return cell;
    }

    Value* NODELETE pointerOfWasmRef(Value* ref)
    {
        return ref;
    }

    Value* pointerOfInt32(Value* value)
    {
        return m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), value);
    }

    Value* int32OfPointer(Value* value)
    {
        return m_currentBlock->appendNew<Value>(m_proc, Trunc, origin(), value);
    }

    // SIMD
    void NODELETE notifyFunctionUsesSIMD() { ASSERT(m_info.usesSIMD(m_functionIndex)); }
    [[nodiscard]] PartialResult addSIMDLoad(ExpressionType pointer, uint32_t offset, ExpressionType& result, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addSIMDStore(ExpressionType value, ExpressionType pointer, uint32_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addSIMDSplat(SIMDLane, ExpressionType scalar, ExpressionType& result);
    [[nodiscard]] PartialResult addSIMDShuffle(v128_t imm, ExpressionType a, ExpressionType b, ExpressionType& result);
    [[nodiscard]] PartialResult addSIMDShift(SIMDLaneOperation, SIMDInfo, ExpressionType v, ExpressionType shift, ExpressionType& result);
    [[nodiscard]] PartialResult addSIMDExtmul(SIMDLaneOperation, SIMDInfo, ExpressionType lhs, ExpressionType rhs, ExpressionType& result);
    [[nodiscard]] PartialResult addSIMDLoadSplat(SIMDLaneOperation, ExpressionType pointer, uint32_t offset, ExpressionType& result, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addSIMDLoadLane(SIMDLaneOperation, ExpressionType pointer, ExpressionType vector, uint32_t offset, uint8_t laneIndex, ExpressionType& result, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addSIMDStoreLane(SIMDLaneOperation, ExpressionType pointer, ExpressionType vector, uint32_t offset, uint8_t laneIndex, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addSIMDLoadExtend(SIMDLaneOperation, ExpressionType pointer, uint32_t offset, ExpressionType& result, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addSIMDLoadPad(SIMDLaneOperation, ExpressionType pointer, uint32_t offset, ExpressionType& result, uint8_t memoryIndex);

    [[nodiscard]] ExpressionType addSIMDConstant(v128_t value)
    {
        return push(constant(B3::V128, value));
    }

    // SIMD generated

    #define B3_OP_CASE(OP) \
    else if (op == SIMDLaneOperation::OP) b3Op = B3::Vector##OP;

    #define B3_OP_CASES() \
    B3::Opcode b3Op = B3::Oops; \
    if (false) { }

    auto addSIMDExtractLane(SIMDInfo info, uint8_t lane, ExpressionType v, ExpressionType& result) -> PartialResult
    {
        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorExtractLane, toB3Type(simdScalarType(info.lane)), info,
            lane,
            get(v)));
        return { };
    }

    auto addSIMDReplaceLane(SIMDInfo info, uint8_t lane, ExpressionType v, ExpressionType s, ExpressionType& result) -> PartialResult
    {
        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorReplaceLane, B3::V128, info,
            lane,
            get(v),
            get(s)));
        return { };
    }

    auto addSIMDI_V(SIMDLaneOperation op, SIMDInfo info, ExpressionType v, ExpressionType& result) -> PartialResult
    {
        B3_OP_CASES()
        B3_OP_CASE(Bitmask)
        B3_OP_CASE(AnyTrue)
        B3_OP_CASE(AllTrue)
        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), b3Op, B3::Int32, info,
            get(v)));
        return { };
    }

    auto addSIMDV_V(SIMDLaneOperation op, SIMDInfo info, ExpressionType v, ExpressionType& result) -> PartialResult
    {
        B3_OP_CASES()
        B3_OP_CASE(Demote)
        B3_OP_CASE(Promote)
        B3_OP_CASE(Abs)
        B3_OP_CASE(Popcnt)
        B3_OP_CASE(Ceil)
        B3_OP_CASE(Floor)
        B3_OP_CASE(Trunc)
        B3_OP_CASE(Nearest)
        B3_OP_CASE(Sqrt)
        B3_OP_CASE(ExtaddPairwise)
        B3_OP_CASE(Convert)
        B3_OP_CASE(ConvertLow)
        B3_OP_CASE(ExtendHigh)
        B3_OP_CASE(ExtendLow)
        B3_OP_CASE(TruncSat)
        B3_OP_CASE(RelaxedTruncSat)
        B3_OP_CASE(Not)
        B3_OP_CASE(Neg)

        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), b3Op, B3::V128, info,
            get(v)));
        return { };
    }

    auto addSIMDBitwiseSelect(ExpressionType v1, ExpressionType v2, ExpressionType c, ExpressionType& result) -> PartialResult
    {
        auto b3Op = B3::VectorBitwiseSelect;
        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), b3Op, B3::V128, SIMDInfo { SIMDLane::v128, SIMDSignMode::None },
            get(v1), get(v2), get(c)));
        return { };
    }

    auto addSIMDRelOp(SIMDLaneOperation, SIMDInfo info, ExpressionType lhs, ExpressionType rhs, Air::Arg relOp, ExpressionType& result) -> PartialResult
    {
        B3::Opcode b3Op = Oops;
        if (scalarTypeIsIntegral(info.lane)) {
            switch (relOp.asRelationalCondition()) {
            case MacroAssembler::Equal: 
                b3Op = VectorEqual;
                break;
            case MacroAssembler::NotEqual: 
                b3Op = VectorNotEqual;
                break;
            case MacroAssembler::LessThan: 
                b3Op = VectorLessThan;
                break;
            case MacroAssembler::LessThanOrEqual: 
                b3Op = VectorLessThanOrEqual;
                break;
            case MacroAssembler::Below: 
                b3Op = VectorBelow;
                break;
            case MacroAssembler::BelowOrEqual: 
                b3Op = VectorBelowOrEqual;
                break;
            case MacroAssembler::GreaterThan: 
                b3Op = VectorGreaterThan;
                break;
            case MacroAssembler::GreaterThanOrEqual: 
                b3Op = VectorGreaterThanOrEqual;
                break;
            case MacroAssembler::Above: 
                b3Op = VectorAbove;
                break;
            case MacroAssembler::AboveOrEqual: 
                b3Op = VectorAboveOrEqual;
                break;
            }
        } else {
            switch (relOp.asDoubleCondition()) {
            case MacroAssembler::DoubleEqualAndOrdered: 
                b3Op = VectorEqual;
                break;
            case MacroAssembler::DoubleNotEqualOrUnordered: 
                b3Op = VectorNotEqual;
                break;
            case MacroAssembler::DoubleLessThanAndOrdered: 
                b3Op = VectorLessThan;
                break;
            case MacroAssembler::DoubleLessThanOrEqualAndOrdered: 
                b3Op = VectorLessThanOrEqual;
                break;
            case MacroAssembler::DoubleGreaterThanAndOrdered: 
                b3Op = VectorGreaterThan;
                break;
            case MacroAssembler::DoubleGreaterThanOrEqualAndOrdered: 
                b3Op = VectorGreaterThanOrEqual;
                break;
            default:
                RELEASE_ASSERT_NOT_REACHED();
                break;
            }
        }

        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), b3Op, B3::V128, info,
            get(lhs), get(rhs)));
        return { };
    }

    Value* fixupOutOfBoundsIndicesForSwizzle(Value* input, Value* indexes)
    {
        // The intel version of the swizzle instruction does not handle OOB indices properly,
        // so we need to fix them up.
        ASSERT(isX86());
        // Let each byte mask be 112 (0x70) then after VectorAddSat
        // each index > 15 would set the saturated index's bit 7 to 1,
        // whose corresponding byte will be zero cleared in VectorSwizzle.
        // https://github.com/WebAssembly/simd/issues/93
        v128_t mask;
        mask.u64x2[0] = 0x7070707070707070;
        mask.u64x2[1] = 0x7070707070707070;
        auto saturatingMask = m_currentBlock->appendNew<Const128Value>(m_proc, origin(), mask);
        auto saturatedIndexes = m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), VectorAddSat, B3::V128, SIMDLane::i8x16, SIMDSignMode::Unsigned, saturatingMask, indexes);
        return m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), VectorSwizzle, B3::V128, SIMDLane::i8x16, SIMDSignMode::None, input, saturatedIndexes);
    }

    auto addSIMDV_VV(SIMDLaneOperation op, SIMDInfo info, ExpressionType a, ExpressionType b, ExpressionType& result) -> PartialResult
    {
        B3_OP_CASES()
        B3_OP_CASE(And)
        B3_OP_CASE(Andnot)
        B3_OP_CASE(AvgRound)
        B3_OP_CASE(DotProduct)
        B3_OP_CASE(Add)
        B3_OP_CASE(Mul)
        B3_OP_CASE(MulSat)
        B3_OP_CASE(Sub)
        B3_OP_CASE(Div)
        B3_OP_CASE(Pmax)
        B3_OP_CASE(Pmin)
        B3_OP_CASE(Or)
        B3_OP_CASE(Swizzle)
        B3_OP_CASE(RelaxedSwizzle)
        B3_OP_CASE(Xor)
        B3_OP_CASE(Narrow)
        B3_OP_CASE(AddSat)
        B3_OP_CASE(SubSat)
        B3_OP_CASE(Max)
        B3_OP_CASE(Min)
        B3_OP_CASE(RelaxedMin)
        B3_OP_CASE(RelaxedMax)
        B3_OP_CASE(RelaxedQ15Mulr)
        B3_OP_CASE(RelaxedDotI8x16I7x16)

        if (isX86() && b3Op == B3::VectorSwizzle) {
            result = push(fixupOutOfBoundsIndicesForSwizzle(get(a), get(b)));
            return { };
        }

        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), b3Op, B3::V128, info,
            get(a), get(b)));
        return { };
    }

    auto addSIMDRelaxedFMA(SIMDLaneOperation op, SIMDInfo info, ExpressionType m1, ExpressionType m2, ExpressionType add, ExpressionType& result) -> PartialResult
    {
        B3_OP_CASES()
        B3_OP_CASE(RelaxedMAdd)
        B3_OP_CASE(RelaxedNMAdd)
        B3_OP_CASE(RelaxedDotI8x16I7x16Add)

        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), b3Op, B3::V128, info,
            get(m1), get(m2), get(add)));
        return { };
    }

    [[nodiscard]] PartialResult addDrop(ExpressionType);
    [[nodiscard]] PartialResult addInlinedArguments(const RTT&);
    [[nodiscard]] PartialResult addArguments(const RTT&);
    [[nodiscard]] PartialResult addLocal(Type, uint32_t);
    ExpressionType addConstant(Type, uint64_t);

    // References
    [[nodiscard]] PartialResult addRefIsNull(ExpressionType value, ExpressionType& result);
    [[nodiscard]] PartialResult addRefFunc(FunctionSpaceIndex index, ExpressionType& result);
    [[nodiscard]] PartialResult addRefAsNonNull(TypedExpression, ExpressionType&);
    [[nodiscard]] PartialResult addRefEq(ExpressionType, ExpressionType, ExpressionType&);

    // Tables
    [[nodiscard]] PartialResult addTableGet(unsigned, ExpressionType index, ExpressionType& result);
    [[nodiscard]] PartialResult addTableSet(unsigned, ExpressionType index, ExpressionType value);
    [[nodiscard]] PartialResult addTableInit(unsigned, unsigned, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length);
    [[nodiscard]] PartialResult addElemDrop(unsigned);
    [[nodiscard]] PartialResult addTableSize(unsigned, ExpressionType& result);
    [[nodiscard]] PartialResult addTableGrow(unsigned, ExpressionType fill, ExpressionType delta, ExpressionType& result);
    [[nodiscard]] PartialResult addTableFill(unsigned, ExpressionType offset, ExpressionType fill, ExpressionType count);
    [[nodiscard]] PartialResult addTableCopy(unsigned, unsigned, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length);

    // Locals
    [[nodiscard]] PartialResult getLocal(uint32_t index, ExpressionType& result);
    [[nodiscard]] PartialResult setLocal(uint32_t index, ExpressionType value);
    [[nodiscard]] PartialResult teeLocal(uint32_t, ExpressionType, ExpressionType& result);

    // Globals
    [[nodiscard]] PartialResult getGlobal(uint32_t index, ExpressionType& result);
    [[nodiscard]] PartialResult setGlobal(uint32_t index, ExpressionType value);

    // Memory
    [[nodiscard]] PartialResult load(LoadOpType, ExpressionType pointer, ExpressionType& result, uint64_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult store(StoreOpType, ExpressionType pointer, ExpressionType value, uint64_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addGrowMemory(ExpressionType delta, ExpressionType& result, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addCurrentMemory(ExpressionType& result, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addMemoryFill(ExpressionType dstAddress, ExpressionType targetValue, ExpressionType count, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addMemoryCopy(ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType count, uint8_t dstMemoryIndex, uint8_t srcMemoryIndex);
    [[nodiscard]] PartialResult addMemoryInit(unsigned, ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType length, uint8_t memoryIndex);
    [[nodiscard]] PartialResult addDataDrop(unsigned);

    // Atomics
    [[nodiscard]] PartialResult atomicLoad(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType& result, uint64_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult atomicStore(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType value, uint64_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult atomicBinaryRMW(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType value, ExpressionType& result, uint64_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult atomicCompareExchange(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType expected, ExpressionType value, ExpressionType& result, uint64_t offset, uint8_t memoryIndex);

    [[nodiscard]] PartialResult atomicWait(ExtAtomicOpType, ExpressionType pointer, ExpressionType value, ExpressionType timeout, ExpressionType& result, uint64_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult atomicNotify(ExtAtomicOpType, ExpressionType pointer, ExpressionType value, ExpressionType& result, uint64_t offset, uint8_t memoryIndex);
    [[nodiscard]] PartialResult atomicFence(ExtAtomicOpType, uint8_t flags);

    // Saturated truncation.
    [[nodiscard]] PartialResult truncSaturated(Ext1OpType, ExpressionType operand, ExpressionType& result, Type returnType, Type operandType);

    // Wide arithmetic.
    [[nodiscard]] PartialResult addI64Add128(ExpressionType lhsLo, ExpressionType lhsHi, ExpressionType rhsLo, ExpressionType rhsHi, ExpressionType& resultLo, ExpressionType& resultHi);
    [[nodiscard]] PartialResult addI64Sub128(ExpressionType lhsLo, ExpressionType lhsHi, ExpressionType rhsLo, ExpressionType rhsHi, ExpressionType& resultLo, ExpressionType& resultHi);
    [[nodiscard]] PartialResult addI64MulWideS(ExpressionType lhs, ExpressionType rhs, ExpressionType& resultLo, ExpressionType& resultHi);
    [[nodiscard]] PartialResult addI64MulWideU(ExpressionType lhs, ExpressionType rhs, ExpressionType& resultLo, ExpressionType& resultHi);
    B3::Type int64PairTupleType();

    // GC
    [[nodiscard]] PartialResult addRefI31(ExpressionType value, ExpressionType& result);
    [[nodiscard]] PartialResult addI31GetS(TypedExpression ref, ExpressionType& result);
    [[nodiscard]] PartialResult addI31GetU(TypedExpression ref, ExpressionType& result);
    [[nodiscard]] PartialResult addArrayNew(TypeSignatureIndex index, ExpressionType size, ExpressionType value, ExpressionType& result);
    [[nodiscard]] PartialResult addArrayNewDefault(TypeSignatureIndex index, ExpressionType size, ExpressionType& result);
    [[nodiscard]] PartialResult addArrayNewFixed(TypeSignatureIndex typeIndex, ArgumentList& args, ExpressionType& result);
    [[nodiscard]] PartialResult addArrayGet(ExtGCOpType arrayGetKind, TypeSignatureIndex typeIndex, TypedExpression arrayref, ExpressionType index, ExpressionType& result);
    [[nodiscard]] PartialResult addArrayNewData(TypeSignatureIndex typeIndex, uint32_t dataIndex, ExpressionType size, ExpressionType offset, ExpressionType& result);
    [[nodiscard]] PartialResult addArrayNewElem(TypeSignatureIndex typeIndex, uint32_t elemSegmentIndex, ExpressionType size, ExpressionType offset, ExpressionType& result);
    [[nodiscard]] PartialResult addArraySet(TypeSignatureIndex typeIndex, TypedExpression arrayref, ExpressionType index, ExpressionType value);
    [[nodiscard]] PartialResult addArrayLen(TypedExpression arrayref, ExpressionType& result);
    [[nodiscard]] PartialResult addArrayFill(TypeSignatureIndex, TypedExpression, ExpressionType, ExpressionType, ExpressionType);
    [[nodiscard]] PartialResult addArrayCopy(TypeSignatureIndex, TypedExpression, ExpressionType, TypeSignatureIndex, TypedExpression, ExpressionType, ExpressionType);
    [[nodiscard]] PartialResult addArrayInitElem(TypeSignatureIndex, TypedExpression, ExpressionType, uint32_t, ExpressionType, ExpressionType);
    [[nodiscard]] PartialResult addArrayInitData(TypeSignatureIndex, TypedExpression, ExpressionType, uint32_t, ExpressionType, ExpressionType);
    [[nodiscard]] PartialResult addStructNew(TypeSignatureIndex typeIndex, ArgumentList& args, ExpressionType& result);
    [[nodiscard]] PartialResult addStructNewDefault(TypeSignatureIndex index, ExpressionType& result);
    [[nodiscard]] PartialResult addStructGet(ExtGCOpType structGetKind, TypedExpression structReference, const RTT&, uint32_t fieldIndex, ExpressionType& result);
    [[nodiscard]] PartialResult addStructSet(TypedExpression structReference, const RTT&, uint32_t fieldIndex, ExpressionType value);
    [[nodiscard]] PartialResult addRefTest(TypedExpression reference, bool allowNull, int32_t heapType, bool shouldNegate, ExpressionType& result);
    [[nodiscard]] PartialResult addRefCast(TypedExpression reference, bool allowNull, int32_t heapType, ExpressionType& result);
    [[nodiscard]] PartialResult addAnyConvertExtern(ExpressionType reference, ExpressionType& result);
    [[nodiscard]] PartialResult addExternConvertAny(ExpressionType reference, ExpressionType& result);

    // Basic operators
#define X(name, opcode, short, idx, ...) \
    [[nodiscard]] PartialResult add##name(ExpressionType arg, ExpressionType& result);
    FOR_EACH_WASM_UNARY_OP(X)
#undef X
#define X(name, opcode, short, idx, ...) \
    [[nodiscard]] PartialResult add##name(ExpressionType left, ExpressionType right, ExpressionType& result);
    FOR_EACH_WASM_BINARY_OP(X)
#undef X

    [[nodiscard]] PartialResult addSelect(ExpressionType condition, ExpressionType nonZero, ExpressionType zero, ExpressionType& result);

    // Control flow
    [[nodiscard]] ControlData addTopLevel(BlockSignature&&);
    [[nodiscard]] PartialResult addBlock(BlockSignature&&, std::span<TypedExpression> args, ControlType& newBlock);
    [[nodiscard]] PartialResult addLoop(BlockSignature&&, std::span<TypedExpression> args, ControlType& block, uint32_t loopIndex);
    [[nodiscard]] PartialResult addIf(ExpressionType condition, BlockSignature&&, std::span<TypedExpression> args, ControlType& result);
    [[nodiscard]] PartialResult addElse(ControlData&, std::span<const TypedExpression>);
    [[nodiscard]] PartialResult addElseToUnreachable(ControlData&);

    [[nodiscard]] PartialResult addTry(BlockSignature&&, std::span<TypedExpression> args, ControlType& result);
    [[nodiscard]] PartialResult addTryTable(BlockSignature&&, std::span<TypedExpression> args, const Vector<CatchHandler>& targets, ControlType& result);
    [[nodiscard]] PartialResult addCatch(unsigned exceptionIndex, const RTT&, std::span<const TypedExpression>, ControlType&, ResultList&);
    [[nodiscard]] PartialResult addCatchToUnreachable(unsigned exceptionIndex, const RTT&, ControlType&, ResultList&);
    [[nodiscard]] PartialResult addCatchAll(std::span<const TypedExpression>, ControlType&);
    [[nodiscard]] PartialResult addCatchAllToUnreachable(ControlType&);
    [[nodiscard]] PartialResult addDelegate(ControlType&, ControlType&);
    [[nodiscard]] PartialResult addDelegateToUnreachable(ControlType&, ControlType&);
    [[nodiscard]] PartialResult addThrow(unsigned exceptionIndex, ArgumentList& args, std::span<const TypedExpression>);
    [[nodiscard]] PartialResult addRethrow(unsigned, ControlType&);
    [[nodiscard]] PartialResult addThrowRef(TypedExpression exception, std::span<const TypedExpression>);

    [[nodiscard]] PartialResult addInlinedReturn(const auto& returnValues);

    [[nodiscard]] PartialResult addReturn(const ControlData&, std::span<const TypedExpression> returnValues);
    [[nodiscard]] PartialResult addBranch(ControlData&, ExpressionType condition, std::span<const TypedExpression> returnValues);
    [[nodiscard]] PartialResult addBranchNull(ControlType&, ExpressionType, std::span<const TypedExpression>, bool, ExpressionType&);
    [[nodiscard]] PartialResult addBranchCast(ControlType&, TypedExpression, std::span<const TypedExpression>, bool, int32_t, bool);
    [[nodiscard]] PartialResult addSwitch(ExpressionType condition, const Vector<ControlData*>& targets, ControlData& defaultTargets, std::span<const TypedExpression> expressionStack);
    [[nodiscard]] PartialResult endBlock(ControlEntry&, std::span<TypedExpression> enclosedStack);
    [[nodiscard]] PartialResult addEndToUnreachable(ControlEntry&, std::span<TypedExpression> enclosedStack);

    [[nodiscard]] PartialResult NODELETE endTopLevel(std::span<const TypedExpression>) { return { }; }

    // Fused comparison stubs (B3 will do this for us later).
    [[nodiscard]] PartialResult NODELETE addFusedBranchCompare(OpType, ControlType&, ExpressionType, std::span<const TypedExpression>) { RELEASE_ASSERT_NOT_REACHED(); }
    [[nodiscard]] PartialResult NODELETE addFusedBranchCompare(OpType, ControlType&, ExpressionType, ExpressionType, std::span<const TypedExpression>) { RELEASE_ASSERT_NOT_REACHED(); }
    [[nodiscard]] PartialResult NODELETE addFusedIfCompare(OpType, ExpressionType, BlockSignature&&, std::span<TypedExpression>, ControlType&) { RELEASE_ASSERT_NOT_REACHED(); }
    [[nodiscard]] PartialResult NODELETE addFusedIfCompare(OpType, ExpressionType, ExpressionType, BlockSignature&&, std::span<TypedExpression>, ControlType&) { RELEASE_ASSERT_NOT_REACHED(); }

    // Calls
    [[nodiscard]] PartialResult addCall(unsigned, FunctionSpaceIndex functionIndexSpace, const RTT&, ArgumentList& args, ResultList& results, CallType = CallType::Call);
    [[nodiscard]] PartialResult addCallIndirect(unsigned, unsigned tableIndex, const RTT&, ArgumentList& args, ResultList& results, CallType = CallType::Call);
    [[nodiscard]] PartialResult addCallRef(unsigned, const RTT&, ArgumentList& args, ResultList& results, CallType = CallType::Call);
    [[nodiscard]] PartialResult addUnreachable();
    [[nodiscard]] PartialResult addCrash();

    using ValueResults = Vector<Value*, 16>;
    void fillCallResults(Value* callResult, const RTT& signature, ValueResults&);
    [[nodiscard]] PartialResult emitDirectCall(unsigned, FunctionSpaceIndex functionIndexSpace, const RTT&, const ArgumentList& args, ValueResults&, CallType = CallType::Call);
    [[nodiscard]] PartialResult emitIndirectCall(Value* calleeInstance, Value* calleeCode, Value* boxedCalleeCallee, const RTT&, const ArgumentList& args, ValueResults&, CallType = CallType::Call);

    Vector<ConstrainedValue> createCallConstrainedArgs(BasicBlock*, const CallInformation& wasmCalleeInfo, const ArgumentList&);
    auto createCallPatchpoint(BasicBlock*, const RTT&, const CallInformation&, const ArgumentList& tmpArgs) -> CallPatchpointData;
    auto createTailCallPatchpoint(BasicBlock*, const RTT&, const CallInformation& wasmCallerInfoAsCallee, const CallInformation& wasmCalleeInfoAsCallee, const ArgumentList& tmpArgSourceLocations, Value* boxedCalleeCallee = nullptr) -> CallPatchpointData;

    InliningNode* canInline(FunctionSpaceIndex functionIndexSpace, unsigned callProfileIndex) const;
    [[nodiscard]] PartialResult emitInlineDirectCall(InliningNode*, FunctionCodeIndex calleeIndex, const RTT&, const ArgumentList& args, ValueResults&);

    void dump(const ControlStack&, const Stack* expressionStack);
    void NODELETE setParser(FunctionParser<OMGIRGenerator>* parser) { m_parser = parser; };
    ALWAYS_INLINE void willParseOpcode() { }
    ALWAYS_INLINE void willParseExtendedOpcode() { }
    ALWAYS_INLINE void didParseOpcode() { }
    void NODELETE didFinishParsingLocals() { }
    void didPopValueFromStack(ExpressionType expr, ASCIILiteral message)
    {
        TRACE_VALUE(Wasm::Types::Void, get(expr), "pop at height: ", m_parser->expressionStack().size() + 1, " site: [", message, "], ", expr);
    }
    const RTT* getArrayRTT(TypeSignatureIndex);
    void getArrayElementType(TypeSignatureIndex, StorageType&);
    void getArrayRefType(TypeSignatureIndex, Type&);

    Value* constant(B3::Type, uint64_t bits, std::optional<Origin> = std::nullopt);
    Value* constant(B3::Type, v128_t bits, std::optional<Origin> = std::nullopt);
    Value* framePointer();
    void insertEntrySwitch();
    void insertConstants();

    B3::Type toB3ResultType(const RTT*);

    void addStackMap(unsigned callSiteIndex, StackMap&& stackmap)
    {
        if (m_inlineParent) {
            m_inlineRoot->addStackMap(callSiteIndex, WTF::move(stackmap));
            return;
        }
        m_stackmaps.add(CallSiteIndex(callSiteIndex), WTF::move(stackmap));
    }

    StackMaps&& NODELETE takeStackmaps()
    {
        RELEASE_ASSERT(m_inlineRoot == this);
        return WTF::move(m_stackmaps);
    }

    Vector<UnlinkedHandlerInfo>&& NODELETE takeExceptionHandlers()
    {
        RELEASE_ASSERT(m_inlineRoot == this);
        return WTF::move(m_exceptionHandlers);
    }

private:
    void NODELETE emitPrepareWasmOperation(BasicBlock* block)
    {
#if !USE(BUILTIN_FRAME_ADDRESS) || ASSERT_ENABLED
        // Prepare wasm operation calls.
        block->appendNew<B3::MemoryValue>(m_proc, B3::Store, origin(), framePointer(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfTemporaryCallFrame()));
#else
        UNUSED_PARAM(block);
#endif
    }

    template<typename OperationType, typename ...Args>
    Value* callWasmOperation(BasicBlock* block, B3::Type resultType, OperationType operation, Args&&... args)
    {
        emitPrepareWasmOperation(block);
        static_assert(FunctionTraits<OperationType>::cCallArity() == sizeof...(Args), "Sanity check");
        Value* operationValue = block->appendNew<ConstPtrValue>(m_proc, origin(), tagCFunction<OperationPtrTag>(operation));
        return block->appendNew<CCallValue>(m_proc, resultType, origin(), operationValue, std::forward<Args>(args)...);
    }

    void emitExceptionCheck(CCallHelpers&, Origin, ExceptionType);

    void emitWriteBarrierForJSWrapper();
    void emitWriteBarrier(Value* cell);
    Value* emitCheckAndPreparePointer(Value* pointer, uint64_t offset, uint32_t sizeOfOp, uint8_t memoryIndex);
    B3::Kind memoryKind(B3::Opcode memoryOp);
    Value* emitLoadOp(LoadOpType, Value* pointer, uint64_t offset);
    void emitStoreOp(StoreOpType, Value* pointer, Value*, uint64_t offset);

    Value* sanitizeAtomicResult(ExtAtomicOpType, Type, Value* result);
    Value* emitAtomicLoadOp(ExtAtomicOpType, Type, Value* pointer, uint64_t offset);
    void emitAtomicStoreOp(ExtAtomicOpType, Type, Value* pointer, Value*, uint64_t offset);
    Value* emitAtomicBinaryRMWOp(ExtAtomicOpType, Type, Value* pointer, Value*, uint64_t offset);
    Value* emitAtomicCompareExchange(ExtAtomicOpType, Type, Value* pointer, Value* expected, Value*, uint64_t offset);

    void mutatorFence();

    Value* emitGetArraySizeWithNullCheck(Type arrayType, Value*);
    void emitNullCheck(Value*, ExceptionType);
    bool emitNullCheckBeforeAccess(Value*, ptrdiff_t offset);
    void emitArraySetUnchecked(TypeSignatureIndex, Value*, Value*, Value*);
    bool emitArraySetUncheckedWithoutWriteBarrier(TypeSignatureIndex, Value*, Value*, Value*);
    // Returns true if a writeBarrier/mutatorFence is needed.
    [[nodiscard]] bool emitStructSet(bool canTrap, Value*, uint32_t, const RTT&, Value*);
    using ArraySegmentOperation = EncodedJSValue SYSV_ABI (&)(JSC::JSWebAssemblyInstance*, uint32_t, uint32_t, uint32_t, uint32_t);
    [[nodiscard]] ExpressionType pushArrayNewFromSegment(ArraySegmentOperation, TypeSignatureIndex typeIndex, uint32_t segmentIndex, ExpressionType arraySize, ExpressionType offset, ExceptionType);
    void emitRefTestOrCast(CastKind, TypedExpression, bool, int32_t, bool, ExpressionType&);

    MemoryValue* loadGCObjectStructureID(TypeSignatureIndex typeIndex)
    {
        auto* structureID = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int32, origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfGCObjectStructureID(m_info, typeIndex.rawIndex())));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_gcObjectStructureIDs[typeIndex.rawIndex()], structureID);
        structureID->setReadsMutability(B3::Mutability::Immutable);
        structureID->setControlDependent(false);
        return structureID;
    }

    const B3::AbstractHeap* structFieldHeap(const RTT& rtt, uint32_t fieldIndex)
    {
        return &m_heaps.JSWebAssemblyStruct_fields[rtt.fieldHeapKey(fieldIndex)];
    }

    const B3::AbstractHeap* arrayElementHeap(const Wasm::StorageType& elementType, Value* indexValue)
    {
        B3::NumberedAbstractHeap* heap;
        if (elementType.is<Wasm::PackedType>()) {
            switch (elementType.as<Wasm::PackedType>()) {
            case Wasm::PackedType::I8:
                heap = &m_heaps.JSWebAssemblyArray_i8;
                break;
            case Wasm::PackedType::I16:
                heap = &m_heaps.JSWebAssemblyArray_i16;
                break;
            default:
                RELEASE_ASSERT_NOT_REACHED();
            }
        } else {
            auto unpacked = elementType.unpacked();
            switch (unpacked.kind) {
            case Wasm::TypeKind::I32:
                heap = &m_heaps.JSWebAssemblyArray_i32;
                break;
            case Wasm::TypeKind::F32:
                heap = &m_heaps.JSWebAssemblyArray_f32;
                break;
            case Wasm::TypeKind::I64:
                heap = &m_heaps.JSWebAssemblyArray_i64;
                break;
            case Wasm::TypeKind::F64:
                heap = &m_heaps.JSWebAssemblyArray_f64;
                break;
            case Wasm::TypeKind::V128:
                heap = &m_heaps.JSWebAssemblyArray_v128;
                break;
            default:
                heap = &m_heaps.JSWebAssemblyArray_ref;
                break;
            }
        }
        if (indexValue->hasInt32()) {
            int32_t idx = indexValue->asInt32();
            if (idx >= 0)
                return &(*heap)[idx];
        }
        return &heap->atAnyNumber();
    }

    void unify(Value* phi, const ExpressionType& source);
    void unifyValuesWithBlock(std::span<const TypedExpression> resultStack, const ControlData& block);

    void emitChecksForModOrDiv(B3::Opcode, Value* left, Value* right);

    [[nodiscard]] int32_t fixupPointerPlusOffset(Value*&, uint32_t);
    [[nodiscard]] Value* fixupPointerPlusOffsetForAtomicOps(ExtAtomicOpType, Value*, uint64_t);

    void restoreWasmContextInstance(BasicBlock*, Value*);
    void restoreWebAssemblyGlobalState(const Vector<MemoryInformation>&, Value* instance, BasicBlock*);
    void reloadMemoryRegistersFromInstance(const MemoryInformation&, Value* instance, BasicBlock*);

    void materializeExpressionStackIntoVariables();
    Value* loadFromScratchBuffer(unsigned& indexInBuffer, Value* pointer, B3::Type);
    void connectValuesAtEntrypoint(unsigned& indexInBuffer, Value* pointer, std::span<const TypedExpression> expressionStack);
    Value* emitCatchImpl(CatchKind, ControlType&, unsigned exceptionIndex = 0);
    void emitCatchTableImpl(ControlData& entryData, const ControlData::TryTableTarget&);
    RefPtr<PatchpointExceptionHandle> preparePatchpointForExceptions(BasicBlock*, PatchpointValue*);
    void connectValuesForCatchEntrypoint(ControlData& catchData, Value* pointer);

    Origin origin();

    ExpressionType push(Value* value)
    {
        if constexpr (WasmOMGIRGeneratorInternal::traceExecution) {
            String site;
#if ASSERT_ENABLED
            if constexpr (WasmOMGIRGeneratorInternal::traceExecutionIncludesConstructionSite)
                site = Value::generateCompilerConstructionSite();
#endif
            TRACE_VALUE(Wasm::Types::Void, value, "push to stack height ", m_parser->expressionStack().size(), " site: [", site, "] ", value);
        }
        return value;
    }

    Value* get(BasicBlock* block, Variable* variable)
    {
        return block->appendNew<VariableValue>(m_proc, B3::Get, origin(), variable);
    }

    Value* get(Variable* variable)
    {
        return get(m_currentBlock, variable);
    }

    Value* get(BasicBlock* block, const OMGExpression& expr)
    {
        if (expr.isMaterialized())
            return get(block, expr.b3Variable());
        return expr.b3Value();
    }

    Value* get(const OMGExpression& expr)
    {
        return get(m_currentBlock, expr);
    }

    Value* set(BasicBlock* block, Variable* dst, Value* src)
    {
        return block->appendNew<VariableValue>(m_proc, B3::Set, origin(), dst, src);
    }

    Value* set(Variable* dst, Value* src)
    {
        return set(m_currentBlock, dst, src);
    }

    bool NODELETE useSignalingMemory0() const
    {
        return m_mode == MemoryMode::Signaling;
    }

    Expected<Vector<ValueResults>, ErrorType> tryInliningPolymorphicCalls(unsigned callProfileIndex, Value* calleeInstance, Value* calleeCallee, const RTT& signature, const ArgumentList&, CallType, bool isTailCallRootCaller, BasicBlock* continuation);

    template<typename... Args>
    void traceValue(Type, Value*, Args&&... info);
    template<typename... Args>
    void traceCF(Args&&... info);

    FunctionParser<OMGIRGenerator>* m_parser { nullptr };
    AbstractHeapRepository& m_heaps;
    CompilationContext& m_context;
    Module& m_module;
    CalleeGroup& m_calleeGroup;
    const ModuleInformation& m_info;
    const IPIntCallee& m_profiledCallee;
    OptimizingJITCallee* m_callee;
    const MemoryMode m_mode { MemoryMode::BoundsChecking }; // mode for memory 0; all other memories use bounds checking
    const CompilationMode m_compilationMode;
    const FunctionCodeIndex m_functionIndex;
    const unsigned m_loopIndexForOSREntry { UINT_MAX };
    InliningNode* m_inlining { nullptr };

    Procedure& m_proc;
    Vector<BasicBlock*> m_rootBlocks;
    BasicBlock* m_topLevelBlock;
    BasicBlock* m_currentBlock { nullptr };

    // Only used when this is an inlined context
    BasicBlock* m_returnContinuation { nullptr };
    OMGIRGenerator* m_inlineRoot { nullptr };
    OMGIRGenerator* m_inlineParent { nullptr };
    Vector<Value*> m_inlinedArgs;
    Vector<Value*> m_inlinedResultPhis;

    Vector<Variable*> m_locals;

    Vector<UnlinkedWasmToWasmCall>& m_unlinkedWasmToWasmCalls; // List each call site and the function index whose address it should be patched with.
    FixedBitVector& m_directCallees; // Note this includes call targets from functions we inline.
    unsigned* m_osrEntryScratchBufferSize;
    UncheckedKeyHashMap<ValueKey, Value*> m_constantPool;
    UncheckedKeyHashMap<const RTT*, B3::Type> m_tupleMap;
    B3::Type m_int64PairTupleType { };
    InsertionSet m_constantInsertionValues;
    Value* m_framePointer { nullptr };
    bool m_makesCalls { false };
    bool m_makesTailCalls { false };

    // This tracks the maximum stack offset for a tail call, to be used in the stack overflow check.
    Checked<int32_t> m_tailCallStackOffsetFromFP { 0 };

    bool m_hasExceptionHandlers;

    Value* m_instanceValue { nullptr };
    MemoryValue* m_vmValue { nullptr };
    Value* m_baseMemoryValue { nullptr };
    Value* m_boundsCheckingSizeValue { nullptr };

    Value* NODELETE instanceValue()
    {
        return m_instanceValue;
    }

    Value* NODELETE vmValue()
    {
        return m_vmValue;
    }

    Value* NODELETE baseMemoryValue()
    {
        return m_baseMemoryValue;
    }

    Value* NODELETE boundsCheckingSizeValue()
    {
        return m_boundsCheckingSizeValue;
    }

    uint32_t m_maxNumJSCallArguments { 0 };
    unsigned m_numImportFunctions;

    Checked<unsigned> m_tryCatchDepth { 0 };
    Checked<unsigned> m_callSiteIndex { 0 };
    StackMaps m_stackmaps;
    Vector<UnlinkedHandlerInfo> m_exceptionHandlers;

    RefPtr<B3::Air::PrologueGenerator> m_prologueGenerator;

    Vector<std::unique_ptr<OMGIRGenerator>> m_protectedInlineeGenerators;
    Vector<std::unique_ptr<FunctionParser<OMGIRGenerator>>> m_protectedInlineeParsers;
};

WTF_MAKE_TZONE_ALLOCATED_IMPL(OMGIRGenerator);

// Memory accesses in WebAssembly have unsigned 32-bit offsets, whereas they have signed 32-bit offsets in B3.
int32_t OMGIRGenerator::fixupPointerPlusOffset(Value*& ptr, uint32_t offset)
{
    if (static_cast<uint64_t>(offset) > static_cast<uint64_t>(std::numeric_limits<int32_t>::max())) {
        ptr = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), ptr, m_currentBlock->appendNew<ConstPtrValue>(m_proc, origin(), offset));
        return 0;
    }
    return offset;
}

void OMGIRGenerator::restoreWasmContextInstance(BasicBlock* block, Value* arg)
{
    // FIXME: Because WasmToWasm call clobbers wasmContextInstance register and does not restore it, we need to restore it in the caller side.
    // This prevents us from using ArgumentReg to this (logically) immutable pinned register.
    PatchpointValue* patchpoint = block->appendNew<PatchpointValue>(m_proc, B3::Void, Origin());
    Effects effects = Effects::none();
    effects.writesPinned = true;
    effects.reads = B3::HeapRange::top();
    patchpoint->effects = effects;
    patchpoint->clobberLate(RegisterSet(GPRInfo::wasmContextInstancePointer));
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([](CCallHelpers& jit, const StackmapGenerationParams& param) {
        jit.move(param[0].gpr(), GPRInfo::wasmContextInstancePointer);
    });
}

void OMGIRGenerator::computeStackCheckSize(bool& needsOverflowCheck, int32_t& checkSize)
{
    const Checked<int32_t> wasmFrameSize = m_proc.frameSize();
    const Checked<int32_t> wasmTailCallFrameSize = -m_tailCallStackOffsetFromFP;
    const unsigned minimumParentCheckSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(1024);
    const unsigned extraFrameSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(std::max<uint32_t>(
        // This allows us to elide stack checks for functions that are terminal nodes in the call
        // tree, (e.g they don't make any calls) and have a small enough frame size. This works by
        // having any such terminal node have its parent caller include some extra size in its
        // own check for it. The goal here is twofold:
        // 1. Emit less code.
        // 2. Try to speed things up by skipping stack checks.
        minimumParentCheckSize,
        // This allows us to elide stack checks in the Wasm -> JS call IC stub. Since these will
        // spill all arguments to the stack, we ensure that a stack check here covers the
        // stack that such a stub would use.
        Checked<uint32_t>(m_maxNumJSCallArguments) * sizeof(Register) + JSCallingConvention::headerSizeInBytes
    ));

    checkSize = wasmFrameSize.value();
    bool frameSizeNeedsOverflowCheck = checkSize >= static_cast<int32_t>(minimumParentCheckSize);
    needsOverflowCheck = frameSizeNeedsOverflowCheck;

    if (m_makesCalls) {
        needsOverflowCheck = true;
        checkSize = checkedSum<int32_t>(checkSize, extraFrameSize).value();
    } else if (m_makesTailCalls) {
        Checked<int32_t> tailCallCheckSize = std::max<Checked<int32_t>>(wasmTailCallFrameSize + extraFrameSize, 0);
        checkSize = frameSizeNeedsOverflowCheck ? std::max<Checked<int32_t>>(tailCallCheckSize, wasmFrameSize).value() : tailCallCheckSize.value();
        needsOverflowCheck = needsOverflowCheck || checkSize >= static_cast<int32_t>(minimumParentCheckSize);
    }

    bool needUnderflowCheck = static_cast<unsigned>(checkSize) > Options::reservedZoneSize();
    needsOverflowCheck = needsOverflowCheck || needUnderflowCheck;
}

OMGIRGenerator::OMGIRGenerator(AbstractHeapRepository& heaps, CompilationContext& context, OMGIRGenerator& parentCaller, OMGIRGenerator& rootCaller, Module& module, CalleeGroup& calleeGroup, unsigned functionIndex, IPIntCallee& profiledCallee, InliningNode* inlining, BasicBlock* returnContinuation, Vector<Value*> args)
    : m_heaps(heaps)
    , m_context(context)
    , m_module(module)
    , m_calleeGroup(calleeGroup)
    , m_info(rootCaller.m_info)
    , m_profiledCallee(profiledCallee)
    , m_callee(parentCaller.m_callee)
    , m_mode(rootCaller.m_mode)
    , m_compilationMode(CompilationMode::OMGMode)
    , m_functionIndex(functionIndex)
    , m_loopIndexForOSREntry(-1)
    , m_inlining(inlining)
    , m_proc(rootCaller.m_proc)
    , m_returnContinuation(returnContinuation)
    , m_inlineRoot(&rootCaller)
    , m_inlineParent(&parentCaller)
    , m_inlinedArgs(WTF::move(args))
    , m_unlinkedWasmToWasmCalls(rootCaller.m_unlinkedWasmToWasmCalls)
    , m_directCallees(rootCaller.m_directCallees)
    , m_osrEntryScratchBufferSize(nullptr)
    , m_constantInsertionValues(m_proc)
    , m_hasExceptionHandlers(m_profiledCallee.hasExceptionHandlers())
    , m_numImportFunctions(m_info.importFunctionCount())
    , m_tryCatchDepth(parentCaller.m_tryCatchDepth)
    , m_callSiteIndex(0)
{
    m_topLevelBlock = m_proc.addBlock();
    m_rootBlocks.append(m_proc.addBlock());
    m_currentBlock = m_rootBlocks[0];
    m_instanceValue = rootCaller.m_instanceValue;
    m_vmValue = rootCaller.m_vmValue;
    m_baseMemoryValue = rootCaller.m_baseMemoryValue;
    m_boundsCheckingSizeValue = rootCaller.m_boundsCheckingSizeValue;
    if (parentCaller.m_hasExceptionHandlers)
        m_hasExceptionHandlers = true;
}

OMGIRGenerator::OMGIRGenerator(AbstractHeapRepository& heaps, CompilationContext& context, Module& module, CalleeGroup& calleeGroup, const ModuleInformation& info, IPIntCallee& profiledCallee, InliningNode* inlining, OptimizingJITCallee& callee, Procedure& procedure, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, FixedBitVector& outgoingDirectCallees, unsigned& osrEntryScratchBufferSize, MemoryMode mode, CompilationMode compilationMode, unsigned functionIndex, unsigned loopIndexForOSREntry)
    : m_heaps(heaps)
    , m_context(context)
    , m_module(module)
    , m_calleeGroup(calleeGroup)
    , m_info(info)
    , m_profiledCallee(profiledCallee)
    , m_callee(&callee)
    , m_mode(mode)
    , m_compilationMode(compilationMode)
    , m_functionIndex(functionIndex)
    , m_loopIndexForOSREntry(loopIndexForOSREntry)
    , m_inlining(inlining)
    , m_proc(procedure)
    , m_inlineRoot(this)
    , m_unlinkedWasmToWasmCalls(unlinkedWasmToWasmCalls)
    , m_directCallees(outgoingDirectCallees)
    , m_osrEntryScratchBufferSize(&osrEntryScratchBufferSize)
    , m_constantInsertionValues(m_proc)
    , m_hasExceptionHandlers(m_profiledCallee.hasExceptionHandlers())
    , m_numImportFunctions(info.importFunctionCount())
{
    m_topLevelBlock = m_proc.addBlock();
    m_rootBlocks.append(m_proc.addBlock());
    m_currentBlock = m_rootBlocks[0];

    // FIXME we don't really need to pin registers here if there's no memory. It makes wasm -> wasm thunks simpler for now. https://bugs.webkit.org/show_bug.cgi?id=166623

    m_proc.pinRegister(GPRInfo::wasmContextInstancePointer);
    m_proc.pinRegister(GPRInfo::wasmBaseMemoryPointer);
    if (mode == MemoryMode::BoundsChecking)
        m_proc.pinRegister(GPRInfo::wasmBoundsCheckingSizeRegister);

    if (info.memoryCount()) {
        m_proc.setWasmBoundsCheckGenerator([=, this](CCallHelpers& jit, WasmBoundsCheckValue* originValue, GPRReg pinnedGPR) {
            AllowMacroScratchRegisterUsage allowScratch(jit);
            switch (m_mode) {
            case MemoryMode::BoundsChecking:
                ASSERT_UNUSED(pinnedGPR, GPRInfo::wasmBoundsCheckingSizeRegister == pinnedGPR);
                break;
            case MemoryMode::Signaling:
                ASSERT_UNUSED(pinnedGPR, InvalidGPRReg == pinnedGPR);
                break;
            }
            this->emitExceptionCheck(jit, originValue->origin(), ExceptionType::OutOfBoundsMemoryAccess);
        });
    }

    {
        // FIXME: Because WasmToWasm call clobbers wasmContextInstance register and does not restore it, we need to restore it in the caller side.
        // This prevents us from using ArgumentReg to this (logically) immutable pinned register.

        B3::PatchpointValue* getInstance = m_topLevelBlock->appendNew<B3::PatchpointValue>(m_proc, pointerType(), Origin());
        getInstance->effects.writesPinned = false;
        getInstance->effects.readsPinned = true;
        getInstance->resultConstraints = { ValueRep::reg(GPRInfo::wasmContextInstancePointer) };
        getInstance->setGenerator([=] (CCallHelpers&, const B3::StackmapGenerationParams&) { });
        m_instanceValue = getInstance;
        m_vmValue = m_topLevelBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfVM()));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_vm, m_vmValue);
        m_vmValue->setControlDependent(false);
        m_vmValue->setReadsMutability(B3::Mutability::Immutable);

        if (m_info.memoryCount()) {
            if (useSignalingMemory0() || m_info.memory(0).isShared()) {
                // Capacity and basePointer will not be changed in this case.
                if (m_mode == MemoryMode::BoundsChecking) {
                    B3::PatchpointValue* getBoundsCheckingSize = m_topLevelBlock->appendNew<B3::PatchpointValue>(m_proc, pointerType(), Origin());
                    getBoundsCheckingSize->effects.writesPinned = false;
                    getBoundsCheckingSize->effects.readsPinned = true;
                    getBoundsCheckingSize->resultConstraints = { ValueRep::reg(GPRInfo::wasmBoundsCheckingSizeRegister) };
                    getBoundsCheckingSize->setGenerator([=] (CCallHelpers&, const B3::StackmapGenerationParams&) { });
                    m_boundsCheckingSizeValue = getBoundsCheckingSize;
                }
                B3::PatchpointValue* getBaseMemory = m_topLevelBlock->appendNew<B3::PatchpointValue>(m_proc, pointerType(), Origin());
                getBaseMemory->effects.writesPinned = false;
                getBaseMemory->effects.readsPinned = true;
                getBaseMemory->resultConstraints = { ValueRep::reg(GPRInfo::wasmBaseMemoryPointer) };
                getBaseMemory->setGenerator([=] (CCallHelpers&, const B3::StackmapGenerationParams&) { });
                m_baseMemoryValue = getBaseMemory;
            }
        }
    }

    m_prologueGenerator = createSharedTask<B3::Air::PrologueGeneratorFunction>([=, this] (CCallHelpers& jit, B3::Air::Code& code) {
        RELEASE_ASSERT(m_callee);
        AllowMacroScratchRegisterUsage allowScratch(jit);

        if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
            int fi = this->m_functionIndex;
            jit.probeDebug([fi] (Probe::Context& context) {
                dataLogLn(" General Before Prologue, fucntion ", fi, " FP: ", RawHex(context.gpr<uint64_t>(GPRInfo::callFrameRegister)), " SP: ", RawHex(context.gpr<uint64_t>(MacroAssembler::stackPointerRegister)));
            });
        }

        code.emitDefaultPrologue(jit);
        GPRReg scratchGPR = wasmCallingConvention().prologueScratchGPRs[0];
        jit.move(CCallHelpers::TrustedImmPtr(CalleeBits::boxNativeCallee(m_callee)), scratchGPR);
        static_assert(CallFrameSlot::codeBlock + 1 == CallFrameSlot::callee);
        jit.storePairPtr(GPRInfo::wasmContextInstancePointer, scratchGPR, GPRInfo::callFrameRegister, CCallHelpers::TrustedImm32(CallFrameSlot::codeBlock * sizeof(Register)));
    });
    {
        B3::PatchpointValue* stackOverflowCheck = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, Void, Origin());
        stackOverflowCheck->appendSomeRegister(instanceValue());
        stackOverflowCheck->appendSomeRegister(framePointer());
        stackOverflowCheck->clobber(RegisterSet::macroClobberedGPRs());
        stackOverflowCheck->numGPScratchRegisters = 0;
        stackOverflowCheck->setGenerator([=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
            ASSERT(m_proc.frameSize() == params.proc().frameSize());
            int32_t checkSize = 0;
            bool needsOverflowCheck = false;
            computeStackCheckSize(needsOverflowCheck, checkSize);
            ASSERT(checkSize || !needsOverflowCheck);

            // This allows leaf functions to not do stack checks if their frame size is within
            // certain limits since their caller would have already done the check.
            if (needsOverflowCheck) {
                AllowMacroScratchRegisterUsage allowScratch(jit);
                GPRReg contextInstance = params[0].gpr();
                GPRReg fp = params[1].gpr();
                if (m_compilationMode == CompilationMode::OMGForOSREntryMode)
                    jit.checkWasmStackOverflow(contextInstance, CCallHelpers::TrustedImm32(checkSize), fp).linkThunk(CodeLocationLabel<JITThunkPtrTag>(Thunks::singleton().stub(crashDueToOMGStackOverflowGenerator).code()), &jit);
                else {
                    auto failure = jit.checkWasmStackOverflow(contextInstance, CCallHelpers::TrustedImm32(checkSize), fp);
                    params.addLatePath(
                        [=](CCallHelpers& jit) {
                            failure.link(jit);
                            int32_t stackSpace = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(RegisterSet::calleeSaveRegisters().numberOfSetRegisters() * sizeof(Register));
                            ASSERT(static_cast<unsigned>(stackSpace) < Options::softReservedZoneSize());
                            jit.addPtr(CCallHelpers::TrustedImm32(-stackSpace), GPRInfo::callFrameRegister, MacroAssembler::stackPointerRegister);
                            jit.move(CCallHelpers::TrustedImm32(static_cast<uint32_t>(ExceptionType::StackOverflow)), GPRInfo::argumentGPR1);
                            jit.nearCallThunk(CodeLocationLabel<JITThunkPtrTag>(Thunks::singleton().stub(throwExceptionFromOMGThunkGenerator).code()));
                        });
                }
            }
        });
    }

    if (m_compilationMode == CompilationMode::OMGForOSREntryMode)
        m_currentBlock = m_proc.addBlock();
}

void OMGIRGenerator::restoreWebAssemblyGlobalState(const Vector<MemoryInformation>& memories, Value* instance, BasicBlock* block)
{
    restoreWasmContextInstance(block, instance);

    if (memories.size()) {
        if (useSignalingMemory0() || memories[0].isShared()) {
            RegisterSet clobbers;
            clobbers.add(GPRInfo::wasmBaseMemoryPointer, IgnoreVectors);
            if (m_mode == MemoryMode::BoundsChecking)
                clobbers.add(GPRInfo::wasmBoundsCheckingSizeRegister, IgnoreVectors);

            B3::PatchpointValue* patchpoint = block->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
            Effects effects = Effects::none();
            effects.writesPinned = true;
            effects.reads = B3::HeapRange::top();
            patchpoint->effects = effects;
            patchpoint->clobber(clobbers);

            patchpoint->append(baseMemoryValue(), ValueRep::SomeRegister);
            if (m_mode == MemoryMode::BoundsChecking)
                patchpoint->append(boundsCheckingSizeValue(), ValueRep::SomeRegister);
            patchpoint->setGenerator([](CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
                jit.move(params[0].gpr(), GPRInfo::wasmBaseMemoryPointer);
                if (params.size() == 2)
                    jit.move(params[1].gpr(), GPRInfo::wasmBoundsCheckingSizeRegister);
            });
            return;
        }

        reloadMemoryRegistersFromInstance(memories[0], instance, block);
    }
}

void OMGIRGenerator::reloadMemoryRegistersFromInstance(const MemoryInformation& memory, Value* instance, BasicBlock* block)
{
    if (!!memory) {
        RegisterSet clobbers;
        clobbers.add(GPRInfo::wasmBaseMemoryPointer, IgnoreVectors);
        clobbers.add(GPRInfo::wasmBoundsCheckingSizeRegister, IgnoreVectors);
        clobbers.merge(RegisterSet::macroClobberedGPRs());

        B3::PatchpointValue* patchpoint = block->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        Effects effects = Effects::none();
        effects.writesPinned = true;
        effects.reads = B3::HeapRange::top();
        patchpoint->effects = effects;
        patchpoint->clobber(clobbers);
        patchpoint->numGPScratchRegisters = 1;

        patchpoint->append(instance, ValueRep::SomeRegister);
        patchpoint->setGenerator([](CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
            AllowMacroScratchRegisterUsage allowScratch(jit);
            GPRReg scratch = params.gpScratch(0);
            jit.loadPairPtr(params[0].gpr(), CCallHelpers::TrustedImm32(JSWebAssemblyInstance::offsetOfCachedMemoryBaseSizePair(0)), GPRInfo::wasmBaseMemoryPointer, GPRInfo::wasmBoundsCheckingSizeRegister);
            jit.cageConditionally(Gigacage::Primitive, GPRInfo::wasmBaseMemoryPointer, GPRInfo::wasmBoundsCheckingSizeRegister, scratch);
        });
    }
}

void OMGIRGenerator::emitExceptionCheck(CCallHelpers& jit, Origin, ExceptionType type)
{
    jit.move(CCallHelpers::TrustedImm32(static_cast<uint32_t>(type)), GPRInfo::argumentGPR1);
    jit.nearCallThunk(CodeLocationLabel<JITThunkPtrTag>(Thunks::singleton().stub(throwExceptionFromOMGThunkGenerator).code()));
}

Value* OMGIRGenerator::constant(B3::Type type, uint64_t bits, std::optional<Origin> maybeOrigin)
{
    auto result = m_constantPool.ensure(ValueKey(opcodeForConstant(type), type, static_cast<int64_t>(bits)), [&] {
        Value* result = nullptr;
        if (type.kind() == B3::V128) {
            v128_t vector { };
            vector.u64x2[0] = bits;
            vector.u64x2[1] = 0;
            result = m_proc.addConstant(maybeOrigin ? *maybeOrigin : origin(), type, vector);
        } else
            result = m_proc.addConstant(maybeOrigin ? *maybeOrigin : origin(), type, bits);
        m_constantInsertionValues.insertValue(0, result);
        return result;
    });
    return result.iterator->value;
}

Value* OMGIRGenerator::constant(B3::Type type, v128_t bits, std::optional<Origin> maybeOrigin)
{
    Value* result = m_proc.addConstant(maybeOrigin ? *maybeOrigin : origin(), type, bits);
    m_constantInsertionValues.insertValue(0, result);
    return result;
}

Value* OMGIRGenerator::framePointer()
{
    if (!m_framePointer) {
        m_framePointer = m_proc.add<B3::Value>(B3::FramePointer, Origin());
        ASSERT(m_framePointer);
        m_constantInsertionValues.insertValue(0, m_framePointer);
    }
    return m_framePointer;
}

void OMGIRGenerator::insertEntrySwitch()
{
    m_proc.setNumEntrypoints(m_rootBlocks.size());

    Ref<B3::Air::PrologueGenerator> catchPrologueGenerator = createSharedTask<B3::Air::PrologueGeneratorFunction>([] (CCallHelpers& jit, B3::Air::Code& code) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        jit.addPtr(CCallHelpers::TrustedImm32(-code.frameSize()), GPRInfo::callFrameRegister, CCallHelpers::stackPointerRegister);
        jit.probe(tagCFunction<JITProbePtrTag>(buildEntryBufferForCatch), nullptr);
    });

    m_proc.code().setPrologueForEntrypoint(0, Ref<B3::Air::PrologueGenerator>(*m_prologueGenerator));
    for (unsigned i = 1; i < m_rootBlocks.size(); ++i)
        m_proc.code().setPrologueForEntrypoint(i, catchPrologueGenerator.copyRef());

    m_currentBlock = m_topLevelBlock;
    m_currentBlock->appendNew<Value>(m_proc, EntrySwitch, Origin());
    for (auto block : m_rootBlocks)
        m_currentBlock->appendSuccessor(FrequentedBlock(block));
}

void OMGIRGenerator::insertConstants()
{
    m_constantInsertionValues.execute(m_proc.at(0));
}

B3::Type OMGIRGenerator::toB3ResultType(const RTT* returnType)
{
    if (returnType->returnsVoid())
        return B3::Void;

    if (returnType->returnCount() == 1)
        return toB3Type(returnType->returnType(0));

    auto result = m_tupleMap.ensure(returnType, [&] {
        Vector<B3::Type> result;
        for (unsigned i = 0; i < returnType->returnCount(); ++i)
            result.append(toB3Type(returnType->returnType(i)));
        return m_proc.addTuple(WTF::move(result));
    });
    return result.iterator->value;
}

B3::Type OMGIRGenerator::int64PairTupleType()
{
    if (m_int64PairTupleType == B3::Void)
        m_int64PairTupleType = m_proc.addTuple({ B3::Int64, B3::Int64 });
    return m_int64PairTupleType;
}

auto OMGIRGenerator::addLocal(Type type, uint32_t count) -> PartialResult
{
    size_t newSize = m_locals.size() + count;
    ASSERT(!(CheckedUint32(count) + m_locals.size()).hasOverflowed());
    ASSERT(newSize <= maxFunctionLocals);
    WASM_COMPILE_FAIL_IF(!m_locals.tryReserveCapacity(newSize), "can't allocate memory for "_s, newSize, " locals"_s);

    m_locals.appendUsingFunctor(count, [&](size_t) {
        Variable* local = m_proc.addVariable(toB3Type(type));
        if (type.isV128())
            m_currentBlock->appendNew<VariableValue>(m_proc, Set, Origin(), local, constant(toB3Type(type), v128_t { }, Origin()));
        else {
            auto val = isRefType(type) ? JSValue::encode(jsNull()) : 0;
            m_currentBlock->appendNew<VariableValue>(m_proc, Set, Origin(), local, constant(toB3Type(type), val, Origin()));
        }
        return local;
    });
    return { };
}

auto OMGIRGenerator::addDrop(ExpressionType) -> PartialResult
{
    return { };
}

auto OMGIRGenerator::addInlinedArguments(const RTT& functionSignature) -> PartialResult
{
    RELEASE_ASSERT(functionSignature.argumentCount() == m_inlinedArgs.size());
    CallInformation wasmCallInfo = wasmCallingConvention().callInformationFor(functionSignature, CallRole::Callee);

    for (size_t i = 0; i < functionSignature.argumentCount(); ++i) {
        B3::Type type = toB3Type(functionSignature.argumentType(i));
        Value* value = m_inlinedArgs[i];
        RELEASE_ASSERT(value->type() == type);

        Variable* argumentVariable = m_proc.addVariable(type);
        m_locals[i] = argumentVariable;
        m_currentBlock->appendNew<VariableValue>(m_proc, Set, Origin(), argumentVariable, value);
    }

    return { };
}

auto OMGIRGenerator::addArguments(const RTT& signature) -> PartialResult
{
    const RTT* functionSignature = &signature;
    ASSERT(!m_locals.size());
    WASM_COMPILE_FAIL_IF(!m_locals.tryReserveCapacity(functionSignature->argumentCount()), "can't allocate memory for "_s, functionSignature->argumentCount(), " arguments"_s);

    m_locals.grow(functionSignature->argumentCount());

    if (m_inlineParent)
        return addInlinedArguments(signature);

    CallInformation wasmCallInfo = wasmCallingConvention().callInformationFor(signature, CallRole::Callee);

    if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
        PatchpointValue* patch = m_proc.add<PatchpointValue>(B3::Void, Origin());
        patch->effects = Effects::none();
        patch->effects.controlDependent = true;
        patch->effects.fence = true;
        patch->effects.reads = HeapRange::top();
        patch->effects.writes = HeapRange::top();
        m_currentBlock->append(patch);
        SUPPRESS_UNCOUNTED_LAMBDA_CAPTURE patch->setGenerator([functionIndex = m_functionIndex, functionSignature, wasmCallInfo](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            SUPPRESS_UNCOUNTED_LAMBDA_CAPTURE jit.probeDebug([functionIndex, functionSignature, wasmCallInfo](Probe::Context& context) {
                dataLogLn(" General Add arguments, fucntion ", functionIndex, " FP: ", RawHex(context.gpr<uint64_t>(GPRInfo::callFrameRegister)), " SP: ", RawHex(context.gpr<uint64_t>(MacroAssembler::stackPointerRegister)));

                auto fpl = context.gpr<uint64_t*>(GPRInfo::callFrameRegister);
                auto fpi = context.gpr<uint32_t*>(GPRInfo::callFrameRegister);

                for (size_t i = 0; i < functionSignature->argumentCount(); ++i) {
                    auto rep = wasmCallInfo.params[i];
                    auto src = rep.location;
                    auto width = rep.width;
                    dataLog("     Arg source ", i, " located at ", src, " = ");

                    if (src.isGPR())
                        dataLog(context.gpr(src.jsr().payloadGPR()), " / ", (int) context.gpr(src.jsr().payloadGPR()));
                    else if (src.isFPR() && width <= Width::Width64)
                        dataLog(context.fpr(src.fpr()));
                    else if (src.isFPR())
                        dataLog(context.vector(src.fpr()));
                    else
                        dataLog(fpl[src.offsetFromFP() / sizeof(uint64_t)], " / ", fpi[src.offsetFromFP() / sizeof(uint32_t)],  " / ", RawHex(fpi[src.offsetFromFP() / sizeof(uint32_t)]), " / ", std::bit_cast<double>(fpl[src.offsetFromFP() / sizeof(uint64_t)]), " at ", RawPointer(&fpi[src.offsetFromFP() / sizeof(uint32_t)]));
                    dataLogLn();
                }
            });
        });
    }

    for (size_t i = 0; i < functionSignature->argumentCount(); ++i) {
        B3::Type type = toB3Type(functionSignature->argumentType(i));
        B3::Value* argument;
        auto rep = wasmCallInfo.params[i];
        if (rep.location.isGPR()) {
            argument = m_currentBlock->appendNew<B3::ArgumentRegValue>(m_proc, Origin(), rep.location.jsr().payloadGPR());
            if (type == B3::Int32)
                argument = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Trunc, Origin(), argument);
        } else if (rep.location.isFPR()) {
            if (type.isVector()) {
                ASSERT(rep.width == Width128);
                argument = m_currentBlock->appendNew<B3::ArgumentRegValue>(m_proc, Origin(), rep.location.fpr(), B3::ArgumentRegValue::UsesVectorArgs);
            } else {
                ASSERT(rep.width != Width128);
                argument = m_currentBlock->appendNew<B3::ArgumentRegValue>(m_proc, Origin(), rep.location.fpr());
            }
            if (type == B3::Float)
                argument = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Trunc, Origin(), argument);
        } else {
            ASSERT(rep.location.isStack());
            B3::Value* address = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Add, Origin(), framePointer(),
                m_currentBlock->appendNew<B3::ConstPtrValue>(m_proc, Origin(), rep.location.offsetFromFP()));
            argument = m_currentBlock->appendNew<B3::MemoryValue>(m_proc, B3::Load, type, Origin(), address);
        }

        Variable* argumentVariable = m_proc.addVariable(argument->type());
        m_locals[i] = argumentVariable;
        m_currentBlock->appendNew<VariableValue>(m_proc, Set, Origin(), argumentVariable, argument);
    }

    return { };
}

auto OMGIRGenerator::addRefIsNull(ExpressionType value, ExpressionType& result) -> PartialResult
{
    result = push(m_currentBlock->appendNew<Value>(m_proc, B3::Equal, origin(), get(value), m_currentBlock->appendNew<WasmConstRefValue>(m_proc, origin(), JSValue::encode(jsNull()))));
    return { };
}

auto OMGIRGenerator::addTableGet(unsigned tableIndex, ExpressionType index, ExpressionType& result) -> PartialResult
{
    // FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::Externref), operationGetWasmTableElement,
        instanceValue(), constant(Int32, tableIndex), get(index));
    {
        result = push(resultValue);
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, m_currentBlock->appendNew<WasmConstRefValue>(m_proc, origin(), 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTableAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::addTableSet(unsigned tableIndex, ExpressionType index, ExpressionType value) -> PartialResult
{
    // FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
    auto shouldThrow = callWasmOperation(m_currentBlock, B3::Int32, operationSetWasmTableElement,
        instanceValue(), constant(Int32, tableIndex), get(index), get(value));
    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), shouldThrow, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTableAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::addRefFunc(FunctionSpaceIndex index, ExpressionType& result) -> PartialResult
{
    // FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
    result = push(callWasmOperation(m_currentBlock, wasmRefType(), operationWasmRefFunc,
        instanceValue(), constant(toB3Type(Types::I32), index)));
    TRACE_VALUE(Wasm::Types::Funcref, get(result), "ref_func ", index);
    return { };
}

auto OMGIRGenerator::addRefAsNonNull(TypedExpression reference, ExpressionType& result) -> PartialResult
{
    auto value = get(reference);
    result = push(value);
    if (reference.type().isNullable())
        emitNullCheck(value, ExceptionType::NullRefAsNonNull);
    return { };
}

auto OMGIRGenerator::addRefEq(ExpressionType ref0, ExpressionType ref1, ExpressionType& result) -> PartialResult
{
    return addI64Eq(ref0, ref1, result);
}

auto OMGIRGenerator::addTableInit(unsigned elementIndex, unsigned tableIndex, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length) -> PartialResult
{
    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmTableInit,
        instanceValue(),
        constant(Int32, elementIndex),
        constant(Int32, tableIndex),
        get(dstOffset), get(srcOffset), get(length));

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTableAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::addElemDrop(unsigned elementIndex) -> PartialResult
{
    callWasmOperation(m_currentBlock, B3::Void, operationWasmElemDrop,
        instanceValue(),
        constant(Int32, elementIndex));

    return { };
}

auto OMGIRGenerator::addTableSize(unsigned tableIndex, ExpressionType& result) -> PartialResult
{
    // FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
    result = push(callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationGetWasmTableSize,
        instanceValue(), constant(Int32, tableIndex)));

    return { };
}

auto OMGIRGenerator::addTableGrow(unsigned tableIndex, ExpressionType fill, ExpressionType delta, ExpressionType& result) -> PartialResult
{
    result = push(callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmTableGrow,
        instanceValue(), constant(Int32, tableIndex), get(fill), get(delta)));

    return { };
}

auto OMGIRGenerator::addTableFill(unsigned tableIndex, ExpressionType offset, ExpressionType fill, ExpressionType count) -> PartialResult
{
    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmTableFill,
        instanceValue(), constant(Int32, tableIndex), get(offset), get(fill), get(count));

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTableAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::addTableCopy(unsigned dstTableIndex, unsigned srcTableIndex, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length) -> PartialResult
{
    Value* resultValue = callWasmOperation(
        m_currentBlock, toB3Type(Types::I32), operationWasmTableCopy,
        instanceValue(),
        constant(Int32, dstTableIndex),
        constant(Int32, srcTableIndex),
        get(dstOffset), get(srcOffset), get(length));

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTableAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::getLocal(uint32_t index, ExpressionType& result) -> PartialResult
{
    ASSERT(m_locals[index]);
    result = push(m_currentBlock->appendNew<VariableValue>(m_proc, B3::Get, origin(), m_locals[index]));
    TRACE_VALUE(m_parser->typeOfLocal(index), get(result), "get_local ", index);
    return { };
}

auto OMGIRGenerator::addUnreachable() -> PartialResult
{
    B3::PatchpointValue* unreachable = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
    unreachable->setGenerator([this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::Unreachable);
    });
    unreachable->effects.terminal = true;
    return { };
}

auto OMGIRGenerator::addCrash() -> PartialResult
{
    B3::PatchpointValue* unreachable = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
    unreachable->setGenerator([] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
        jit.breakpoint();
    });
    unreachable->effects.terminal = true;
    return { };
}

void OMGIRGenerator::fillCallResults(Value* callResult, const RTT& signature, ValueResults& results)
{
    B3::Type returnType = toB3ResultType(&signature);
    ASSERT(returnType == callResult->type());

    switch (returnType.kind()) {
    case B3::Void: {
        break;
    }
    case B3::Tuple: {
        const Vector<B3::Type>& tuple = m_proc.tupleForType(returnType);
        ASSERT(signature.returnCount() == tuple.size());
        for (unsigned i = 0; i < signature.returnCount(); ++i)
            results.append(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), tuple[i], callResult, i));
        break;
    }
    default: {
        results.append(callResult);
        break;
    }
    }
}


// After a wasm call returns, move stack results from the callee's SP-relative
// convention offsets to wherever B3 placed them (register or FP-relative slot),
// then restore SP to cfr - frameSize.
static void emitWasmCallStackResultsAndSPRestore(CCallHelpers& jit,
    const B3::StackmapGenerationParams& params,
    const RTT& signature,
    const CallInformation& wasmCalleeInfo)
{
    auto frameSize = params.code().frameSize();

    for (unsigned i = 0; i < wasmCalleeInfo.results.size(); ++i) {
        auto& loc = wasmCalleeInfo.results[i];
        if (!loc.location.isStackArgument())
            continue;

        auto src = CCallHelpers::Address(MacroAssembler::stackPointerRegister, loc.location.offsetFromSP());
        auto& rep = params[i];

        auto wasmType = signature.returnType(i);
        if (rep.isGPR()) {
            if (wasmType.isI32())
                jit.load32(src, rep.gpr());
            else
                jit.load64(src, rep.gpr());
        } else if (rep.isFPR()) {
            if (wasmType.isF32())
                jit.loadFloat(src, rep.fpr());
            else if (wasmType.isF64())
                jit.loadDouble(src, rep.fpr());
            else {
                ASSERT(wasmType.isV128());
                jit.loadVector(src, rep.fpr());
            }
        } else {
            ASSERT(rep.isStack());
            if (wasmType.isV128())
                jit.transferVector(src, CCallHelpers::Address(GPRInfo::callFrameRegister, rep.offsetFromFP()));
            else
                jit.transfer64(src, CCallHelpers::Address(GPRInfo::callFrameRegister, rep.offsetFromFP()));
        }
    }

    jit.addPtr(CCallHelpers::TrustedImm32(-frameSize), GPRInfo::callFrameRegister, MacroAssembler::stackPointerRegister);
}

auto OMGIRGenerator::emitIndirectCall(Value* calleeInstance, Value* calleeCode, Value* boxedCalleeCallee, const RTT& signature, const ArgumentList& args, ValueResults& results, CallType callType) -> PartialResult
{
    const bool isTailCallRootCaller = callType == CallType::TailCall && !m_inlineParent;

    m_makesCalls = true;
    if (callType == CallType::TailCall)
        m_makesTailCalls = true;

    const auto& callingConvention = wasmCallingConvention();
    CallInformation wasmCalleeInfo = callingConvention.callInformationFor(signature, CallRole::Caller);
    CallInformation wasmCalleeInfoAsCallee = callingConvention.callInformationFor(signature, CallRole::Callee);
    Checked<int32_t> calleeStackSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCalleeInfo.headerAndArgumentStackSizeInBytes);
    if (isTailCallRootCaller)
        calleeStackSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCalleeInfo.headerAndArgumentStackSizeInBytes * 2 + sizeof(Register));

    m_proc.requestCallArgAreaSizeInBytes(calleeStackSize);

    // Tail call patchpoint is emitted before the B3-level context switch so
    // wasmContextInstancePointer still holds the caller's instance.
    if (isTailCallRootCaller) {
        const TypeSignatureIndex callerTypeSignatureIndex = m_info.internalFunctionTypeSignatureIndices[m_functionIndex];
        const RTT& callerType = m_info.rtt(callerTypeSignatureIndex);
        CallInformation wasmCallerInfoAsCallee = callingConvention.callInformationFor(callerType, CallRole::Callee);

        auto [patchpoint, _, prepareForCall] = createTailCallPatchpoint(m_currentBlock, signature, wasmCallerInfoAsCallee, wasmCalleeInfoAsCallee, args, boxedCalleeCallee);
        unsigned patchArgsIndex = patchpoint->reps().size();
        patchpoint->append(calleeCode, ValueRep(GPRInfo::nonPreservedNonArgumentGPR0));
        patchpoint->append(calleeInstance, ValueRep::SomeRegister);
        // Cross-instance setup below reloads pinned registers before the tail-call shuffle consumes late inputs.
        patchpoint->clobberLate(RegisterSet::wasmPinnedRegisters());
        // emitRestoreInstanceFrameIfNeeded needs two scratches. wasmBaseMemoryPointer is
        // always pinned so B3 won't allocate it. wasmBoundsCheckingSizeRegister
        // is only pinned in BoundsChecking mode, so in Signaling mode we need B3 to give us a
        // scratch that avoids the inputs.
        if (m_mode == MemoryMode::Signaling)
            patchpoint->numGPScratchRegisters = 1;
        patchArgsIndex += m_proc.resultCount(patchpoint->type());
        Checked<int32_t> callerStackSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCallerInfoAsCallee.headerAndArgumentStackSizeInBytes);
        patchpoint->setGenerator([prepareForCall = prepareForCall, patchArgsIndex, callerStackSize = static_cast<int32_t>(callerStackSize), mode = m_mode](CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
            GPRReg calleeInstanceGPR = params[patchArgsIndex + 1].gpr();
            GPRReg scratch2 = mode == MemoryMode::Signaling ? params.gpScratch(0) : GPRInfo::wasmBoundsCheckingSizeRegister;
            auto sameInstance = jit.branchPtr(CCallHelpers::Equal, calleeInstanceGPR, GPRInfo::wasmContextInstancePointer);
            {
                AllowMacroScratchRegisterUsage allowScratch(jit);
                int32_t topSource = -static_cast<int32_t>(params.code().frameSize());
                for (unsigned i = 0; i < params.size(); ++i) {
                    if (params[i].isStack())
                        topSource = std::max(topSource, params[i].offsetFromFP() + static_cast<int32_t>(sizeof(Register)));
                }
                for (const auto& entry : params.code().calleeSaveRegisterAtOffsetList())
                    topSource = std::max<int32_t>(topSource, entry.offset() + entry.byteSize());
                Checked<int32_t> topSourceOffsetFromFP = static_cast<int32_t>(roundUpToMultipleOf<stackAlignmentBytes()>(topSource));
                emitRestoreInstanceFrameIfNeeded(jit, GPRInfo::wasmContextInstancePointer, callerStackSize, params.code().frameSize(), topSourceOffsetFromFP, GPRInfo::wasmBaseMemoryPointer, scratch2);
                jit.move(calleeInstanceGPR, GPRInfo::wasmContextInstancePointer);
                jit.loadPairPtr(GPRInfo::wasmContextInstancePointer, CCallHelpers::TrustedImm32(JSWebAssemblyInstance::offsetOfCachedMemoryBaseSizePair(0)), GPRInfo::wasmBaseMemoryPointer, GPRInfo::wasmBoundsCheckingSizeRegister);
                jit.cageConditionally(Gigacage::Primitive, GPRInfo::wasmBaseMemoryPointer, GPRInfo::wasmBoundsCheckingSizeRegister, calleeInstanceGPR);
            }
            sameInstance.link(&jit);
            prepareForCall->run(jit, params);
            AllowMacroScratchRegisterUsage allowScratch(jit);
            jit.farJump(params[patchArgsIndex].gpr(), WasmEntryPtrTag);
        });
        return { };
    }

    // Do a context switch if needed.
    {
        BasicBlock* continuation = m_proc.addBlock();
        BasicBlock* doContextSwitch = m_proc.addBlock();

        Value* isSameContextInstance = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(),
            calleeInstance, instanceValue());
        m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(),
            isSameContextInstance, FrequentedBlock(continuation), FrequentedBlock(doContextSwitch));

        PatchpointValue* patchpoint = doContextSwitch->appendNew<PatchpointValue>(m_proc, B3::Void, origin());
        patchpoint->effects.writesPinned = true;
        // We pessimistically assume we're calling something with BoundsChecking memory.
        // FIXME: We shouldn't have to do this: https://bugs.webkit.org/show_bug.cgi?id=172181
        patchpoint->clobber(RegisterSet::wasmPinnedRegisters());
        patchpoint->clobber(RegisterSet::macroClobberedGPRs());
        patchpoint->append(calleeInstance, ValueRep::SomeRegister);
        patchpoint->numGPScratchRegisters = 1;

        patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
            AllowMacroScratchRegisterUsage allowScratch(jit);
            GPRReg calleeInstance = params[0].gpr();
            ASSERT(calleeInstance != GPRInfo::wasmBaseMemoryPointer);
            jit.storeWasmContextInstance(calleeInstance);
            static_assert(GPRInfo::wasmBoundsCheckingSizeRegister != GPRInfo::wasmBaseMemoryPointer);
            // FIXME: We should support more than one memory size register
            //   see: https://bugs.webkit.org/show_bug.cgi?id=162952
            ASSERT(GPRInfo::wasmBoundsCheckingSizeRegister != calleeInstance);
            GPRReg scratch = params.gpScratch(0);
            jit.loadPairPtr(calleeInstance, CCallHelpers::TrustedImm32(JSWebAssemblyInstance::offsetOfCachedMemoryBaseSizePair(0)), GPRInfo::wasmBaseMemoryPointer, GPRInfo::wasmBoundsCheckingSizeRegister);
            jit.cageConditionally(Gigacage::Primitive, GPRInfo::wasmBaseMemoryPointer, GPRInfo::wasmBoundsCheckingSizeRegister, scratch);
        });
        doContextSwitch->appendNewControlValue(m_proc, Jump, origin(), continuation);

        m_currentBlock = continuation;
    }

    auto [patchpoint, handle, prepareForCall] = createCallPatchpoint(m_currentBlock, signature, wasmCalleeInfo, args);
    // We need to clobber all potential pinned registers since we might be leaving the instance.
    // We pessimistically assume we're always calling something that is bounds checking so
    // because the wasm->wasm thunk unconditionally overrides the size registers.
    // FIXME: We should not have to do this, but the wasm->wasm stub assumes it can
    // use all the pinned registers as scratch: https://bugs.webkit.org/show_bug.cgi?id=172181
    patchpoint->clobberLate(RegisterSet::wasmPinnedRegisters());

    unsigned patchArgsIndex = patchpoint->reps().size();
    patchpoint->append(calleeCode, ValueRep::SomeRegister);
    patchpoint->append(boxedCalleeCallee, ValueRep::SomeRegister);
    patchArgsIndex += m_proc.resultCount(patchpoint->type());
    patchpoint->setGenerator([this, handle = handle, prepareForCall = prepareForCall, patchArgsIndex, signature = Ref<const RTT>(signature), wasmCalleeInfo = WTF::move(wasmCalleeInfo)](CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        if (prepareForCall)
            prepareForCall->run(jit, params);
        if (handle)
            handle->collectStackMap(this, params);

        jit.storeWasmCalleeToCalleeCallFrame(params[patchArgsIndex + 1].gpr());
        jit.call(params[patchArgsIndex].gpr(), WasmEntryPtrTag);
        emitWasmCallStackResultsAndSPRestore(jit, params, signature, wasmCalleeInfo);
    });
    fillCallResults(patchpoint, signature, results);

    // The call could have been to another WebAssembly instance, and / or could have modified our Memory.
    restoreWebAssemblyGlobalState(m_info.memories, instanceValue(), m_currentBlock);
    return { };
}

auto OMGIRGenerator::addGrowMemory(ExpressionType delta, ExpressionType& result, uint8_t memoryIndex) -> PartialResult
{
    result = push(callWasmOperation(m_currentBlock, m_info.memory(memoryIndex).addressType().asB3TypeKind(), operationGrowMemory,
        instanceValue(), get(delta), constant(Int32, memoryIndex)));

    restoreWebAssemblyGlobalState(m_info.memories, instanceValue(), m_currentBlock);

    return { };
}

auto OMGIRGenerator::addCurrentMemory(ExpressionType& result, uint8_t memoryIndex) -> PartialResult
{
    if (!memoryIndex) {
        static_assert(sizeof(std::declval<Memory*>()->size()) == sizeof(uintptr_t), "codegen relies on this size");

        Value* size = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfCachedMemory0Size()));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_cachedMemory0Size, size);

        constexpr uint32_t shiftValue = 16;
        static_assert(PageCount::pageSize == 1ull << shiftValue, "This must hold for the code below to be correct.");
        Value* numPages = m_currentBlock->appendNew<Value>(m_proc, ZShr, origin(), size, constant(Int32, shiftValue));

        if (m_info.memory(memoryIndex).isMemory64())
            result = push(numPages);
        else
            result = push(int32OfPointer(numPages));
    } else {
        Value* resultValue = callWasmOperation(m_currentBlock, m_info.memory(memoryIndex).addressType().asB3TypeKind(), operationWasmMemorySizeInPages,
            instanceValue(), constant(Int32, memoryIndex));
        result = push(resultValue);
    }

    return { };
}

auto OMGIRGenerator::addMemoryFill(ExpressionType dstAddress, ExpressionType target, ExpressionType count, uint8_t memoryIndex) -> PartialResult
{
    auto* dstAddressValue = m_info.memory(memoryIndex).isMemory64()
        ? get(dstAddress)
        : m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), get(dstAddress));
    auto* targetValue = get(target);
    auto* countValue = m_info.memory(memoryIndex).isMemory64()
        ? get(count)
        : m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), get(count));

    if (!memoryIndex) {
        auto* memorySize = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfCachedMemory0Size()));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_cachedMemory0Size, memorySize);

        auto* sum = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), dstAddressValue, countValue);
        auto* sumOverflowed = m_currentBlock->appendNew<Value>(m_proc, Below, origin(), sum, dstAddressValue);
        Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitOr, origin(), sumOverflowed, m_currentBlock->appendNew<Value>(m_proc, Above, origin(), sum, memorySize));
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
        check->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });

        m_currentBlock->appendNew<BulkMemoryValue>(
            m_proc, MemoryFill, origin(),
            m_currentBlock->appendNew<WasmAddressValue>(m_proc, origin(), dstAddressValue, GPRInfo::wasmBaseMemoryPointer),
            targetValue,
            countValue);
    } else {
        Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmMemoryFill,
            instanceValue(), dstAddressValue, targetValue, countValue, constant(Int32, memoryIndex));

        {
            CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
                m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

            check->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
                this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
            });
        }
    }

    return { };
}

auto OMGIRGenerator::addMemoryInit(unsigned dataSegmentIndex, ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType length, uint8_t memoryIndex) -> PartialResult
{
    auto dstAddressValue = m_info.memory(memoryIndex).isMemory64()
        ? get(dstAddress)
        : m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), get(dstAddress));

    auto srcAddressValue = m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), get(srcAddress));

    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmMemoryInit,
        instanceValue(),
        constant(Int32, dataSegmentIndex),
        dstAddressValue, srcAddressValue, get(length), constant(Int32, memoryIndex));

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::addMemoryCopy(ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType count, uint8_t dstMemoryIndex, uint8_t srcMemoryIndex) -> PartialResult
{
    auto* dstAddressValue = m_info.memory(dstMemoryIndex).isMemory64()
        ? get(dstAddress)
        : m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), get(dstAddress));
    auto* srcAddressValue = m_info.memory(srcMemoryIndex).isMemory64()
        ? get(srcAddress)
        : m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), get(srcAddress));
    auto* countValue = m_info.memory(srcMemoryIndex).isMemory64() && m_info.memory(dstMemoryIndex).isMemory64()
        ? get(count)
        : m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), get(count));

    if (!dstMemoryIndex && !srcMemoryIndex) {
        auto* memorySize = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfCachedMemory0Size()));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_cachedMemory0Size, memorySize);
        {
            auto* dstSum = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), dstAddressValue, countValue);
            auto* dstSumOverflowed = m_currentBlock->appendNew<Value>(m_proc, Below, origin(), dstSum, dstAddressValue);
            Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitOr, origin(), dstSumOverflowed, m_currentBlock->appendNew<Value>(m_proc, Above, origin(), dstSum, memorySize));
            CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
            check->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
                this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
            });
        }
        {
            auto* srcSum = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), srcAddressValue, countValue);
            auto* srcSumOverflowed = m_currentBlock->appendNew<Value>(m_proc, Below, origin(), srcSum, srcAddressValue);
            Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitOr, origin(), srcSumOverflowed, m_currentBlock->appendNew<Value>(m_proc, Above, origin(), srcSum, memorySize));
            CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
            check->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
                this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
            });
        }

        m_currentBlock->appendNew<BulkMemoryValue>(
            m_proc, MemoryCopy, origin(),
            m_currentBlock->appendNew<WasmAddressValue>(m_proc, origin(), dstAddressValue, GPRInfo::wasmBaseMemoryPointer),
            m_currentBlock->appendNew<WasmAddressValue>(m_proc, origin(), srcAddressValue, GPRInfo::wasmBaseMemoryPointer),
            countValue);
    } else {
        Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmMemoryCopy,
            instanceValue(),
            dstAddressValue, srcAddressValue, countValue, constant(Int32, dstMemoryIndex), constant(Int32, srcMemoryIndex));

        {
            CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
                m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

            check->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
                this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
            });
        }
    }

    return { };
}

auto OMGIRGenerator::addDataDrop(unsigned dataSegmentIndex) -> PartialResult
{
    callWasmOperation(m_currentBlock, B3::Void, operationWasmDataDrop,
        instanceValue(),
        constant(Int32, dataSegmentIndex));

    return { };
}

template<typename... Args>
void OMGIRGenerator::traceValue(Type type, Value* value, Args&&... info)
{
    if constexpr (!WasmOMGIRGeneratorInternal::traceExecution)
        return;
    if (!type.isFuncref() && !type.isVoid())
        return;
    auto* patch = m_proc.add<PatchpointValue>(B3::Void, origin());
    patch->effects = Effects::none();
    patch->effects.controlDependent = true;
    patch->effects.fence = true;
    patch->effects.reads = HeapRange::top();
    patch->effects.writes = HeapRange::top();
    StringPrintStream sb;
    if (m_parser->unreachableBlocks())
        sb.print("(unreachable) ");
    sb.print("TRACE OMG EXECUTION fn[", m_functionIndex, "] stack height ", m_parser->expressionStack().size(), " type ", type, " ");
    sb.print(info...);
    dataLogLn("static: ", sb.toString());
    patch->setGenerator([infoString = sb.toString(), type] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        JIT_COMMENT(jit, "PROBE FOR ", infoString);
        jit.probeDebug([params, type, infoString](Probe::Context& ctx) {
            auto rep = params[0];
            uint64_t rawVal = 0;
            ASSERT(rep.isGPR() || rep.isFPR());
            if (rep.isGPR())
                rawVal = ctx.gpr(rep.gpr());
            else if (rep.isFPR())
                rawVal = ctx.fpr(rep.fpr());
            else if (rep.isConstant())
                rawVal = rep.value();

            dataLogLn(infoString, " = ", rawVal);

            if (type.isVoid() || !rawVal)
                return;

            JSValue jsValue = JSValue::decode(rawVal);
            RELEASE_ASSERT(jsValue.isCallable() || jsValue.isUndefinedOrNull());
        });
    });
    patch->append(ConstrainedValue(value, ValueRep::SomeRegister));
    m_currentBlock->append(patch);
}

template<typename... Args>
void OMGIRGenerator::traceCF(Args&&... info)
{
    if constexpr (!WasmOMGIRGeneratorInternal::traceExecution)
        return;
    auto* patch = m_proc.add<PatchpointValue>(B3::Void, origin());
    patch->effects = Effects::none();
    patch->effects.controlDependent = true;
    patch->effects.fence = true;
    patch->effects.reads = HeapRange::top();
    patch->effects.writes = HeapRange::top();
    StringPrintStream sb;
    sb.print("TRACE OMG EXECUTION fn[", m_functionIndex, " <inlined into ", m_inlineParent ? m_inlineParent->m_functionIndex : -1, ">] stack height ", m_parser->expressionStack().size(), " CF ");
    sb.print(info...);
    dataLogLn("static: ", sb.toString());
    patch->setGenerator([infoString = sb.toString()] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        JIT_COMMENT(jit, "PROBE FOR ", infoString);
        jit.probeDebug([params, infoString](Probe::Context&) {
            dataLogLn(infoString);
        });
    });
    m_currentBlock->append(patch);

    if (!WasmOMGIRGeneratorInternal::traceStackValues)
        return;
    int i = 0;
    for (auto val : m_parser->expressionStack()) {
        ++i;
        traceValue(Wasm::Types::Void, get(val.value()), " parser stack[", i, "] = ", val.value());
    }

    if (m_parser->unreachableBlocks())
        return;
}

auto OMGIRGenerator::setLocal(uint32_t index, ExpressionType value) -> PartialResult
{
    ASSERT(m_locals[index]);
    m_currentBlock->appendNew<VariableValue>(m_proc, B3::Set, origin(), m_locals[index], get(value));
    TRACE_VALUE(m_parser->typeOfLocal(index), get(value), "set_local ", index);
    return { };
}

auto OMGIRGenerator::teeLocal(uint32_t index, ExpressionType value, ExpressionType& result) -> PartialResult
{
    ASSERT(m_locals[index]);
    Value* input = get(value);
    m_currentBlock->appendNew<VariableValue>(m_proc, B3::Set, origin(), m_locals[index], input);
    result = push(input);
    TRACE_VALUE(m_parser->typeOfLocal(index), input, "tee_local ", index);
    return { };
}

auto OMGIRGenerator::getGlobal(uint32_t index, ExpressionType& result) -> PartialResult
{
    const Wasm::GlobalInformation& global = m_info.globals[index];
    switch (global.bindingMode) {
    case Wasm::GlobalInformation::BindingMode::EmbeddedInInstance: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, toB3Type(global.type), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfGlobal(m_info, index)));
        switch (global.type.kind) {
        case TypeKind::I32:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_i32[index], value);
            break;
        case TypeKind::F32:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_f32[index], value);
            break;
        case TypeKind::I64:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_i64[index], value);
            break;
        case TypeKind::F64:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_f64[index], value);
            break;
        case TypeKind::V128:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_v128[index], value);
            break;
        default:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_ref[index], value);
            break;
        }
        if (global.mutability == Mutability::Immutable) {
            value->setReadsMutability(B3::Mutability::Immutable);
            value->setControlDependent(false);
        }
        result = push(value);
        break;
    }
    case Wasm::GlobalInformation::BindingMode::Portable: {
        ASSERT(global.mutability == Wasm::Mutability::Mutable);
        auto* pointer = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfGlobal(m_info, index)));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_portableGlobals[index], pointer);
        pointer->setReadsMutability(B3::Mutability::Immutable);
        pointer->setControlDependent(false);

        auto* load = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, toB3Type(global.type), origin(), pointer, safeCast<int32_t>(Wasm::Global::Value::offsetOfValue()));
        m_heaps.decorateMemory(&m_heaps.WasmGlobalValue_value, load);

        result = push(load);
        break;
    }
    }
    TRACE_VALUE(global.type, get(result), "get_global ", index);

    return { };
}

auto OMGIRGenerator::setGlobal(uint32_t index, ExpressionType value) -> PartialResult
{
    const Wasm::GlobalInformation& global = m_info.globals[index];
    ASSERT(toB3Type(global.type) == value.type());
    TRACE_VALUE(global.type, get(value), "set_global ", index);

    switch (global.bindingMode) {
    case Wasm::GlobalInformation::BindingMode::EmbeddedInInstance: {
        auto* store = m_currentBlock->appendNew<MemoryValue>(m_proc, Store, origin(), get(value), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfGlobal(m_info, index)));
        switch (global.type.kind) {
        case TypeKind::I32:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_i32[index], store);
            break;
        case TypeKind::F32:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_f32[index], store);
            break;
        case TypeKind::I64:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_i64[index], store);
            break;
        case TypeKind::F64:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_f64[index], store);
            break;
        case TypeKind::V128:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_v128[index], store);
            break;
        default:
            m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_embeddedGlobals_ref[index], store);
            break;
        }
        if (isRefType(global.type))
            emitWriteBarrierForJSWrapper();
        break;
    }
    case Wasm::GlobalInformation::BindingMode::Portable: {
        ASSERT(global.mutability == Wasm::Mutability::Mutable);
        auto* pointer = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfGlobal(m_info, index)));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_portableGlobals[index], pointer);
        pointer->setReadsMutability(B3::Mutability::Immutable);
        pointer->setControlDependent(false);

        auto* store = m_currentBlock->appendNew<MemoryValue>(m_proc, Store, origin(), get(value), static_cast<Value*>(pointer), safeCast<int32_t>(Wasm::Global::Value::offsetOfValue()));
        m_heaps.decorateMemory(&m_heaps.WasmGlobalValue_value, store);

        // We emit a write-barrier onto JSWebAssemblyGlobal, not JSWebAssemblyInstance.
        if (isRefType(global.type)) {
            auto* cell = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), pointer, safeCast<int32_t>(Wasm::Global::Value::offsetOfOwner()));
            m_heaps.decorateMemory(&m_heaps.WasmGlobalValue_owner, cell);
            cell->setControlDependent(false);

            emitWriteBarrier(cell);
        }
        break;
    }
    }
    return { };
}

inline void OMGIRGenerator::emitWriteBarrierForJSWrapper()
{
    emitWriteBarrier(instanceValue());
}

inline void OMGIRGenerator::emitWriteBarrier(Value* cell)
{
    Value* cellState = m_currentBlock->appendNew<MemoryValue>(m_proc, Load8Z, Int32, origin(), cell, safeCast<int32_t>(JSCell::cellStateOffset()));
    m_heaps.decorateMemory(&m_heaps.JSCell_cellState, cellState);

    auto* vm = vmValue();
    Value* threshold = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int32, origin(), vm, safeCast<int32_t>(VM::offsetOfHeapBarrierThreshold()));
    m_heaps.decorateMemory(&m_heaps.VM_heap_barrierThreshold, threshold);

    BasicBlock* recheckPath = m_proc.addBlock();
    BasicBlock* doSlowPath = m_proc.addBlock();
    BasicBlock* continuation = m_proc.addBlock();

    m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(),
        m_currentBlock->appendNew<Value>(m_proc, Above, origin(), cellState, threshold),
        FrequentedBlock(continuation), FrequentedBlock(recheckPath, FrequencyClass::Rare));
    recheckPath->addPredecessor(m_currentBlock);
    continuation->addPredecessor(m_currentBlock);
    m_currentBlock = recheckPath;

    auto* fence = m_currentBlock->appendNew<FenceValue>(m_proc, origin());
    m_heaps.decorateFenceRead(&m_heaps.root, fence);
    m_heaps.decorateFenceWrite(&m_heaps.JSCell_cellState, fence);

    Value* cellStateLoadAfterFence = m_currentBlock->appendNew<MemoryValue>(m_proc, Load8Z, Int32, origin(), cell, safeCast<int32_t>(JSCell::cellStateOffset()));
    m_heaps.decorateMemory(&m_heaps.JSCell_cellState, cellStateLoadAfterFence);

    m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(),
        m_currentBlock->appendNew<Value>(m_proc, Above, origin(), cellStateLoadAfterFence, constant(Int32, blackThreshold)),
        FrequentedBlock(continuation), FrequentedBlock(doSlowPath, FrequencyClass::Rare));
    doSlowPath->addPredecessor(m_currentBlock);
    continuation->addPredecessor(m_currentBlock);
    m_currentBlock = doSlowPath;

    Value* call = callWasmOperation(m_currentBlock, B3::Void, operationWasmWriteBarrierSlowPath, cell, vm);
    m_heaps.decorateCCallRead(&m_heaps.root, call);
    m_heaps.decorateCCallWrite(&m_heaps.JSCell_cellState, call);
    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);

    continuation->addPredecessor(m_currentBlock);
    m_currentBlock = continuation;
}

inline Value* OMGIRGenerator::emitCheckAndPreparePointer(Value* pointer, uint64_t offset, uint32_t sizeOfOperation, uint8_t memoryIndex)
{
    static_assert(GPRInfo::wasmBaseMemoryPointer != InvalidGPRReg);

    if (!memoryIndex) {
        // m_mode is the mode used for memory 0
        switch (m_mode) {
        case MemoryMode::BoundsChecking: {
            // We're not using signal handling only when the memory is not shared.
            // Regardless of signaling, we must check that no memory access exceeds the current memory size.
            static_assert(GPRInfo::wasmBoundsCheckingSizeRegister != InvalidGPRReg);
            if (WTF::sumOverflows<uint64_t>(offset, sizeOfOperation)) {
                B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
                throwException->setGenerator([this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
                    this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
                });
                break;
            }
            uint64_t lastLoadedOffset = offset;
            lastLoadedOffset += static_cast<uint64_t>(sizeOfOperation - 1);
            m_currentBlock->appendNew<WasmBoundsCheckValue>(m_proc, origin(), GPRInfo::wasmBoundsCheckingSizeRegister, pointer, lastLoadedOffset);
            break;
        }

        case MemoryMode::Signaling: {
            RELEASE_ASSERT(!m_info.memory(memoryIndex).isMemory64());
            // We've virtually mapped 4GiB+redzone for this memory. Only the user-allocated pages are addressable, contiguously in range [0, current],
            // and everything above is mapped PROT_NONE. We don't need to perform any explicit bounds check in the 4GiB range because WebAssembly register
            // memory accesses are 32-bit. However WebAssembly register + offset accesses perform the addition in 64-bit which can push an access above
            // the 32-bit limit (the offset is unsigned 32-bit). The redzone will catch most small offsets, and we'll explicitly bounds check any
            // register + large offset access. We don't think this will be generated frequently.
            //
            // We could check that register + large offset doesn't exceed 4GiB+redzone since that's technically the limit we need to avoid overflowing the
            // PROT_NONE region, but it's better if we use a smaller immediate because it can codegens better. We know that anything equal to or greater
            // than the declared 'maximum' will trap, so we can compare against that number. If there was no declared 'maximum' then we still know that
            // any access equal to or greater than 4GiB will trap, no need to add the redzone.
            if (offset >= Memory::fastMappedRedzoneBytes()) {
                size_t maximum = m_info.memory(memoryIndex).maximum() ? m_info.memory(memoryIndex).maximum().bytes() : std::numeric_limits<uint32_t>::max();
                uint64_t lastLoadedOffset = static_cast<uint64_t>(offset);
                lastLoadedOffset += static_cast<uint64_t>(sizeOfOperation - 1);
                m_currentBlock->appendNew<WasmBoundsCheckValue>(m_proc, origin(), pointer, lastLoadedOffset, maximum);
            }
            break;
        }
        }

        if (!m_info.memory(memoryIndex).isMemory64())
            pointer = m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), pointer);
        return m_currentBlock->appendNew<WasmAddressValue>(m_proc, origin(), pointer, GPRInfo::wasmBaseMemoryPointer);
    }

    // if memoryIndex != 0, force bounds checking

    bool offsetAndSizeOverflows = m_info.memory(memoryIndex).isMemory64()
        ? sumOverflows<uint64_t>(offset, sizeOfOperation)
        : sumOverflows<uint32_t>(offset, sizeOfOperation);

    if (offsetAndSizeOverflows) [[unlikely]] {
        B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        throwException->setGenerator([this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });
    }

    auto baseAndSizeOffset = JSWebAssemblyInstance::offsetOfCachedMemoryBaseSizePair(memoryIndex);

    auto* memorySize = m_currentBlock->appendNew<MemoryValue>(
        m_proc, Load, pointerType(), origin(), instanceValue(),
        safeCast<int32_t>(baseAndSizeOffset + sizeof(uintptr_t)));

    uint64_t lastLoadedOffset = static_cast<uint64_t>(offset);
    lastLoadedOffset += static_cast<uint64_t>(sizeOfOperation - 1);
    auto boundsCheckOffset = constant(Int64, lastLoadedOffset);
    if (!m_info.memory(memoryIndex).isMemory64())
        pointer = m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), pointer);

    Value* sum;
    if (m_info.memory(memoryIndex).isMemory64() && lastLoadedOffset) {
        // FIXME: We should have an optional ResultCondition for CheckAdd (and friends)
        sum = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), pointer, boundsCheckOffset);
        Value* overflowed = m_currentBlock->appendNew<Value>(m_proc, Below, origin(), sum, pointer);
        CheckValue* overflowCheck = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), overflowed);
        overflowCheck->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });
    } else
        sum = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), pointer, boundsCheckOffset);

    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, AboveEqual, origin(), sum, memorySize);
    CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    check->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
    });

    Value* basePointer = m_currentBlock->appendNew<MemoryValue>(
        m_proc, Load, pointerType(), origin(), instanceValue(),
        safeCast<int32_t>(baseAndSizeOffset));
    return m_currentBlock->appendNew<Value>(m_proc, Add, origin(), pointer, basePointer);
}

inline uint32_t sizeOfLoadOp(LoadOpType op)
{
    switch (op) {
    case LoadOpType::I32Load8S:
    case LoadOpType::I32Load8U:
    case LoadOpType::I64Load8S:
    case LoadOpType::I64Load8U:
        return 1;
    case LoadOpType::I32Load16S:
    case LoadOpType::I64Load16S:
    case LoadOpType::I32Load16U:
    case LoadOpType::I64Load16U:
        return 2;
    case LoadOpType::I32Load:
    case LoadOpType::I64Load32S:
    case LoadOpType::I64Load32U:
    case LoadOpType::F32Load:
        return 4;
    case LoadOpType::I64Load:
    case LoadOpType::F64Load:
        return 8;
    }
    RELEASE_ASSERT_NOT_REACHED();
}

inline B3::Kind OMGIRGenerator::memoryKind(B3::Opcode memoryOp)
{
    if (useSignalingMemory0() || m_info.memory(0).isShared())
        return trapping(memoryOp);
    return memoryOp;
}

inline Value* OMGIRGenerator::emitLoadOp(LoadOpType op, Value* pointer, uint64_t uoffset)
{
    int32_t offset = fixupPointerPlusOffset(pointer, uoffset);

    switch (op) {
    case LoadOpType::I32Load8S: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load8S), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }

    case LoadOpType::I64Load8S: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load8S), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return m_currentBlock->appendNew<Value>(m_proc, SExt32, origin(), value);
    }

    case LoadOpType::I32Load8U: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load8Z), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }

    case LoadOpType::I64Load8U: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load8Z), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), value);
    }

    case LoadOpType::I32Load16S: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load16S), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }

    case LoadOpType::I64Load16S: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load16S), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return m_currentBlock->appendNew<Value>(m_proc, SExt32, origin(), value);
    }

    case LoadOpType::I32Load16U: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load16Z), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }

    case LoadOpType::I64Load16U: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load16Z), origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), value);
    }

    case LoadOpType::I32Load: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), Int32, origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }

    case LoadOpType::I64Load32U: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), Int32, origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), value);
    }

    case LoadOpType::I64Load32S: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), Int32, origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return m_currentBlock->appendNew<Value>(m_proc, SExt32, origin(), value);
    }

    case LoadOpType::I64Load: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), Int64, origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }

    case LoadOpType::F32Load: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), Float, origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }

    case LoadOpType::F64Load: {
        auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), Double, origin(), pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
        return value;
    }
    }
    RELEASE_ASSERT_NOT_REACHED();
}

auto OMGIRGenerator::load(LoadOpType op, ExpressionType pointerVar, ExpressionType& result, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    Value* pointer = get(pointerVar);

    bool offsetAndSizeOverflows = m_info.memory(memoryIndex).isMemory64()
        ? sumOverflows<uint64_t>(offset, sizeOfLoadOp(op))
        : sumOverflows<uint32_t>(offset, sizeOfLoadOp(op));

    if (offsetAndSizeOverflows) [[unlikely]] {
        // FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
        // as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
        B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        throwException->setGenerator([this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });

        switch (op) {
        case LoadOpType::I32Load8S:
        case LoadOpType::I32Load16S:
        case LoadOpType::I32Load:
        case LoadOpType::I32Load16U:
        case LoadOpType::I32Load8U:
            result = push(constant(Int32, 0));
            break;
        case LoadOpType::I64Load8S:
        case LoadOpType::I64Load8U:
        case LoadOpType::I64Load16S:
        case LoadOpType::I64Load32U:
        case LoadOpType::I64Load32S:
        case LoadOpType::I64Load:
        case LoadOpType::I64Load16U:
            result = push(constant(Int64, 0));
            break;
        case LoadOpType::F32Load:
            result = push(constant(Float, 0));
            break;
        case LoadOpType::F64Load:
            result = push(constant(Double, 0));
            break;
        }

    } else
        result = push(emitLoadOp(op, emitCheckAndPreparePointer(pointer, offset, sizeOfLoadOp(op), memoryIndex), offset));

    return { };
}

inline uint32_t sizeOfStoreOp(StoreOpType op)
{
    switch (op) {
    case StoreOpType::I32Store8:
    case StoreOpType::I64Store8:
        return 1;
    case StoreOpType::I32Store16:
    case StoreOpType::I64Store16:
        return 2;
    case StoreOpType::I32Store:
    case StoreOpType::I64Store32:
    case StoreOpType::F32Store:
        return 4;
    case StoreOpType::I64Store:
    case StoreOpType::F64Store:
        return 8;
    }
    RELEASE_ASSERT_NOT_REACHED();
}


inline void OMGIRGenerator::emitStoreOp(StoreOpType op, Value* pointer, Value* value, uint64_t uoffset)
{
    int32_t offset = fixupPointerPlusOffset(pointer, uoffset);

    switch (op) {
    case StoreOpType::I64Store8:
        value = m_currentBlock->appendNew<Value>(m_proc, Trunc, origin(), value);
        [[fallthrough]];

    case StoreOpType::I32Store8: {
        auto* store = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Store8), origin(), value, pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, store);
        return;
    }

    case StoreOpType::I64Store16:
        value = m_currentBlock->appendNew<Value>(m_proc, Trunc, origin(), value);
        [[fallthrough]];

    case StoreOpType::I32Store16: {
        auto* store = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Store16), origin(), value, pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, store);
        return;
    }

    case StoreOpType::I64Store32:
        value = m_currentBlock->appendNew<Value>(m_proc, Trunc, origin(), value);
        [[fallthrough]];

    case StoreOpType::I64Store:
    case StoreOpType::I32Store:
    case StoreOpType::F32Store:
    case StoreOpType::F64Store: {
        auto* store = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Store), origin(), value, pointer, offset);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, store);
        return;
    }
    }
    RELEASE_ASSERT_NOT_REACHED();
}

auto OMGIRGenerator::store(StoreOpType op, ExpressionType pointerVar, ExpressionType valueVar, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    Value* pointer = get(pointerVar);
    Value* value = get(valueVar);
    ASSERT(pointer->type() == m_info.memory(memoryIndex).addressType());
    bool offsetAndSizeOverflows = m_info.memory(memoryIndex).isMemory64()
        ? sumOverflows<uint64_t>(offset, sizeOfStoreOp(op))
        : sumOverflows<uint32_t>(offset, sizeOfStoreOp(op));

    if (offsetAndSizeOverflows) [[unlikely]] {
        // FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
        // as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
        B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        throwException->setGenerator([this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });
    } else
        emitStoreOp(op, emitCheckAndPreparePointer(pointer, offset, sizeOfStoreOp(op), memoryIndex), value, offset);

    return { };
}

inline Width accessWidth(ExtAtomicOpType op)
{
    return widthForBytes(1 << memoryLog2Alignment(op));
}

inline uint32_t sizeOfAtomicOpMemoryAccess(ExtAtomicOpType op)
{
    return bytesForWidth(accessWidth(op));
}

inline Value* OMGIRGenerator::sanitizeAtomicResult(ExtAtomicOpType op, Type valueType, Value* result)
{
    auto sanitize32 = [&](Value* result) {
        switch (accessWidth(op)) {
        case Width8:
            return m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(), result, constant(Int32, 0xff));
        case Width16:
            return m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(), result, constant(Int32, 0xffff));
        default:
            return result;
        }
    };

    switch (valueType.kind) {
    case TypeKind::I64: {
        if (accessWidth(op) == Width64)
            return result;
        return m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), sanitize32(result));
    }
    case TypeKind::I32:
        return sanitize32(result);
    default:
        RELEASE_ASSERT_NOT_REACHED();
        return nullptr;
    }
}

Value* OMGIRGenerator::fixupPointerPlusOffsetForAtomicOps(ExtAtomicOpType op, Value* ptr, uint64_t offset)
{
    auto pointer = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), ptr, m_currentBlock->appendNew<ConstPtrValue>(m_proc, origin(), offset));
    if (accessWidth(op) != Width8) {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(), pointer, constant(pointerType(), sizeOfAtomicOpMemoryAccess(op) - 1)));
        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::UnalignedMemoryAccess);
        });
    }
    return pointer;
}

inline Value* OMGIRGenerator::emitAtomicLoadOp(ExtAtomicOpType op, Type valueType, Value* pointer, uint64_t uoffset)
{
    pointer = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);

    Value* value = nullptr;
    switch (accessWidth(op)) {
    case Width8:
    case Width16:
    case Width32:
        value = constant(Int32, 0);
        break;
    case Width64:
        value = constant(Int64, 0);
        break;
    case Width128:
        RELEASE_ASSERT_NOT_REACHED();
        break;
    }

    auto* atomic = m_currentBlock->appendNew<AtomicValue>(m_proc, memoryKind(AtomicXchgAdd), origin(), accessWidth(op), value, pointer);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, atomic);
    m_heaps.decorateFencedAccess(&m_heaps.WebAssemblyMemory, atomic);
    return sanitizeAtomicResult(op, valueType, atomic);
}

auto OMGIRGenerator::atomicLoad(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType& result, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    ASSERT(pointer.type().kind() == m_info.memory(memoryIndex).addressType().asB3TypeKind());

    const bool overflows = m_info.memory(memoryIndex).isMemory64()
        ? sumOverflows<uint64_t>(offset, sizeOfAtomicOpMemoryAccess(op))
        : sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op));

    if (overflows) [[unlikely]] {
        // FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
        // as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
        B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        throwException->setGenerator([this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });

        switch (valueType.kind) {
        case TypeKind::I32:
            result = push(constant(Int32, 0));
            break;
        case TypeKind::I64:
            result = push(constant(Int64, 0));
            break;
        default:
            RELEASE_ASSERT_NOT_REACHED();
            break;
        }
    } else {
        result = push(emitAtomicLoadOp(op, valueType, emitCheckAndPreparePointer(get(pointer), offset, sizeOfAtomicOpMemoryAccess(op), memoryIndex), offset));
    }

    return { };
}

inline void OMGIRGenerator::emitAtomicStoreOp(ExtAtomicOpType op, Type valueType, Value* pointer, Value* value, uint64_t uoffset)
{
    pointer = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);

    if (valueType.isI64() && accessWidth(op) != Width64)
        value = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Trunc, Origin(), value);
    auto* atomic = m_currentBlock->appendNew<AtomicValue>(m_proc, memoryKind(AtomicXchg), origin(), accessWidth(op), value, pointer);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, atomic);
    m_heaps.decorateFencedAccess(&m_heaps.WebAssemblyMemory, atomic);
}

auto OMGIRGenerator::atomicStore(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType value, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    ASSERT(pointer.type().kind() == m_info.memory(memoryIndex).addressType().asB3TypeKind());
    const bool overflows = m_info.memory(memoryIndex).isMemory64()
        ? sumOverflows<uint64_t>(offset, sizeOfAtomicOpMemoryAccess(op))
        : sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op));

    if (overflows) [[unlikely]] {
        // FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
        // as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
        B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        throwException->setGenerator([this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });
    } else {
        emitAtomicStoreOp(op, valueType, emitCheckAndPreparePointer(get(pointer), offset, sizeOfAtomicOpMemoryAccess(op), memoryIndex), get(value), offset);
    }

    return { };
}

inline Value* OMGIRGenerator::emitAtomicBinaryRMWOp(ExtAtomicOpType op, Type valueType, Value* pointer, Value* value, uint64_t uoffset)
{
    pointer = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);

    B3::Opcode opcode = B3::Nop;
    switch (op) {
    case ExtAtomicOpType::I32AtomicRmw8AddU:
    case ExtAtomicOpType::I32AtomicRmw16AddU:
    case ExtAtomicOpType::I32AtomicRmwAdd:
    case ExtAtomicOpType::I64AtomicRmw8AddU:
    case ExtAtomicOpType::I64AtomicRmw16AddU:
    case ExtAtomicOpType::I64AtomicRmw32AddU:
    case ExtAtomicOpType::I64AtomicRmwAdd:
        opcode = AtomicXchgAdd;
        break;
    case ExtAtomicOpType::I32AtomicRmw8SubU:
    case ExtAtomicOpType::I32AtomicRmw16SubU:
    case ExtAtomicOpType::I32AtomicRmwSub:
    case ExtAtomicOpType::I64AtomicRmw8SubU:
    case ExtAtomicOpType::I64AtomicRmw16SubU:
    case ExtAtomicOpType::I64AtomicRmw32SubU:
    case ExtAtomicOpType::I64AtomicRmwSub:
        opcode = AtomicXchgSub;
        break;
    case ExtAtomicOpType::I32AtomicRmw8AndU:
    case ExtAtomicOpType::I32AtomicRmw16AndU:
    case ExtAtomicOpType::I32AtomicRmwAnd:
    case ExtAtomicOpType::I64AtomicRmw8AndU:
    case ExtAtomicOpType::I64AtomicRmw16AndU:
    case ExtAtomicOpType::I64AtomicRmw32AndU:
    case ExtAtomicOpType::I64AtomicRmwAnd:
        opcode = AtomicXchgAnd;
        break;
    case ExtAtomicOpType::I32AtomicRmw8OrU:
    case ExtAtomicOpType::I32AtomicRmw16OrU:
    case ExtAtomicOpType::I32AtomicRmwOr:
    case ExtAtomicOpType::I64AtomicRmw8OrU:
    case ExtAtomicOpType::I64AtomicRmw16OrU:
    case ExtAtomicOpType::I64AtomicRmw32OrU:
    case ExtAtomicOpType::I64AtomicRmwOr:
        opcode = AtomicXchgOr;
        break;
    case ExtAtomicOpType::I32AtomicRmw8XorU:
    case ExtAtomicOpType::I32AtomicRmw16XorU:
    case ExtAtomicOpType::I32AtomicRmwXor:
    case ExtAtomicOpType::I64AtomicRmw8XorU:
    case ExtAtomicOpType::I64AtomicRmw16XorU:
    case ExtAtomicOpType::I64AtomicRmw32XorU:
    case ExtAtomicOpType::I64AtomicRmwXor:
        opcode = AtomicXchgXor;
        break;
    case ExtAtomicOpType::I32AtomicRmw8XchgU:
    case ExtAtomicOpType::I32AtomicRmw16XchgU:
    case ExtAtomicOpType::I32AtomicRmwXchg:
    case ExtAtomicOpType::I64AtomicRmw8XchgU:
    case ExtAtomicOpType::I64AtomicRmw16XchgU:
    case ExtAtomicOpType::I64AtomicRmw32XchgU:
    case ExtAtomicOpType::I64AtomicRmwXchg:
        opcode = AtomicXchg;
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
        break;
    }

    if (valueType.isI64() && accessWidth(op) != Width64)
        value = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Trunc, Origin(), value);

    auto* atomic = m_currentBlock->appendNew<AtomicValue>(m_proc, memoryKind(opcode), origin(), accessWidth(op), value, pointer);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, atomic);
    m_heaps.decorateFencedAccess(&m_heaps.WebAssemblyMemory, atomic);
    return sanitizeAtomicResult(op, valueType, atomic);
}

auto OMGIRGenerator::atomicBinaryRMW(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType value, ExpressionType& result, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    ASSERT(pointer.type().kind() == m_info.memory(memoryIndex).addressType().asB3TypeKind());

    const bool overflows = m_info.memory(memoryIndex).isMemory64()
        ? sumOverflows<uint64_t>(offset, sizeOfAtomicOpMemoryAccess(op))
        : sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op));

    if (overflows) [[unlikely]] {
        // FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
        // as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
        B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        throwException->setGenerator([this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });

        switch (valueType.kind) {
        case TypeKind::I32:
            result = push(constant(Int32, 0));
            break;
        case TypeKind::I64:
            result = push(constant(Int64, 0));
            break;
        default:
            RELEASE_ASSERT_NOT_REACHED();
            break;
        }
    } else {
        result = push(emitAtomicBinaryRMWOp(op, valueType, emitCheckAndPreparePointer(get(pointer), offset, sizeOfAtomicOpMemoryAccess(op), memoryIndex), get(value), offset));
    }

    return { };
}

Value* OMGIRGenerator::emitAtomicCompareExchange(ExtAtomicOpType op, Type valueType, Value* pointer, Value* expected, Value* value, uint64_t uoffset)
{
    pointer = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);

    Width accessWidth = Wasm::accessWidth(op);

    if (widthForType(toB3Type(valueType)) == accessWidth) {
        auto* atomic = m_currentBlock->appendNew<AtomicValue>(m_proc, memoryKind(AtomicStrongCAS), origin(), accessWidth, expected, value, pointer);
        m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, atomic);
        m_heaps.decorateFencedAccess(&m_heaps.WebAssemblyMemory, atomic);
        return sanitizeAtomicResult(op, valueType, atomic);
    }

    Value* maximum = nullptr;
    switch (valueType.kind) {
    case TypeKind::I64: {
        switch (accessWidth) {
        case Width8:
            maximum = constant(Int64, UINT8_MAX);
            break;
        case Width16:
            maximum = constant(Int64, UINT16_MAX);
            break;
        case Width32:
            maximum = constant(Int64, UINT32_MAX);
            break;
        case Width64:
        case Width128:
            RELEASE_ASSERT_NOT_REACHED();
        }
        break;
    }
    case TypeKind::I32:
        switch (accessWidth) {
        case Width8:
            maximum = constant(Int32, UINT8_MAX);
            break;
        case Width16:
            maximum = constant(Int32, UINT16_MAX);
            break;
        case Width32:
        case Width64:
        case Width128:
            RELEASE_ASSERT_NOT_REACHED();
        }
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
    }

    auto truncatedExpected = expected;
    auto truncatedValue = value;

    truncatedExpected = m_currentBlock->appendNew<B3::Value>(m_proc, B3::BitAnd, origin(), maximum, expected);

    if (valueType.isI64()) {
        truncatedExpected = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Trunc, Origin(), expected);
        truncatedValue = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Trunc, Origin(), value);
    }

    auto* atomic = m_currentBlock->appendNew<AtomicValue>(m_proc, memoryKind(AtomicStrongCAS), origin(), accessWidth, truncatedExpected, truncatedValue, pointer);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, atomic);
    m_heaps.decorateFencedAccess(&m_heaps.WebAssemblyMemory, atomic);
    return sanitizeAtomicResult(op, valueType, atomic);
}

[[nodiscard]] bool OMGIRGenerator::emitStructSet(bool canTrap, Value* structValue, uint32_t fieldIndex, const RTT& rtt, Value* argument)
{
    structValue = pointerOfWasmRef(structValue);
    auto fieldType = rtt.field(fieldIndex).type;

    const RTT& definingRTT = rtt.definingRTTForField(fieldIndex);
    uint64_t fieldHeapKey = definingRTT.fieldHeapKey(fieldIndex);

    B3::Kind kind = canTrap ? trapping(WasmStructSet) : WasmStructSet;
    Value* storeValue = m_currentBlock->appendNew<WasmStructSetValue>(m_proc, kind, origin(), structValue, argument, Ref { rtt }, fieldIndex, fieldHeapKey);

    m_heaps.decorateWasmStructSet(structFieldHeap(definingRTT, fieldIndex), storeValue);

    // FIXME: We should be able elide this write barrier if we know we're storing jsNull();
    return fieldType.is<Type>() && isRefType(fieldType.unpacked());
}

auto OMGIRGenerator::atomicCompareExchange(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType expected, ExpressionType value, ExpressionType& result, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    ASSERT(pointer.type().kind() == m_info.memory(memoryIndex).addressType().asB3TypeKind());

    const bool overflows = m_info.memory(memoryIndex).isMemory64()
        ? sumOverflows<uint64_t>(offset, sizeOfAtomicOpMemoryAccess(op))
        : sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op));

    if (overflows) [[unlikely]] {
        // FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
        // as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
        B3::PatchpointValue* throwException = m_currentBlock->appendNew<B3::PatchpointValue>(m_proc, B3::Void, origin());
        throwException->setGenerator([this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });

        switch (valueType.kind) {
        case TypeKind::I32:
            result = push(constant(Int32, 0));
            break;
        case TypeKind::I64:
            result = push(constant(Int64, 0));
            break;
        default:
            RELEASE_ASSERT_NOT_REACHED();
            break;
        }
    } else {
        result = push(emitAtomicCompareExchange(op, valueType, emitCheckAndPreparePointer(get(pointer), offset, sizeOfAtomicOpMemoryAccess(op), memoryIndex), get(expected), get(value), offset));
    }

    return { };
}

auto OMGIRGenerator::atomicWait(ExtAtomicOpType op, ExpressionType pointerVar, ExpressionType valueVar, ExpressionType timeoutVar, ExpressionType& result, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    Value* pointer = get(pointerVar);
    Value* value = get(valueVar);
    Value* timeout = get(timeoutVar);
    Value* resultValue = nullptr;
    if (op == ExtAtomicOpType::MemoryAtomicWait32) {
        resultValue = callWasmOperation(m_currentBlock, Int32, operationMemoryAtomicWait32,
            instanceValue(), pointer, constant(Int64, offset), value, timeout, constant(Int32, memoryIndex));
    } else {
        resultValue = callWasmOperation(m_currentBlock, Int32, operationMemoryAtomicWait64,
            instanceValue(), pointer, constant(Int64, offset), value, timeout, constant(Int32, memoryIndex));
    }

    {
        result = push(resultValue);
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::atomicNotify(ExtAtomicOpType, ExpressionType pointer, ExpressionType count, ExpressionType& result, uint64_t offset, uint8_t memoryIndex) -> PartialResult
{
    Value* resultValue = callWasmOperation(m_currentBlock, Int32, operationMemoryAtomicNotify,
        instanceValue(), get(pointer), constant(Int64, offset), get(count), constant(Int32, memoryIndex));
    {
        result = push(resultValue);
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsMemoryAccess);
        });
    }

    return { };
}

auto OMGIRGenerator::atomicFence(ExtAtomicOpType, uint8_t) -> PartialResult
{
    m_currentBlock->appendNew<FenceValue>(m_proc, origin());
    return { };
}

auto OMGIRGenerator::truncSaturated(Ext1OpType op, ExpressionType argVar, ExpressionType& result, Type returnType, Type) -> PartialResult
{
    Value* arg = get(argVar);

    if constexpr (isARM64()) {
        // ARM64 FCVTZS/FCVTZU natively implement WebAssembly trunc-sat semantics:
        // NaN -> 0, out-of-range -> saturated min/max.
        PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, toB3Type(returnType), origin());
        patchpoint->append(arg, ValueRep::SomeRegister);
        patchpoint->setGenerator([=](CCallHelpers& jit, const StackmapGenerationParams& params) {
            switch (op) {
            case Ext1OpType::I32TruncSatF32S:
                jit.truncateFloatToInt32(params[1].fpr(), params[0].gpr());
                break;
            case Ext1OpType::I32TruncSatF32U:
                jit.truncateFloatToUint32(params[1].fpr(), params[0].gpr());
                break;
            case Ext1OpType::I32TruncSatF64S:
                jit.truncateDoubleToInt32(params[1].fpr(), params[0].gpr());
                break;
            case Ext1OpType::I32TruncSatF64U:
                jit.truncateDoubleToUint32(params[1].fpr(), params[0].gpr());
                break;
            case Ext1OpType::I64TruncSatF32S:
                jit.truncateFloatToInt64(params[1].fpr(), params[0].gpr());
                break;
            case Ext1OpType::I64TruncSatF32U:
                jit.truncateFloatToUint64(params[1].fpr(), params[0].gpr(), InvalidFPRReg, InvalidFPRReg);
                break;
            case Ext1OpType::I64TruncSatF64S:
                jit.truncateDoubleToInt64(params[1].fpr(), params[0].gpr());
                break;
            case Ext1OpType::I64TruncSatF64U:
                jit.truncateDoubleToUint64(params[1].fpr(), params[0].gpr(), InvalidFPRReg, InvalidFPRReg);
                break;
            default:
                RELEASE_ASSERT_NOT_REACHED();
                break;
            }
        });
        patchpoint->effects = Effects::none();
        result = push(patchpoint);
        return { };
    }

    Value* maxFloat = nullptr;
    Value* minFloat = nullptr;
    Value* signBitConstant = nullptr;
    bool requiresMacroScratchRegisters = false;
    switch (op) {
    case Ext1OpType::I32TruncSatF32S:
        maxFloat = constant(Float, std::bit_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int32_t>::min())));
        minFloat = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min())));
        break;
    case Ext1OpType::I32TruncSatF32U:
        maxFloat = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min()) * static_cast<float>(-2.0)));
        minFloat = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(-1.0)));
        break;
    case Ext1OpType::I32TruncSatF64S:
        maxFloat = constant(Double, std::bit_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int32_t>::min())));
        minFloat = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) - 1.0));
        break;
    case Ext1OpType::I32TruncSatF64U:
        maxFloat = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) * -2.0));
        minFloat = constant(Double, std::bit_cast<uint64_t>(-1.0));
        break;
    case Ext1OpType::I64TruncSatF32S:
        maxFloat = constant(Float, std::bit_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int64_t>::min())));
        minFloat = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min())));
        break;
    case Ext1OpType::I64TruncSatF32U:
        maxFloat = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min()) * static_cast<float>(-2.0)));
        minFloat = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(-1.0)));
        // Since x86 doesn't have an instruction to convert floating points to unsigned integers, we at least try to do the smart thing if
        // the numbers would be positive anyway as a signed integer. Since we cannot materialize constants into fprs we have b3 do it
        // so we can pool them if needed.
        if (isX86())
            signBitConstant = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
        requiresMacroScratchRegisters = true;
        break;
    case Ext1OpType::I64TruncSatF64S:
        maxFloat = constant(Double, std::bit_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int64_t>::min())));
        minFloat = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min())));
        break;
    case Ext1OpType::I64TruncSatF64U:
        maxFloat = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min()) * -2.0));
        minFloat = constant(Double, std::bit_cast<uint64_t>(-1.0));
        // Since x86 doesn't have an instruction to convert floating points to unsigned integers, we at least try to do the smart thing if
        // the numbers are would be positive anyway as a signed integer. Since we cannot materialize constants into fprs we have b3 do it
        // so we can pool them if needed.
        if (isX86())
            signBitConstant = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
        requiresMacroScratchRegisters = true;
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
        break;
    }

    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, toB3Type(returnType), origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    if (requiresMacroScratchRegisters) {
        if (isX86()) {
            ASSERT(signBitConstant);
            patchpoint->append(signBitConstant, ValueRep::SomeRegister);
            patchpoint->numFPScratchRegisters = 1;
        }
        patchpoint->clobber(RegisterSet::macroClobberedGPRs());
    }
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        switch (op) {
        case Ext1OpType::I32TruncSatF32S:
            jit.truncateFloatToInt32(params[1].fpr(), params[0].gpr());
            break;
        case Ext1OpType::I32TruncSatF32U:
            jit.truncateFloatToUint32(params[1].fpr(), params[0].gpr());
            break;
        case Ext1OpType::I32TruncSatF64S:
            jit.truncateDoubleToInt32(params[1].fpr(), params[0].gpr());
            break;
        case Ext1OpType::I32TruncSatF64U:
            jit.truncateDoubleToUint32(params[1].fpr(), params[0].gpr());
            break;
        case Ext1OpType::I64TruncSatF32S:
            jit.truncateFloatToInt64(params[1].fpr(), params[0].gpr());
            break;
        case Ext1OpType::I64TruncSatF32U: {
            AllowMacroScratchRegisterUsage allowScratch(jit);
            ASSERT(requiresMacroScratchRegisters);
            FPRReg scratch = InvalidFPRReg;
            FPRReg constant = InvalidFPRReg;
            if (isX86()) {
                scratch = params.fpScratch(0);
                constant = params[2].fpr();
            }
            jit.truncateFloatToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
            break;
        }
        case Ext1OpType::I64TruncSatF64S:
            jit.truncateDoubleToInt64(params[1].fpr(), params[0].gpr());
            break;
        case Ext1OpType::I64TruncSatF64U: {
            AllowMacroScratchRegisterUsage allowScratch(jit);
            ASSERT(requiresMacroScratchRegisters);
            FPRReg scratch = InvalidFPRReg;
            FPRReg constant = InvalidFPRReg;
            if (isX86()) {
                scratch = params.fpScratch(0);
                constant = params[2].fpr();
            }
            jit.truncateDoubleToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
            break;
        }
        default:
            RELEASE_ASSERT_NOT_REACHED();
            break;
        }
    });
    patchpoint->effects = Effects::none();

    Value* maxResult = nullptr;
    Value* minResult = nullptr;
    Value* zero = nullptr;
    bool requiresNaNCheck = false;
    switch (op) {
    case Ext1OpType::I32TruncSatF32S:
    case Ext1OpType::I32TruncSatF64S:
        maxResult = constant(Int32, std::bit_cast<uint32_t>(INT32_MAX));
        minResult = constant(Int32, std::bit_cast<uint32_t>(INT32_MIN));
        zero = constant(Int32, 0);
        requiresNaNCheck = true;
        break;
    case Ext1OpType::I32TruncSatF32U:
    case Ext1OpType::I32TruncSatF64U:
        maxResult = constant(Int32, std::bit_cast<uint32_t>(UINT32_MAX));
        minResult = constant(Int32, std::bit_cast<uint32_t>(0U));
        break;
    case Ext1OpType::I64TruncSatF32S:
    case Ext1OpType::I64TruncSatF64S:
        maxResult = constant(Int64, std::bit_cast<uint64_t>(INT64_MAX));
        minResult = constant(Int64, std::bit_cast<uint64_t>(INT64_MIN));
        zero = constant(Int64, 0);
        requiresNaNCheck = true;
        break;
    case Ext1OpType::I64TruncSatF32U:
    case Ext1OpType::I64TruncSatF64U:
        maxResult = constant(Int64, std::bit_cast<uint64_t>(UINT64_MAX));
        minResult = constant(Int64, std::bit_cast<uint64_t>(0ULL));
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
        break;
    }

    result = push(m_currentBlock->appendNew<Value>(m_proc, B3::Select, origin(),
        m_currentBlock->appendNew<Value>(m_proc, GreaterThan, origin(), arg, minFloat),
        m_currentBlock->appendNew<Value>(m_proc, B3::Select, origin(),
            m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, maxFloat),
            patchpoint, maxResult),
        requiresNaNCheck ? m_currentBlock->appendNew<Value>(m_proc, B3::Select, origin(), m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), arg, arg), minResult, zero) : minResult));

    return { };
}

// Wide arithmetic

auto OMGIRGenerator::addI64Add128(ExpressionType lhsLoVar, ExpressionType lhsHiVar, ExpressionType rhsLoVar, ExpressionType rhsHiVar, ExpressionType& resultLo, ExpressionType& resultHi) -> PartialResult
{
    Value* lhsLo = get(lhsLoVar);
    Value* lhsHi = get(lhsHiVar);
    Value* rhsLo = get(rhsLoVar);
    Value* rhsHi = get(rhsHiVar);

    B3::Type tupleType = int64PairTupleType();
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, tupleType, origin());
    patchpoint->append(lhsLo, ValueRep::SomeRegister);
    patchpoint->append(lhsHi, ValueRep::SomeRegister);
    patchpoint->append(rhsLo, ValueRep::SomeRegister);
    patchpoint->append(rhsHi, ValueRep::SomeRegister);
    patchpoint->resultConstraints = { ValueRep::SomeEarlyRegister, isX86() ? ValueRep::SomeEarlyRegister : ValueRep::SomeRegister };
    patchpoint->setGenerator([=](CCallHelpers& jit, const StackmapGenerationParams& params) {
        GPRReg resLo = params[0].gpr();
        GPRReg resHi = params[1].gpr();
        GPRReg aLo = params[2].gpr();
        GPRReg aHi = params[3].gpr();
        GPRReg bLo = params[4].gpr();
        GPRReg bHi = params[5].gpr();
#if CPU(ARM64)
        jit.add64AndSetFlags(aLo, bLo, resLo);
        jit.addCarry64(aHi, bHi, resHi);
#elif CPU(X86_64)
        jit.move(aLo, resLo);
        jit.add64(bLo, resLo);
        jit.move(aHi, resHi);
        jit.addCarry64(bHi, resHi);
#endif
    });
    patchpoint->effects = Effects::none();

    resultLo = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 0));
    resultHi = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 1));
    return { };
}

auto OMGIRGenerator::addI64Sub128(ExpressionType lhsLoVar, ExpressionType lhsHiVar, ExpressionType rhsLoVar, ExpressionType rhsHiVar, ExpressionType& resultLo, ExpressionType& resultHi) -> PartialResult
{
    Value* lhsLo = get(lhsLoVar);
    Value* lhsHi = get(lhsHiVar);
    Value* rhsLo = get(rhsLoVar);
    Value* rhsHi = get(rhsHiVar);

    B3::Type tupleType = int64PairTupleType();
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, tupleType, origin());
    patchpoint->append(lhsLo, ValueRep::SomeRegister);
    patchpoint->append(lhsHi, ValueRep::SomeRegister);
    patchpoint->append(rhsLo, ValueRep::SomeRegister);
    patchpoint->append(rhsHi, ValueRep::SomeRegister);
    patchpoint->resultConstraints = { ValueRep::SomeEarlyRegister, isX86() ? ValueRep::SomeEarlyRegister : ValueRep::SomeRegister };
    patchpoint->setGenerator([=](CCallHelpers& jit, const StackmapGenerationParams& params) {
        GPRReg resLo = params[0].gpr();
        GPRReg resHi = params[1].gpr();
        GPRReg aLo = params[2].gpr();
        GPRReg aHi = params[3].gpr();
        GPRReg bLo = params[4].gpr();
        GPRReg bHi = params[5].gpr();
#if CPU(ARM64)
        jit.sub64AndSetFlags(aLo, bLo, resLo);
        jit.subBorrow64(aHi, bHi, resHi);
#elif CPU(X86_64)
        jit.move(aLo, resLo);
        jit.sub64(bLo, resLo);
        jit.move(aHi, resHi);
        jit.subBorrow64(bHi, resHi);
#endif
    });
    patchpoint->effects = Effects::none();

    resultLo = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 0));
    resultHi = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 1));
    return { };
}

auto OMGIRGenerator::addI64MulWideU(ExpressionType lhsVar, ExpressionType rhsVar, ExpressionType& resultLo, ExpressionType& resultHi) -> PartialResult
{
    Value* lhs = get(lhsVar);
    Value* rhs = get(rhsVar);

#if CPU(ARM64)
    resultLo = push(m_currentBlock->appendNew<Value>(m_proc, Mul, origin(), lhs, rhs));
    resultHi = push(m_currentBlock->appendNew<Value>(m_proc, UMulHigh, origin(), lhs, rhs));

#elif CPU(X86_64)
    // FIXME: We should get B3 on X86 to lower this to one instruction without a patchpoint.
    B3::Type tupleType = int64PairTupleType();
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, tupleType, origin());
    patchpoint->append(lhs, ValueRep::reg(X86Registers::eax));
    patchpoint->append(rhs, ValueRep::SomeRegister);
    patchpoint->resultConstraints = { ValueRep::reg(X86Registers::eax), ValueRep::reg(X86Registers::edx) };
    patchpoint->effects = Effects::none();
    patchpoint->setGenerator([=](CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.x86UMulHigh64(params[3].gpr(), params[0].gpr(), params[1].gpr());
    });

    resultLo = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 0));
    resultHi = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 1));
#endif

    return { };
}

auto OMGIRGenerator::addI64MulWideS(ExpressionType lhsVar, ExpressionType rhsVar, ExpressionType& resultLo, ExpressionType& resultHi) -> PartialResult
{
    Value* lhs = get(lhsVar);
    Value* rhs = get(rhsVar);

#if CPU(ARM64)
    resultLo = push(m_currentBlock->appendNew<Value>(m_proc, Mul, origin(), lhs, rhs));
    resultHi = push(m_currentBlock->appendNew<Value>(m_proc, MulHigh, origin(), lhs, rhs));

#elif CPU(X86_64)
    // FIXME: We should get B3 on X86 to lower this to one instruction without a patchpoint.
    B3::Type tupleType = int64PairTupleType();
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, tupleType, origin());
    patchpoint->append(lhs, ValueRep::reg(X86Registers::eax));
    patchpoint->append(rhs, ValueRep::SomeRegister);
    patchpoint->resultConstraints = { ValueRep::reg(X86Registers::eax), ValueRep::reg(X86Registers::edx) };
    patchpoint->effects = Effects::none();
    patchpoint->setGenerator([=](CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.x86MulHigh64(params[3].gpr(), params[0].gpr(), params[1].gpr());
    });

    resultLo = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 0));
    resultHi = push(m_currentBlock->appendNew<ExtractValue>(m_proc, origin(), B3::Int64, patchpoint, 1));
#endif

    return { };
}

auto OMGIRGenerator::addRefI31(ExpressionType value, ExpressionType& result) -> PartialResult
{
    ASSERT(value.type() == Int32);
    Value* shiftLeft = m_currentBlock->appendNew<Value>(m_proc, B3::Shl, origin(), get(value), constant(Int32, 0x1));
    Value* shiftRight = m_currentBlock->appendNew<Value>(m_proc, B3::SShr, origin(), shiftLeft, constant(Int32, 0x1));
    Value* extended = m_currentBlock->appendNew<Value>(m_proc, B3::ZExt32, origin(), shiftRight);
    result = push(m_currentBlock->appendNew<Value>(m_proc, B3::BitOr, origin(), extended, constant(Int64, JSValue::NumberTag)));

    return { };
}

auto OMGIRGenerator::addI31GetS(TypedExpression reference, ExpressionType& result) -> PartialResult
{
    // Trap on null reference.
    Value* value = get(reference);
    if (reference.type().isNullable())
        emitNullCheck(value, ExceptionType::NullI31Get);

    result = push(m_currentBlock->appendNew<Value>(m_proc, B3::Trunc, origin(), value));

    return { };
}

auto OMGIRGenerator::addI31GetU(TypedExpression reference, ExpressionType& result) -> PartialResult
{
    // Trap on null reference.
    Value* value = get(reference);
    if (reference.type().isNullable())
        emitNullCheck(value, ExceptionType::NullI31Get);

    Value* masked = m_currentBlock->appendNew<Value>(m_proc, B3::BitAnd, origin(), int32OfPointer(pointerOfWasmRef(value)), constant(Int32, 0x7fffffff));
    result = push(masked);
    return { };
}

// Given a type index, verify that it's an array type and return its expansion
const RTT* OMGIRGenerator::getArrayRTT(TypeSignatureIndex typeIndex)
{
    const RTT& arrayRTT = m_info.rtt(typeIndex);
    ASSERT(arrayRTT.kind() == RTTKind::Array);
    return &arrayRTT;
}

// Given a type index for an array signature, look it up, expand it and
// return the element type
void OMGIRGenerator::getArrayElementType(TypeSignatureIndex typeIndex, StorageType& result)
{
    const RTT* arrayType = getArrayRTT(typeIndex);
    result = arrayType->elementType().type;
}

// Given a type index, verify that it's an array type and return the type (Ref a)
void OMGIRGenerator::getArrayRefType(TypeSignatureIndex typeIndex, Type& result)
{
    result = Type { TypeKind::Ref, m_info.rtt(typeIndex).asTypeIndex() };
}

auto OMGIRGenerator::addArrayNew(TypeSignatureIndex typeIndex, ExpressionType size, ExpressionType value, ExpressionType& result) -> PartialResult
{
#if ASSERT_ENABLED
    StorageType elementType;
    getArrayElementType(typeIndex, elementType);
    ASSERT(toB3Type(elementType.unpacked()) == value.type());
#endif

    Value* initValue = get(value);
    Value* sizeValue = get(size);

    auto* structureID = loadGCObjectStructureID(typeIndex);

    Ref<const RTT> rtt = m_info.rtt(typeIndex);
    int32_t allocatorsBaseOffset = safeCast<int32_t>(JSWebAssemblyInstance::offsetOfAllocatorForGCObject(m_info, 0));
    m_proc.setUsesWasmGCArrayAllocations();

    auto* array = m_currentBlock->appendNew<WasmArrayNewValue>(m_proc, origin(), wasmRefType(), Ref { rtt }, typeIndex.rawIndex(), allocatorsBaseOffset, instanceValue(), structureID, sizeValue, initValue);

    mutatorFence();
    result = push(array);
    return { };
}

auto OMGIRGenerator::pushArrayNewFromSegment(ArraySegmentOperation operation, TypeSignatureIndex typeIndex, uint32_t segmentIndex, ExpressionType arraySize, ExpressionType offset, ExceptionType exceptionType) -> ExpressionType
{
    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::Arrayref), operation,
        instanceValue(), constant(Int32, typeIndex.rawIndex()),
        constant(Int32, segmentIndex),
        get(arraySize), get(offset));

    // Indicates out of bounds for the segment or allocation failure.
    emitNullCheck(resultValue, exceptionType);

    return push(resultValue);
}

auto OMGIRGenerator::addArrayNewDefault(TypeSignatureIndex typeIndex, ExpressionType size, ExpressionType& result) -> PartialResult
{
    StorageType elementType;
    getArrayElementType(typeIndex, elementType);

    Value* initValue = nullptr;
    if (isRefType(elementType.unpacked()))
        initValue = m_currentBlock->appendNew<WasmConstRefValue>(m_proc, origin(), JSValue::encode(jsNull()));
    else if (elementType.elementSize() == 16)
        initValue = constant(V128, v128_t { });
    else
        initValue = constant(toB3Type(elementType.unpacked()), 0);

    Value* sizeValue = get(size);

    auto* structureID = loadGCObjectStructureID(typeIndex);

    Ref<const RTT> rtt = m_info.rtt(typeIndex);
    int32_t allocatorsBaseOffset = safeCast<int32_t>(JSWebAssemblyInstance::offsetOfAllocatorForGCObject(m_info, 0));
    m_proc.setUsesWasmGCArrayAllocations();

    auto* array = m_currentBlock->appendNew<WasmArrayNewValue>(m_proc, origin(), wasmRefType(), Ref { rtt }, typeIndex.rawIndex(), allocatorsBaseOffset, instanceValue(), structureID, sizeValue, initValue);

    mutatorFence();
    result = push(array);
    return { };
}

auto OMGIRGenerator::addArrayNewData(TypeSignatureIndex typeIndex, uint32_t dataIndex, ExpressionType arraySize, ExpressionType offset, ExpressionType& result) -> PartialResult
{
    result = pushArrayNewFromSegment(operationWasmArrayNewData, typeIndex, dataIndex, arraySize, offset, ExceptionType::BadArrayNewInitData);

    return { };
}

auto OMGIRGenerator::addArrayNewElem(TypeSignatureIndex typeIndex, uint32_t elemSegmentIndex, ExpressionType arraySize, ExpressionType offset, ExpressionType& result) -> PartialResult
{
    result = pushArrayNewFromSegment(operationWasmArrayNewElem, typeIndex, elemSegmentIndex, arraySize, offset, ExceptionType::BadArrayNewInitElem);
    return { };
}

auto OMGIRGenerator::addArrayNewFixed(TypeSignatureIndex typeIndex, ArgumentList& args, ExpressionType& result) -> PartialResult
{
    StorageType elementType;
    getArrayElementType(typeIndex, elementType);

    auto* size = constant(Int32, args.size());

    auto* structureID = loadGCObjectStructureID(typeIndex);

    Ref<const RTT> rtt = m_info.rtt(typeIndex);
    int32_t allocatorsBaseOffset = safeCast<int32_t>(JSWebAssemblyInstance::offsetOfAllocatorForGCObject(m_info, 0));
    m_proc.setUsesWasmGCArrayAllocations();

    auto* object = m_currentBlock->appendNew<WasmArrayNewValue>(m_proc, origin(), wasmRefType(), Ref { rtt }, typeIndex.rawIndex(), allocatorsBaseOffset, instanceValue(), structureID, size);

    for (uint32_t i = 0; i < args.size(); ++i) {
        // Emit the array set code -- note that this omits the bounds check, since
        // if operationWasmArrayNewEmpty() returned a non-null value, it's an array of the right size
        emitArraySetUncheckedWithoutWriteBarrier(typeIndex, object, constant(Int32, i), get(args[i]));
    }
    mutatorFence();
    result = push(object);
    return { };
}

Value* OMGIRGenerator::emitGetArraySizeWithNullCheck(Type arrayType, Value* array)
{
    int32_t offset = safeCast<int32_t>(JSWebAssemblyArray::offsetOfSize());
    bool canTrap = false;
    if (arrayType.isNullable())
        canTrap = emitNullCheckBeforeAccess(array, offset);
    B3::Kind kind = canTrap ? trapping(WasmArrayLength) : B3::Kind(WasmArrayLength);
    auto* arrayLength = m_currentBlock->appendNew<WasmArrayLengthValue>(m_proc, kind, Int32, origin(), pointerOfWasmRef(array));
    m_heaps.decorateWasmArrayLength(&m_heaps.JSWebAssemblyArray_size, arrayLength);
    return arrayLength;
}

auto OMGIRGenerator::addArrayGet(ExtGCOpType arrayGetKind, TypeSignatureIndex typeIndex, TypedExpression arrayref, ExpressionType index, ExpressionType& result) -> PartialResult
{
    auto arrayValue = get(arrayref);
    auto indexValue = get(index);
    StorageType elementType;
    getArrayElementType(typeIndex, elementType);
    Wasm::Type resultType = elementType.unpacked();

    // Check array bounds.
    auto* arraySize = emitGetArraySizeWithNullCheck(arrayref.type(), arrayValue);
    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, AboveEqual, origin(), indexValue, arraySize));
        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsArrayGet);
        });
    }

    Ref<const RTT> arrayType = m_info.rtt(typeIndex);
    Wasm::Mutability mutability = arrayType->elementType().mutability;
    B3::Mutability b3Mutability = (mutability == Wasm::Mutability::Immutable) ? B3::Mutability::Immutable : B3::Mutability::Mutable;

    Value* loadValue = m_currentBlock->appendNew<WasmArrayGetValue>(m_proc, WasmArrayGet, origin(),
        toB3Type(resultType), arrayValue, indexValue, arrayType.copyRef(), b3Mutability);
    m_heaps.decorateWasmArrayGet(arrayElementHeap(elementType, indexValue), loadValue);

    Value* postProcess = loadValue;
    if (elementType.is<PackedType>()) {
        switch (arrayGetKind) {
        case ExtGCOpType::ArrayGet:
        case ExtGCOpType::ArrayGetU:
            break;
        case ExtGCOpType::ArrayGetS: {
            size_t elementSize = elementType.as<PackedType>() == PackedType::I8 ? sizeof(uint8_t) : sizeof(uint16_t);
            uint8_t bitShift = (sizeof(uint32_t) - elementSize) * 8;
            Value* shiftLeft = m_currentBlock->appendNew<Value>(m_proc, B3::Shl, origin(), postProcess, constant(Int32, bitShift));
            postProcess = m_currentBlock->appendNew<Value>(m_proc, B3::SShr, origin(), shiftLeft, constant(Int32, bitShift));
            break;
        }
        default:
            RELEASE_ASSERT_NOT_REACHED();
            return { };
        }
    }

    result = push(postProcess);
    return { };
}

void OMGIRGenerator::emitNullCheck(Value* ref, ExceptionType exceptionType)
{
    CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
        m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), ref, m_currentBlock->appendNew<WasmConstRefValue>(m_proc, origin(), JSValue::encode(jsNull()))));
    check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, exceptionType);
    });
}

bool OMGIRGenerator::emitNullCheckBeforeAccess(Value* ref, ptrdiff_t offset)
{
    if (Options::useWasmFaultSignalHandler()) {
        if (offset <= maxAcceptableOffsetForNullReference())
            return true;
    }

    CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
        m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), ref, m_currentBlock->appendNew<WasmConstRefValue>(m_proc, origin(), JSValue::encode(jsNull()))));
    check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::NullAccess);
    });
    return false;
}

// Does the array set without null check and bounds checks -- can be
// called directly by addArrayNewFixed()
bool OMGIRGenerator::emitArraySetUncheckedWithoutWriteBarrier(TypeSignatureIndex typeIndex, Value* arrayref, Value* indexValue, Value* setValue)
{
    StorageType elementType;
    getArrayElementType(typeIndex, elementType);

    auto* storeNode = m_currentBlock->appendNew<WasmArraySetValue>(m_proc, WasmArraySet, origin(),
        arrayref, indexValue, setValue, Ref { m_info.rtt(typeIndex) });
    m_heaps.decorateWasmArraySet(arrayElementHeap(elementType, indexValue), storeNode);

    return isRefType(elementType.unpacked());
}

void OMGIRGenerator::emitArraySetUnchecked(TypeSignatureIndex typeIndex, Value* arrayref, Value* index, Value* setValue)
{
    if (emitArraySetUncheckedWithoutWriteBarrier(typeIndex, arrayref, index, setValue))
        emitWriteBarrier(pointerOfWasmRef(arrayref));
}


auto OMGIRGenerator::addArraySet(TypeSignatureIndex typeIndex, TypedExpression arrayref, ExpressionType index, ExpressionType value) -> PartialResult
{
#if ASSERT_ENABLED
    const RTT* arrayType = getArrayRTT(typeIndex);
    UNUSED_VARIABLE(arrayType);
#endif

    auto arrayValue = get(arrayref);
    auto indexValue = get(index);
    auto valueValue = get(value);

    // Check array bounds.
    auto* arraySize = emitGetArraySizeWithNullCheck(arrayref.type(), arrayValue);
    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, AboveEqual, origin(), indexValue, arraySize));
        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsArraySet);
        });
    }

    emitArraySetUnchecked(typeIndex, arrayValue, indexValue, valueValue);

    return { };
}

auto OMGIRGenerator::addArrayLen(TypedExpression arrayref, ExpressionType& result) -> PartialResult
{
    auto arrayValue = get(arrayref);

    auto* arraySize = emitGetArraySizeWithNullCheck(arrayref.type(), arrayValue);

    result = push(arraySize);

    return { };
}

auto OMGIRGenerator::addArrayFill(TypeSignatureIndex typeIndex, TypedExpression arrayref, ExpressionType offset, ExpressionType value, ExpressionType size) -> PartialResult
{
    StorageType elementType;
    getArrayElementType(typeIndex, elementType);

    Value* arrayValue = get(arrayref);
    Value* offsetValue = get(offset);
    Value* valueValue = get(value);
    Value* sizeValue = get(size);

    if (arrayref.type().isNullable())
        emitNullCheck(arrayValue, ExceptionType::NullArrayFill);

    Value* resultValue;
    if (!elementType.unpacked().isV128()) {
        Value* valueGPR = valueValue;
        if (valueValue->type().isFloat())
            valueGPR = m_currentBlock->appendNew<Value>(m_proc, BitwiseCast, origin(), valueGPR);
        resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmArrayFill,
            instanceValue(), arrayValue, offsetValue, valueGPR, sizeValue);
    } else {
        Value* lane0 = m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorExtractLane, B3::Int64, SIMDLane::i64x2, SIMDSignMode::None, uint8_t { 0 }, valueValue);
        Value* lane1 = m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorExtractLane, B3::Int64, SIMDLane::i64x2, SIMDSignMode::None, uint8_t { 1 }, valueValue);
        resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmArrayFillVector,
            instanceValue(), arrayValue, offsetValue, lane0, lane1, sizeValue);
    }

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsArrayFill);
        });
    }

    return { };
}

auto OMGIRGenerator::addArrayCopy(TypeSignatureIndex, TypedExpression dst, ExpressionType dstOffset, TypeSignatureIndex, TypedExpression src, ExpressionType srcOffset, ExpressionType size) -> PartialResult
{
    auto dstValue = get(dst);
    auto dstOffsetValue = get(dstOffset);
    auto srcValue = get(src);
    auto srcOffsetValue = get(srcOffset);
    auto sizeValue = get(size);

    if (dst.type().isNullable())
        emitNullCheck(dstValue, ExceptionType::NullArrayCopy);
    if (src.type().isNullable())
        emitNullCheck(srcValue, ExceptionType::NullArrayCopy);

    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmArrayCopy,
        instanceValue(),
        dstValue, dstOffsetValue,
        srcValue, srcOffsetValue,
        sizeValue);

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsArrayCopy);
        });
    }

    return { };
}

auto OMGIRGenerator::addArrayInitElem(TypeSignatureIndex, TypedExpression dst, ExpressionType dstOffset, uint32_t srcElementIndex, ExpressionType srcOffset, ExpressionType size) -> PartialResult
{
    auto dstValue = get(dst);
    auto dstOffsetValue = get(dstOffset);
    auto srcOffsetValue = get(srcOffset);
    auto sizeValue = get(size);

    if (dst.type().isNullable())
        emitNullCheck(dstValue, ExceptionType::NullArrayInitElem);

    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmArrayInitElem,
        instanceValue(),
        dstValue, dstOffsetValue,
        constant(Int32, srcElementIndex), srcOffsetValue,
        sizeValue);

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsArrayInitElem);
        });
    }

    return { };
}

auto OMGIRGenerator::addArrayInitData(TypeSignatureIndex, TypedExpression dst, ExpressionType dstOffset, uint32_t srcDataIndex, ExpressionType srcOffset, ExpressionType size) -> PartialResult
{
    auto dstValue = get(dst);
    auto dstOffsetValue = get(dstOffset);
    auto srcOffsetValue = get(srcOffset);
    auto sizeValue = get(size);

    if (dst.type().isNullable())
        emitNullCheck(dstValue, ExceptionType::NullArrayInitData);

    Value* resultValue = callWasmOperation(m_currentBlock, toB3Type(Types::I32), operationWasmArrayInitData,
        instanceValue(),
        dstValue, dstOffsetValue,
        constant(Int32, srcDataIndex), srcOffsetValue,
        sizeValue);

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), resultValue, constant(Int32, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsArrayInitData);
        });
    }

    return { };
}

auto OMGIRGenerator::addStructNew(TypeSignatureIndex typeIndex, ArgumentList& args, ExpressionType& result) -> PartialResult
{
    const RTT& rtt = m_info.rtt(typeIndex);

    auto* structureID = loadGCObjectStructureID(typeIndex);

    int32_t allocatorsBaseOffset = safeCast<int32_t>(JSWebAssemblyInstance::offsetOfAllocatorForGCObject(m_info, 0));
    m_proc.setUsesWasmGCStructAllocations();

    auto* structNew = m_currentBlock->appendNew<WasmStructNewValue>(m_proc, origin(), wasmRefType(), Ref { rtt }, typeIndex.rawIndex(), allocatorsBaseOffset, instanceValue(), structureID);

    for (uint32_t i = 0; i < args.size(); ++i) {
        bool needsWriteBarrier = emitStructSet(/* canTrap */ false, structNew, i, rtt, get(args[i]));
        UNUSED_VARIABLE(needsWriteBarrier);
    }
    mutatorFence();
    result = push(structNew);
    return { };
}

auto OMGIRGenerator::addStructNewDefault(TypeSignatureIndex typeIndex, ExpressionType& result) -> PartialResult
{
    const RTT& rtt = m_info.rtt(typeIndex);

    auto* structureID = loadGCObjectStructureID(typeIndex);

    int32_t allocatorsBaseOffset = safeCast<int32_t>(JSWebAssemblyInstance::offsetOfAllocatorForGCObject(m_info, 0));
    m_proc.setUsesWasmGCStructAllocations();

    auto* structNew = m_currentBlock->appendNew<WasmStructNewValue>(m_proc, origin(), wasmRefType(), Ref { rtt }, typeIndex.rawIndex(), allocatorsBaseOffset, instanceValue(), structureID);

    for (StructFieldCount i = 0; i < rtt.fieldCount(); ++i) {
        Value* initValue;
        auto fieldType = rtt.field(i).type;
        if (Wasm::isRefType(fieldType))
            initValue = m_currentBlock->appendNew<WasmConstRefValue>(m_proc, origin(), JSValue::encode(jsNull()));
        else if (typeSizeInBytes(fieldType) == 16)
            initValue = constant(V128, v128_t { });
        else
            initValue = constant(toB3Type(fieldType.unpacked()), 0);
        // We know all the values here are not cells so we don't need a writeBarrier.
        bool needsWriteBarrier = emitStructSet(/* canTrap */ false, structNew, i, rtt, initValue);
        UNUSED_VARIABLE(needsWriteBarrier);
    }
    mutatorFence();
    result = push(structNew);
    return { };
}

auto OMGIRGenerator::addStructGet(ExtGCOpType structGetKind, TypedExpression structReference, const RTT& rtt, uint32_t fieldIndex, ExpressionType& result) -> PartialResult
{
    auto field = rtt.field(fieldIndex);
    auto fieldType = field.type;
    auto resultType = fieldType.unpacked();

    Value* structValue = get(structReference);

    ASSERT(fieldIndex <= maxStructFieldCount);
    int32_t fieldOffset = JSWebAssemblyStruct::offsetOfData() + rtt.offsetOfFieldInPayload(fieldIndex);

    bool canTrap = false;
    if (structReference.type().isNullable())
        canTrap = emitNullCheckBeforeAccess(structValue, fieldOffset);

    const RTT& definingRTT = rtt.definingRTTForField(fieldIndex);
    uint64_t fieldHeapKey = definingRTT.fieldHeapKey(fieldIndex);

    B3::Mutability mutability = field.mutability == Wasm::Mutability::Mutable ? B3::Mutability::Mutable : B3::Mutability::Immutable;

    B3::Kind kind = canTrap ? trapping(WasmStructGet) : WasmStructGet;
    Value* loadValue = m_currentBlock->appendNew<WasmStructGetValue>(m_proc, kind, origin(), toB3Type(resultType), structValue, Ref { rtt }, fieldIndex, fieldHeapKey, mutability);

    m_heaps.decorateWasmStructGet(structFieldHeap(definingRTT, fieldIndex), loadValue);

    // For StructGetS (signed extension of packed types), apply sign extension as post-process.
    Value* postProcess = loadValue;
    if (fieldType.is<PackedType>() && structGetKind == ExtGCOpType::StructGetS) {
        uint8_t bitShift = (sizeof(uint32_t) - fieldType.elementSize()) * 8;
        Value* shiftLeft = m_currentBlock->appendNew<Value>(m_proc, B3::Shl, origin(), postProcess, constant(Int32, bitShift));
        postProcess = m_currentBlock->appendNew<Value>(m_proc, B3::SShr, origin(), shiftLeft, constant(Int32, bitShift));
    }

    result = push(postProcess);
    return { };
}

auto OMGIRGenerator::addStructSet(TypedExpression structReference, const RTT& rtt, uint32_t fieldIndex, ExpressionType value) -> PartialResult
{
    Value* structValue = get(structReference);
    Value* valueValue = get(value);

    ASSERT(fieldIndex <= maxStructFieldCount);
    int32_t fieldOffset = JSWebAssemblyStruct::offsetOfData() + rtt.offsetOfFieldInPayload(fieldIndex);

    bool canTrap = false;
    if (structReference.type().isNullable())
        canTrap = emitNullCheckBeforeAccess(structValue, fieldOffset);

    bool needsWriteBarrier = emitStructSet(canTrap, structValue, fieldIndex, rtt, valueValue);
    if (needsWriteBarrier)
        emitWriteBarrier(pointerOfWasmRef(structValue));
    return { };
}

auto OMGIRGenerator::addRefTest(TypedExpression reference, bool allowNull, int32_t heapType, bool shouldNegate, ExpressionType& result) -> PartialResult
{
    emitRefTestOrCast(CastKind::Test, reference, allowNull, heapType, shouldNegate, result);
    return { };
}

auto OMGIRGenerator::addRefCast(TypedExpression reference, bool allowNull, int32_t heapType, ExpressionType& result) -> PartialResult
{
    emitRefTestOrCast(CastKind::Cast, reference, allowNull, heapType, false, result);
    return { };
}

void OMGIRGenerator::emitRefTestOrCast(CastKind castKind, TypedExpression reference, bool allowNull, int32_t toHeapType, bool shouldNegate, ExpressionType& result)
{
    Value* value = get(reference);

    RefPtr<const Wasm::RTT> targetRTT;
    int32_t originalTypeIndex = toHeapType;
    if (!typeIndexIsType(static_cast<Wasm::TypeIndex>(toHeapType))) {
        targetRTT = &m_info.rtt(ModuleInformation::typeSignatureIndexFromHeapType(toHeapType));
        toHeapType = 0;
        ASSERT(!typeIndexIsType(static_cast<Wasm::TypeIndex>(toHeapType)));
    }

    OptionSet<B3::WasmRefTypeCheckFlag> flags;
    if (allowNull) {
        // If incoming type is not nullable, let's not allow null.
        if (reference.type().isNullable())
            flags.add(B3::WasmRefTypeCheckFlag::AllowNull);
    }
    if (shouldNegate)
        flags.add(B3::WasmRefTypeCheckFlag::ShouldNegate);
    if (reference.type().isNullable())
        flags.add(B3::WasmRefTypeCheckFlag::ReferenceIsNullable);
    if (reference.type().definitelyIsCellOrNull())
        flags.add(B3::WasmRefTypeCheckFlag::DefinitelyIsCellOrNull);
    if (reference.type().definitelyIsWasmGCObjectOrNull())
        flags.add(B3::WasmRefTypeCheckFlag::DefinitelyIsWasmGCObjectOrNull);

    auto type = castKind == CastKind::Cast ? Int64 : Int32;
    auto kind = castKind == CastKind::Cast ? trapping(WasmRefCast) : WasmRefTest;

    if (targetRTT && targetRTT->kind() != Wasm::RTTKind::Function) {
        auto* targetStructureID = loadGCObjectStructureID(TypeSignatureIndex(originalTypeIndex));

        auto* castValue = m_currentBlock->appendNew<B3::WasmRefTypeCheckValue>(m_proc, kind, type, origin(), toHeapType, flags, WTF::move(targetRTT), value, targetStructureID);
        result = push(castValue);
        return;
    }

    auto* castValue = m_currentBlock->appendNew<B3::WasmRefTypeCheckValue>(m_proc, kind, type, origin(), toHeapType, flags, WTF::move(targetRTT), value);
    result = push(castValue);
}

void OMGIRGenerator::mutatorFence()
{
    if (isX86()) {
        m_currentBlock->appendNew<FenceValue>(m_proc, origin());
        return;
    }

    auto* slowPath = m_proc.addBlock();
    auto* continuation = m_proc.addBlock();

    auto* vm = vmValue();
    Value* shouldFence = m_currentBlock->appendNew<MemoryValue>(m_proc, Load8Z, Int32, origin(), vm, safeCast<int32_t>(VM::offsetOfHeapMutatorShouldBeFenced()));
    m_heaps.decorateMemory(&m_heaps.VM_heap_mutatorShouldBeFenced, shouldFence);

    m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(), shouldFence, FrequentedBlock(slowPath, FrequencyClass::Rare), FrequentedBlock(continuation));
    slowPath->addPredecessor(m_currentBlock);
    continuation->addPredecessor(m_currentBlock);

    m_currentBlock = slowPath;
    m_currentBlock->appendNew<FenceValue>(m_proc, origin());
    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);
    continuation->addPredecessor(m_currentBlock);

    m_currentBlock = continuation;
}

auto OMGIRGenerator::addAnyConvertExtern(ExpressionType reference, ExpressionType& result) -> PartialResult
{
    result = push(callWasmOperation(m_currentBlock, toB3Type(anyrefType()), operationWasmAnyConvertExtern, get(reference)));
    return { };
}

auto OMGIRGenerator::addExternConvertAny(ExpressionType reference, ExpressionType& result) -> PartialResult
{
    result = push(get(reference));
    return { };
}

auto OMGIRGenerator::addSelect(ExpressionType condition, ExpressionType nonZero, ExpressionType zero, ExpressionType& result) -> PartialResult
{
    result = push(m_currentBlock->appendNew<Value>(m_proc, B3::Select, origin(), get(condition), get(nonZero), get(zero)));
    return { };
}

OMGIRGenerator::ExpressionType OMGIRGenerator::addConstant(Type type, uint64_t value)
{
    return push(constant(toB3Type(type), value));
}

auto OMGIRGenerator::addSIMDSplat(SIMDLane lane, ExpressionType scalar, ExpressionType& result) -> PartialResult
{
    Value* toSplat = get(scalar);
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorSplat, B3::V128, lane, SIMDSignMode::None, toSplat));
    return { };
}

auto OMGIRGenerator::addSIMDShift(SIMDLaneOperation op, SIMDInfo info, ExpressionType v, ExpressionType shift, ExpressionType& result) -> PartialResult
{
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(),
        op == SIMDLaneOperation::Shr ? B3::VectorShr : B3::VectorShl, B3::V128, info, get(v), get(shift)));
    return { };
}

auto OMGIRGenerator::addSIMDExtmul(SIMDLaneOperation op, SIMDInfo info, ExpressionType lhs, ExpressionType rhs, ExpressionType& result) -> PartialResult
{
    ASSERT(info.signMode != SIMDSignMode::None);
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), op == SIMDLaneOperation::ExtmulLow ? VectorMulLow : VectorMulHigh, B3::V128, info, get(lhs), get(rhs)));
    return { };
}

auto OMGIRGenerator::addSIMDShuffle(v128_t imm, ExpressionType a, ExpressionType b, ExpressionType& result) -> PartialResult
{
    if constexpr (isX86()) {
        v128_t leftImm = imm;
        v128_t rightImm = imm;
        for (unsigned i = 0; i < 16; ++i) {
            if (leftImm.u8x16[i] > 15)
                leftImm.u8x16[i] = 0xFF; // Force OOB
            if (rightImm.u8x16[i] < 16 || rightImm.u8x16[i] > 31)
                rightImm.u8x16[i] = 0xFF; // Force OOB
            else
                rightImm.u8x16[i] -= 16; // Canonicalize to 0..15
        }
        // Store each byte (w/ index < 16) of `a` to result
        // and zero clear each byte (w/ index > 15) in result.
        Value* leftImmConst = m_currentBlock->appendNew<Const128Value>(m_proc, origin(), SIMDShuffle::toCanonicalUnaryPattern(leftImm));
        Value* leftResult = m_currentBlock->appendNew<SIMDValue>(m_proc, origin(),
            VectorSwizzle, B3::V128, SIMDLane::i8x16, SIMDSignMode::None, get(a), leftImmConst);

        // Store each byte (w/ original index in [16, 32)) of `b` to result2
        // and zero clear each byte that did not refer to `b` in result2.
        Value* rightImmConst = m_currentBlock->appendNew<Const128Value>(m_proc, origin(), SIMDShuffle::toCanonicalUnaryPattern(rightImm));
        Value* rightResult = m_currentBlock->appendNew<SIMDValue>(m_proc, origin(),
            VectorSwizzle, B3::V128, SIMDLane::i8x16, SIMDSignMode::None, get(b), rightImmConst);

        result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(),
            VectorOr, B3::V128, SIMDLane::v128, SIMDSignMode::None, leftResult, rightResult));

        return { };
    }

    if constexpr (!isARM64())
        UNREACHABLE_FOR_PLATFORM();

    Value* indexes = m_currentBlock->appendNew<Const128Value>(m_proc, origin(), imm);
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(),
        VectorSwizzle, B3::V128, SIMDLane::i8x16, SIMDSignMode::None, get(a), get(b), indexes));

    return { };
}

auto OMGIRGenerator::addSIMDLoad(ExpressionType pointerVariable, uint32_t uoffset, ExpressionType& result, uint8_t memoryIndex) -> PartialResult
{
    Value* ptr = emitCheckAndPreparePointer(get(pointerVariable), uoffset, 16, memoryIndex);
    int32_t offset = fixupPointerPlusOffset(ptr, uoffset);
    auto* value = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), B3::V128, origin(), ptr, offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, value);
    result = push(value);

    return { };
}

auto OMGIRGenerator::addSIMDStore(ExpressionType value, ExpressionType pointerVariable, uint32_t uoffset, uint8_t memoryIndex) -> PartialResult
{
    Value* ptr = emitCheckAndPreparePointer(get(pointerVariable), uoffset, 16, memoryIndex);
    int32_t offset = fixupPointerPlusOffset(ptr, uoffset);
    auto* store = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Store), origin(), get(value), ptr, offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, store);

    return { };
}

auto OMGIRGenerator::addSIMDLoadSplat(SIMDLaneOperation op, ExpressionType pointerVariable, uint32_t uoffset, ExpressionType& result, uint8_t memoryIndex) -> PartialResult
{
    size_t byteSize;

    B3::Opcode loadOp;
    B3::Type type;
    SIMDLane lane;
    switch (op) {
    case SIMDLaneOperation::LoadSplat8:
        loadOp = Load8Z;
        type = B3::Int32;
        lane = SIMDLane::i8x16;
        byteSize = 1;
        break;
    case SIMDLaneOperation::LoadSplat16:
        loadOp = Load16Z;
        type = B3::Int32;
        lane = SIMDLane::i16x8;
        byteSize = 2;
        break;
    case SIMDLaneOperation::LoadSplat32:
        loadOp = Load;
        type = B3::Int32;
        lane = SIMDLane::i32x4;
        byteSize = 4;
        break;
    case SIMDLaneOperation::LoadSplat64:
        loadOp = Load;
        type = B3::Int64;
        lane = SIMDLane::i64x2;
        byteSize = 8;
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
    }

    Value* ptr = emitCheckAndPreparePointer(get(pointerVariable), uoffset, byteSize, memoryIndex);
    int32_t offset = fixupPointerPlusOffset(ptr, uoffset);
    auto* memLoad = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(loadOp), type, origin(), ptr, offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, memLoad);
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorSplat, B3::V128, lane, SIMDSignMode::None, memLoad));

    return { };
}

auto OMGIRGenerator::addSIMDLoadLane(SIMDLaneOperation op, ExpressionType pointerVariable, ExpressionType vectorVariable, uint32_t uoffset, uint8_t laneIndex, ExpressionType& result, uint8_t memoryIndex) -> PartialResult
{
    size_t byteSize;
    B3::Opcode loadOp;
    B3::Type type;
    SIMDLane lane;
    switch (op) {
    case SIMDLaneOperation::LoadLane8:
        loadOp = Load8Z;
        type = B3::Int32;
        lane = SIMDLane::i8x16;
        byteSize = 1;
        break;
    case SIMDLaneOperation::LoadLane16:
        loadOp = Load16Z;
        type = B3::Int32;
        lane = SIMDLane::i16x8;
        byteSize = 2;
        break;
    case SIMDLaneOperation::LoadLane32:
        loadOp = Load;
        type = B3::Int32;
        lane = SIMDLane::i32x4;
        byteSize = 4;
        break;
    case SIMDLaneOperation::LoadLane64:
        loadOp = Load;
        type = B3::Int64;
        lane = SIMDLane::i64x2;
        byteSize = 8;
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
    }

    Value* ptr = emitCheckAndPreparePointer(get(pointerVariable), uoffset, byteSize, memoryIndex);
    int32_t offset = fixupPointerPlusOffset(ptr, uoffset);
    auto* memLoad = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(loadOp), type, origin(), ptr, offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, memLoad);
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorReplaceLane, B3::V128, lane, SIMDSignMode::None, laneIndex, get(vectorVariable), memLoad));

    return { };
}

auto OMGIRGenerator::addSIMDStoreLane(SIMDLaneOperation op, ExpressionType pointerVariable, ExpressionType vectorVariable, uint32_t uoffset, uint8_t laneIndex, uint8_t memoryIndex) -> PartialResult
{
    size_t byteSize;
    B3::Opcode storeOp;
    B3::Type type;
    SIMDLane lane;
    switch (op) {
    case SIMDLaneOperation::StoreLane8:
        storeOp = Store8;
        type = B3::Int32;
        lane = SIMDLane::i8x16;
        byteSize = 1;
        break;
    case SIMDLaneOperation::StoreLane16:
        storeOp = Store16;
        type = B3::Int32;
        lane = SIMDLane::i16x8;
        byteSize = 2;
        break;
    case SIMDLaneOperation::StoreLane32:
        storeOp = Store;
        type = B3::Int32;
        lane = SIMDLane::i32x4;
        byteSize = 4;
        break;
    case SIMDLaneOperation::StoreLane64:
        storeOp = Store;
        type = B3::Int64;
        lane = SIMDLane::i64x2;
        byteSize = 8;
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
    }

    Value* ptr = emitCheckAndPreparePointer(get(pointerVariable), uoffset, byteSize, memoryIndex);
    int32_t offset = fixupPointerPlusOffset(ptr, uoffset);
    Value* laneValue = m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorExtractLane, type, lane, byteSize < 4 ? SIMDSignMode::Unsigned : SIMDSignMode::None, laneIndex, get(vectorVariable));
    auto* store = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(storeOp), origin(), laneValue, ptr, offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, store);

    return { };
}

auto OMGIRGenerator::addSIMDLoadExtend(SIMDLaneOperation op, ExpressionType pointerVariable, uint32_t uoffset, ExpressionType& result, uint8_t memoryIndex) -> PartialResult
{
    B3::Opcode loadOp = Load;
    size_t byteSize = 8;
    SIMDLane lane;
    SIMDSignMode signMode;
    switch (op) {
    case SIMDLaneOperation::LoadExtend8U:
        lane = SIMDLane::i16x8;
        signMode = SIMDSignMode::Unsigned;
        break;
    case SIMDLaneOperation::LoadExtend8S:
        lane = SIMDLane::i16x8;
        signMode = SIMDSignMode::Signed;
        break;
    case SIMDLaneOperation::LoadExtend16U:
        lane = SIMDLane::i32x4;
        signMode = SIMDSignMode::Unsigned;
        break;
    case SIMDLaneOperation::LoadExtend16S:
        lane = SIMDLane::i32x4;
        signMode = SIMDSignMode::Signed;
        break;
    case SIMDLaneOperation::LoadExtend32U:
        lane = SIMDLane::i64x2;
        signMode = SIMDSignMode::Unsigned;
        break;
    case SIMDLaneOperation::LoadExtend32S:
        lane = SIMDLane::i64x2;
        signMode = SIMDSignMode::Signed;
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
    }

    Value* ptr = emitCheckAndPreparePointer(get(pointerVariable), uoffset, byteSize, memoryIndex);
    int32_t offset = fixupPointerPlusOffset(ptr, uoffset);
    auto* memLoad = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(loadOp), B3::Double, origin(), ptr, offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, memLoad);
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), VectorExtendLow, B3::V128, SIMDInfo { lane, signMode }, memLoad));

    return { };
}

auto OMGIRGenerator::addSIMDLoadPad(SIMDLaneOperation op, ExpressionType pointerVariable, uint32_t uoffset, ExpressionType& result, uint8_t memoryIndex) -> PartialResult
{
    B3::Type loadType;
    unsigned byteSize;
    SIMDLane lane;
    uint8_t idx = 0;
    switch (op) {
    case SIMDLaneOperation::LoadPad32:
        loadType = B3::Float;
        byteSize = 4;
        lane = SIMDLane::f32x4;
        break;
    case SIMDLaneOperation::LoadPad64:
        loadType = B3::Double;
        byteSize = 8;
        lane = SIMDLane::f64x2;
        break;
    default:
        RELEASE_ASSERT_NOT_REACHED();
    }

    Value* ptr = emitCheckAndPreparePointer(get(pointerVariable), uoffset, byteSize, memoryIndex);
    int32_t offset = fixupPointerPlusOffset(ptr, uoffset);
    auto* memLoad = m_currentBlock->appendNew<MemoryValue>(m_proc, memoryKind(Load), loadType, origin(), ptr, offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyMemory, memLoad);
    result = push(m_currentBlock->appendNew<SIMDValue>(m_proc, origin(), B3::VectorReplaceLane, B3::V128, lane, SIMDSignMode::None, idx,
        m_currentBlock->appendNew<Const128Value>(m_proc, origin(), v128_t { }),
        memLoad));

    return { };
}

Value* OMGIRGenerator::loadFromScratchBuffer(unsigned& indexInBuffer, Value* pointer, B3::Type type)
{
    int32_t offset = safeCast<int32_t>(sizeof(Wasm::Context::ScratchBufferEntry) * (indexInBuffer++));
    RELEASE_ASSERT(type.isNumeric());
    return m_currentBlock->appendNew<MemoryValue>(m_proc, Load, type, origin(), pointer, offset);
}

void OMGIRGenerator::connectValuesAtEntrypoint(unsigned& indexInBuffer, Value* pointer, std::span<const TypedExpression> expressionStack)
{
    TRACE_CF("Connect values at entrypoint");
    for (const TypedExpression& expr : expressionStack) {
        if (!expr.value().isMaterialized()) {
            RELEASE_ASSERT(expr.value().b3Value()->isConstant());
            indexInBuffer++;
            continue;
        }
        Variable* var = expr.value().b3Variable();
        Value* load = loadFromScratchBuffer(indexInBuffer, pointer, var->type());
        set(var, load);
    }
};

auto OMGIRGenerator::addLoop(BlockSignature&& signature, std::span<TypedExpression> args, ControlType& block, uint32_t loopIndex) -> PartialResult
{
    auto enclosingStack = m_parser->expressionStack();
    TRACE_CF("LOOP: entering loop index: ", loopIndex, " signature: ", signature);
    BasicBlock* body = m_proc.addBlock();
    BasicBlock* continuation = m_proc.addBlock();

    block = ControlData(m_proc, origin(), WTF::move(signature), BlockType::Loop, continuation, body);

    for (unsigned i = 0; i < block.signature().argumentCount(); ++i) {
        TypedExpression value = args[i];
        Value* phi = block.phis[i];
        m_currentBlock->appendNew<UpsilonValue>(m_proc, origin(), get(value), phi);
        body->append(phi);
        // Replace args in place: the parser keeps them as the new block's stack.
        args[i] = TypedExpression(block.signature().argumentType(i), phi);
    }

    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), body);
    if (loopIndex == m_loopIndexForOSREntry) {
        // This must be kept in sync with BBQJIT::makeStackMap.
        dataLogLnIf(WasmOMGIRGeneratorInternal::verbose, "Setting up for OSR entry");

        ASSERT(!m_inlineParent);
        materializeExpressionStackIntoVariables();

        m_currentBlock = m_rootBlocks[0];
        Value* pointer = m_rootBlocks[0]->appendNew<ArgumentRegValue>(m_proc, Origin(), GPRInfo::argumentGPR0);

        unsigned indexInBuffer = 0;

        for (auto& local : m_locals)
            m_currentBlock->appendNew<VariableValue>(m_proc, Set, Origin(), local, loadFromScratchBuffer(indexInBuffer, pointer, local->type()));

        for (auto& control : m_parser->controlStack()) {
            auto& data = control.controlData;
            if (ControlType::isAnyCatch(data)) {
                auto* load = loadFromScratchBuffer(indexInBuffer, pointer, pointerType());
                m_currentBlock->appendNew<VariableValue>(m_proc, Set, origin(), data.exception(), load);
            } else if (ControlType::isTry(data))
                ++indexInBuffer;
        }

        for (size_t controlIndex = 0; controlIndex < m_parser->controlStack().size(); ++controlIndex) {
            ASSERT(&m_parser->controlStack()[controlIndex].controlData != &block);
            connectValuesAtEntrypoint(indexInBuffer, pointer, m_parser->enclosedSliceOf(controlIndex));
        }
        // Args are loaded separately into the loop's phis below; trim them off here.
        ASSERT(enclosingStack.size() >= args.size());
        connectValuesAtEntrypoint(indexInBuffer, pointer, enclosingStack.first(enclosingStack.size() - args.size()));
        // The loop's stack can be read by the loop body, so the restored values should join using the loop-back phi nodes.
        for (unsigned i = 0; i < args.size(); i++) {
            auto* load = loadFromScratchBuffer(indexInBuffer, pointer, args[i].value().type());
            m_currentBlock->appendNew<UpsilonValue>(m_proc, origin(), load, block.phis[i]);
        }

        ASSERT(!m_proc.usesSIMD() || m_compilationMode == CompilationMode::OMGForOSREntryMode);
        *m_osrEntryScratchBufferSize = indexInBuffer;
        m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), body);
        body->addPredecessor(m_currentBlock);
    }

    m_currentBlock = body;
    return { };
}

OMGIRGenerator::ControlData OMGIRGenerator::addTopLevel(BlockSignature&& signature)
{
    TRACE_CF("TopLevel: ", signature);
    ControlData topLevel = ControlData(m_proc, Origin(), WTF::move(signature), BlockType::TopLevel, m_proc.addBlock());
    return topLevel;
}

auto OMGIRGenerator::addBlock(BlockSignature&& signature, std::span<TypedExpression> args, ControlType& newBlock) -> PartialResult
{
    UNUSED_PARAM(args);
    TRACE_CF("Block: ", signature);
    BasicBlock* continuation = m_proc.addBlock();

    newBlock = ControlData(m_proc, origin(), WTF::move(signature), BlockType::Block, continuation);
    return { };
}

auto OMGIRGenerator::addIf(ExpressionType condition, BlockSignature&& signature, std::span<TypedExpression> args, ControlType& result) -> PartialResult
{
    UNUSED_PARAM(args);
    // FIXME: This needs to do some kind of stack passing.

    BasicBlock* taken = m_proc.addBlock();
    BasicBlock* notTaken = m_proc.addBlock();
    BasicBlock* continuation = m_proc.addBlock();
    FrequencyClass takenFrequency = FrequencyClass::Normal;
    FrequencyClass notTakenFrequency = FrequencyClass::Normal;

    BranchHint hint = m_info.getBranchHint(m_functionIndex, m_parser->currentOpcodeStartingOffset());
    switch (hint) {
    case BranchHint::Unlikely:
        takenFrequency = FrequencyClass::Rare;
        break;
    case BranchHint::Likely:
        notTakenFrequency = FrequencyClass::Rare;
        break;
    case BranchHint::Invalid:
        break;
    }

    m_currentBlock->appendNew<Value>(m_proc, B3::Branch, origin(), get(condition));
    m_currentBlock->setSuccessors(FrequentedBlock(taken, takenFrequency), FrequentedBlock(notTaken, notTakenFrequency));
    taken->addPredecessor(m_currentBlock);
    notTaken->addPredecessor(m_currentBlock);

    m_currentBlock = taken;
    TRACE_CF("IF");
    result = ControlData(m_proc, origin(), WTF::move(signature), BlockType::If, continuation, notTaken);
    return { };
}

auto OMGIRGenerator::addElse(ControlData& data, std::span<const TypedExpression> currentStack) -> PartialResult
{
    unifyValuesWithBlock(currentStack, data);
    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), data.continuation);
    return addElseToUnreachable(data);
}

auto OMGIRGenerator::addElseToUnreachable(ControlData& data) -> PartialResult
{
    ASSERT(data.blockType() == BlockType::If);
    m_currentBlock = data.special;
    data.convertIfToBlock();
    TRACE_CF("ELSE");
    return { };
}

auto OMGIRGenerator::addTry(BlockSignature&& signature, std::span<TypedExpression> args, ControlType& result) -> PartialResult
{
    UNUSED_PARAM(args);
    ++m_tryCatchDepth;
    TRACE_CF("TRY");

    BasicBlock* continuation = m_proc.addBlock();
    materializeExpressionStackIntoVariables();
    result = ControlData(m_proc, origin(), WTF::move(signature), BlockType::Try, continuation, advanceCallSiteIndex(), m_tryCatchDepth);
    return { };
}

auto OMGIRGenerator::addTryTable(BlockSignature&& signature, std::span<TypedExpression> args, const Vector<CatchHandler>& targets, ControlType& result) -> PartialResult
{
    UNUSED_PARAM(args);
    ++m_tryCatchDepth;
    TRACE_CF("TRY");

    auto targetList = targets.map(
        [&](const auto& target) -> ControlData::TryTableTarget {
            return {
                target.type,
                target.tag,
                target.exceptionSignature,
                target.target
            };
        }
    );

    BasicBlock* continuation = m_proc.addBlock();
    materializeExpressionStackIntoVariables();
    result = ControlData(m_proc, origin(), WTF::move(signature), BlockType::TryTable, continuation, advanceCallSiteIndex(), m_tryCatchDepth);
    result.setTryTableTargets(WTF::move(targetList));

    return { };
}

auto OMGIRGenerator::addCatch(unsigned exceptionIndex, const RTT& signature, std::span<const TypedExpression> currentStack, ControlType& data, ResultList& results) -> PartialResult
{
    TRACE_CF("CATCH: ", signature);
    unifyValuesWithBlock(currentStack, data);
    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), data.continuation);
    return addCatchToUnreachable(exceptionIndex, signature, data, results);
}

// Must be kept in sync with connectValuesForCatchEntrypoint. Creates a stackmap for the
// wasm expression stack up to the inner most Try/TryTable, which is the point in
// the stack that the corresponding catch entrypoint will need to restore.
RefPtr<PatchpointExceptionHandle> OMGIRGenerator::preparePatchpointForExceptions(BasicBlock* block, PatchpointValue* patch)
{
    bool mustSaveState = m_tryCatchDepth;

    if (!mustSaveState)
        return nullptr;

    unsigned firstStackmapChildOffset = patch->numChildren();
    unsigned firstStackmapParamOffset = firstStackmapChildOffset + m_proc.resultCount(patch->type());

    Vector<Value*> liveValues;
    Origin origin = this->origin();

    OMGIRGenerator* innerTryFrame = nullptr;
    unsigned innerTryControlStackIndex = 0;

    Vector<OMGIRGenerator*> frames;
    for (auto* currentFrame = this; currentFrame; currentFrame = currentFrame->m_inlineParent) {
        if (!innerTryFrame) {
            for (unsigned i = currentFrame->m_parser->controlStack().size(); i--; ) {
                ControlData& data = currentFrame->m_parser->controlStack()[i].controlData;
                if (ControlType::isTry(data) || ControlType::isTryTable(data)) {
                    innerTryFrame = currentFrame;
                    innerTryControlStackIndex = i;
                    break;
                }
            }
        }
        frames.append(currentFrame);
    }
    frames.reverse();

    if (!innerTryFrame)
        return nullptr; // We're inside a Catch but not a Try (since m_tryCatchDepth != 0).

    for (auto* currentFrame : frames) {
        for (Variable* local : currentFrame->m_locals) {
            Value* result = block->appendNew<VariableValue>(m_proc, B3::Get, origin, local);
            liveValues.append(result);
        }
        unsigned end = currentFrame == innerTryFrame ? innerTryControlStackIndex + 1 : currentFrame->m_parser->controlStack().size();
        for (unsigned controlIndex = 0; controlIndex < end; ++controlIndex) {
            ControlData& data = currentFrame->m_parser->controlStack()[controlIndex].controlData;
            for (ExpressionType expr : currentFrame->m_parser->enclosedSliceOf(controlIndex))
                liveValues.append(get(block, expr));
            if (ControlType::isAnyCatch(data))
                liveValues.append(get(block, data.exception()));
        }
        if (currentFrame == innerTryFrame)
            break;
        ASSERT(currentFrame != this); // Should have encountered the inner most Try by now.
        for (ExpressionType expr : currentFrame->m_parser->expressionStack())
            liveValues.append(get(block, expr));
    }

    patch->effects.exitsSideways = true;
    patch->appendVectorWithRep(liveValues, ValueRep::LateColdAny);

    return PatchpointExceptionHandle::create(m_hasExceptionHandlers, callSiteIndex(), static_cast<unsigned>(liveValues.size()), firstStackmapParamOffset, firstStackmapChildOffset);
}

// Materializes the wasm expression stack into variables so that Catch block and loop OSR entrypoints have a place
// to restore the wasm stack state. Note that catch labels always occur after Try/TryTable, so materalizing when
// the Try block is encountered works even with loops.
void OMGIRGenerator::materializeExpressionStackIntoVariables()
{
    class Materializer {
    public:
        Materializer(Procedure& proc)
            : m_proc(proc)
            , m_insertionSet(proc) { }

        ~Materializer()
        {
            endBlock(nullptr);
        }

        void convertToVariable(OMGExpression& expr, Variable* variable)
        {
            if (expr.isMaterialized() || expr.b3Value()->isConstant())
                return;
            ASSERT(!expr.isMaterialized());
            Value* value = expr.b3Value();
            BasicBlock* block = value->owner;

            if (block != m_block)
                endBlock(block);

            while (m_block->at(m_instIndex++) != value)
                ASSERT(m_instIndex < m_block->size());

            Value* setVariable = m_proc.add<VariableValue>(B3::Set, value->origin(), variable, value);
            m_insertionSet.insertValue(m_instIndex, setVariable);

            expr.setMaterialized(variable);
        }

        void endBlock(BasicBlock* nextBlock)
        {
            if (m_block)
                m_insertionSet.execute(m_block);
            m_block = nextBlock;
            m_instIndex = 0;
        }

    private:
        Procedure& m_proc;
        InsertionSet m_insertionSet;
        BasicBlock* m_block { nullptr };
        unsigned m_instIndex { 0 };
    };

    Materializer materializer(m_proc);

    Vector<OMGIRGenerator*> frames;
    for (auto* currentFrame = this; currentFrame; currentFrame = currentFrame->m_inlineParent)
        frames.append(currentFrame);
    frames.reverse();

    for (auto* currentFrame : frames) {
        auto* parser = currentFrame->m_parser;

        for (size_t controlIndex = 0; controlIndex < parser->controlStack().size(); ++controlIndex) {
            for (auto& expr : parser->enclosedSliceOf(controlIndex))
                materializer.convertToVariable(expr.value(), m_proc.addVariable(expr.value().type()));
        }
        // Note that this is the not yet (but soon to be) enclosed slice for the Try/TryTable/Loop.
        for (auto& expr : parser->expressionStack())
            materializer.convertToVariable(expr.value(), m_proc.addVariable(expr.value().type()));
    }
}

// Must be kept in sync with preparePatchpointForExceptions.
void OMGIRGenerator::connectValuesForCatchEntrypoint(ControlData& catchData, Value* pointer)
{
    unsigned indexInBuffer = 0;

    Vector<OMGIRGenerator*> frames;
    for (auto* currentFrame = this; currentFrame; currentFrame = currentFrame->m_inlineParent)
        frames.append(currentFrame);
    frames.reverse();

    for (auto* currentFrame : frames) {
        for (auto& local : currentFrame->m_locals)
            m_currentBlock->appendNew<VariableValue>(m_proc, Set, Origin(), local, loadFromScratchBuffer(indexInBuffer, pointer, local->type()));

        for (size_t controlIndex = 0; controlIndex < currentFrame->m_parser->controlStack().size(); ++controlIndex) {
            auto& controlData = currentFrame->m_parser->controlStack()[controlIndex].controlData;
            connectValuesAtEntrypoint(indexInBuffer, pointer, currentFrame->m_parser->enclosedSliceOf(controlIndex));
            if (ControlType::isAnyCatch(controlData) && &controlData != &catchData) {
                auto* load = loadFromScratchBuffer(indexInBuffer, pointer, pointerType());
                m_currentBlock->appendNew<VariableValue>(m_proc, Set, origin(), controlData.exception(), load);
            }
        }
        // inlineParent frames only
        if (currentFrame != this) {
            connectValuesAtEntrypoint(indexInBuffer, pointer, currentFrame->m_parser->expressionStack());
        }
    }
}

auto OMGIRGenerator::addCatchToUnreachable(unsigned exceptionIndex, const RTT& signature, ControlType& data, ResultList& results) -> PartialResult
{
    Value* payload = emitCatchImpl(CatchKind::Catch, data, exceptionIndex);
    unsigned offset = 0;
    for (unsigned i = 0; i < signature.argumentCount(); ++i) {
        Type type = signature.argumentType(i);
        Value* value = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, toB3Type(type), origin(), payload, safeCast<int32_t>(offset * sizeof(uint64_t)));
        results.append(push(value));
        offset += type.kind == TypeKind::V128 ? 2 : 1;
    }
    TRACE_CF("CATCH");
    return { };
}

auto OMGIRGenerator::addCatchAll(std::span<const TypedExpression> currentStack, ControlType& data) -> PartialResult
{
    unifyValuesWithBlock(currentStack, data);
    TRACE_CF("CATCH_ALL");
    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), data.continuation);
    return addCatchAllToUnreachable(data);
}

auto OMGIRGenerator::addCatchAllToUnreachable(ControlType& data) -> PartialResult
{
    emitCatchImpl(CatchKind::CatchAll, data);
    return { };
}

Value* OMGIRGenerator::emitCatchImpl(CatchKind kind, ControlType& data, unsigned exceptionIndex)
{
    m_currentBlock = m_proc.addBlock();
    m_rootBlocks.append(m_currentBlock);

    if (ControlType::isTry(data)) {
        if (kind == CatchKind::Catch)
            data.convertTryToCatch(advanceCallSiteIndex(), m_proc.addVariable(pointerType()));
        else
            data.convertTryToCatchAll(advanceCallSiteIndex(), m_proc.addVariable(pointerType()));
    }
    // We convert from "try" to "catch" ControlType above. This doesn't
    // happen if ControlType is already a "catch". This can happen when
    // we have multiple catches like "try {} catch(A){} catch(B){}...CatchAll(E){}"
    ASSERT(ControlType::isAnyCatch(data));

    HandlerType handlerType = kind == CatchKind::Catch ? HandlerType::Catch : HandlerType::CatchAll;
    m_exceptionHandlers.append({ handlerType, data.tryStart(), data.tryEnd(), 0, m_tryCatchDepth, exceptionIndex });

    Value* pointer = m_currentBlock->appendNew<ArgumentRegValue>(m_proc, Origin(), GPRInfo::argumentGPR0);
    Value* exception = m_currentBlock->appendNew<ArgumentRegValue>(m_proc, Origin(), GPRInfo::argumentGPR1);
    Value* buffer = m_currentBlock->appendNew<ArgumentRegValue>(m_proc, Origin(), GPRInfo::argumentGPR2);

    connectValuesForCatchEntrypoint(data, pointer);

    set(data.exception(), exception);
    TRACE_CF("CATCH");

    return buffer;
}

auto OMGIRGenerator::emitCatchTableImpl(ControlData& data, const ControlData::TryTableTarget& target) -> void
{
    auto block = m_proc.addBlock();
    m_rootBlocks.append(block);
    auto oldBlock = m_currentBlock;
    m_currentBlock = block;

    HandlerType handlerType;
    switch (target.type) {
    case CatchKind::Catch:
        handlerType = HandlerType::TryTableCatch;
        break;
    case CatchKind::CatchRef:
        handlerType = HandlerType::TryTableCatchRef;
        break;
    case CatchKind::CatchAll:
        handlerType = HandlerType::TryTableCatchAll;
        break;
    case CatchKind::CatchAllRef:
        handlerType = HandlerType::TryTableCatchAllRef;
        break;
    }
    m_exceptionHandlers.append({ handlerType, data.tryStart(), data.tryEnd(), 0, m_tryCatchDepth, target.tag });

    auto signature = target.exceptionSignature;

    Value* pointer = m_currentBlock->appendNew<ArgumentRegValue>(m_proc, Origin(), GPRInfo::argumentGPR0);
    Value* exception = m_currentBlock->appendNew<ArgumentRegValue>(m_proc, Origin(), GPRInfo::argumentGPR1);
    Value* buffer = m_currentBlock->appendNew<ArgumentRegValue>(m_proc, Origin(), GPRInfo::argumentGPR2);

    connectValuesForCatchEntrypoint(data, pointer);

    Stack resultStack;
    if (target.type == CatchKind::Catch || target.type == CatchKind::CatchRef) {
        unsigned offset = 0;
        for (unsigned i = 0; i < signature->argumentCount(); ++i) {
            Type type = signature->argumentType(i);
            Value* value = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, toB3Type(type), origin(), buffer, safeCast<int32_t>(offset * sizeof(uint64_t)));
            resultStack.constructAndAppend(type, value);
            offset += type.kind == TypeKind::V128 ? 2 : 1;
        }
    }

    if (target.type == CatchKind::CatchRef || target.type == CatchKind::CatchAllRef) {
        exception = wasmRefOfCell(exception);
        resultStack.constructAndAppend(Type { TypeKind::RefNull, static_cast<TypeIndex>(TypeKind::Exnref) }, exception);
    }

    auto& targetControl = m_parser->resolveControlRef(target.target).controlData;
    unifyValuesWithBlock(resultStack, targetControl);

    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), FrequentedBlock(targetControl.targetBlockForBranch(), FrequencyClass::Normal));
    targetControl.targetBlockForBranch()->addPredecessor(block);

    m_currentBlock = oldBlock;
}

auto OMGIRGenerator::addDelegate(ControlType& target, ControlType& data) -> PartialResult
{
    return addDelegateToUnreachable(target, data);
}

auto OMGIRGenerator::addDelegateToUnreachable(ControlType& target, ControlType& data) -> PartialResult
{
    TRACE_CF("DELEGATE");
    unsigned targetDepth = 0;
    if (m_inlineParent)
        targetDepth += m_inlineParent->m_tryCatchDepth;

    if (ControlType::isTry(target))
        targetDepth = target.tryDepth();

    m_exceptionHandlers.append({ HandlerType::Delegate, data.tryStart(), advanceCallSiteIndex(), 0, m_tryCatchDepth, targetDepth });
    return { };
}

auto OMGIRGenerator::addThrow(unsigned exceptionIndex, ArgumentList& args, std::span<const TypedExpression>) -> PartialResult
{
    TRACE_CF("THROW");

    advanceCallSiteIndex();
    PatchpointValue* patch = m_proc.add<PatchpointValue>(B3::Void, origin(), cloningForbidden(Patchpoint));
    patch->effects.terminal = true;
    patch->append(instanceValue(), ValueRep::reg(GPRInfo::argumentGPR0));
    unsigned offset = 0;
    for (auto arg : args) {
        patch->append(get(arg), ValueRep::stackArgument(safeCast<int32_t>(offset * sizeof(EncodedJSValue))));
        offset += arg.value().type().isVector() ?  2 : 1;
    }
    m_maxNumJSCallArguments = std::max(m_maxNumJSCallArguments, offset);
    patch->clobber(RegisterSet::registersToSaveForJSCall(m_proc.usesSIMD() ? RegisterSet::allRegisters() : RegisterSet::allScalarRegisters()));
    auto handle = preparePatchpointForExceptions(m_currentBlock, patch);
    patch->setGenerator([this, exceptionIndex, handle = WTF::move(handle), origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        if (handle)
            handle->collectStackMap(this, params);
        RELEASE_ASSERT(origin.wasmOrigin());
        emitThrowImpl(jit, exceptionIndex);
    });
    m_currentBlock->append(patch);

    return { };
}

[[nodiscard]] auto OMGIRGenerator::addThrowRef(TypedExpression exnref, std::span<const TypedExpression>) -> PartialResult
{
    TRACE_CF("THROW_REF");

    Value* exception = get(exnref);
    if (exnref.type().isNullable())
        emitNullCheck(exception, ExceptionType::NullExnrefReference);

    advanceCallSiteIndex();
    PatchpointValue* patch = m_proc.add<PatchpointValue>(B3::Void, origin(), cloningForbidden(Patchpoint));
    patch->clobber(RegisterSet::registersToSaveForJSCall(m_proc.usesSIMD() ? RegisterSet::allRegisters() : RegisterSet::allScalarRegisters()));
    patch->effects.terminal = true;
    patch->append(instanceValue(), ValueRep::reg(GPRInfo::argumentGPR0));
    patch->append(exception , ValueRep::reg(GPRInfo::argumentGPR1));
    auto handle = preparePatchpointForExceptions(m_currentBlock, patch);
    patch->setGenerator([this, handle = WTF::move(handle), origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        if (handle)
            handle->collectStackMap(this, params);
        RELEASE_ASSERT(origin.wasmOrigin());
        emitThrowRefImpl(jit);
    });
    m_currentBlock->append(patch);
    return { };
}

auto OMGIRGenerator::addRethrow(unsigned, ControlType& data) -> PartialResult
{
    TRACE_CF("RETHROW");

    advanceCallSiteIndex();
    PatchpointValue* patch = m_proc.add<PatchpointValue>(B3::Void, origin(), cloningForbidden(Patchpoint));
    patch->clobber(RegisterSet::registersToSaveForJSCall(m_proc.usesSIMD() ? RegisterSet::allRegisters() : RegisterSet::allScalarRegisters()));
    patch->effects.terminal = true;
    patch->append(instanceValue(), ValueRep::reg(GPRInfo::argumentGPR0));
    patch->append(get(data.exception()), ValueRep::reg(GPRInfo::argumentGPR1));
    auto handle = preparePatchpointForExceptions(m_currentBlock, patch);
    patch->setGenerator([this, handle = WTF::move(handle), origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        if (handle)
            handle->collectStackMap(this, params);
        RELEASE_ASSERT(origin.wasmOrigin());
        emitThrowRefImpl(jit);
    });
    m_currentBlock->append(patch);

    return { };
}

auto OMGIRGenerator::addInlinedReturn(const auto& returnValues) -> PartialResult
{
    dataLogLnIf(WasmOMGIRGeneratorInternal::verboseInlining, "Returning inline to BB ", *m_returnContinuation);

    const auto& signature = m_parser->signatureRTT();
    CallInformation wasmCallInfo = wasmCallingConvention().callInformationFor(signature, CallRole::Callee);
    RELEASE_ASSERT(returnValues.size() >= wasmCallInfo.results.size());
    RELEASE_ASSERT(signature.returnCount() == wasmCallInfo.results.size());
    RELEASE_ASSERT(m_inlinedResultPhis.size() == wasmCallInfo.results.size());

    unsigned offset = returnValues.size() - wasmCallInfo.results.size();
    for (unsigned i = 0; i < wasmCallInfo.results.size(); ++i)
        m_currentBlock->appendNew<UpsilonValue>(m_proc, origin(), get(returnValues[offset + i]), m_inlinedResultPhis[i]);

    m_currentBlock->appendNewControlValue(m_proc, B3::Jump, origin(), FrequentedBlock(m_returnContinuation));
    return { };
}

auto OMGIRGenerator::addReturn(const ControlData&, std::span<const TypedExpression> returnValues) -> PartialResult
{
    TRACE_CF("RETURN");
    if (m_returnContinuation)
        return addInlinedReturn(returnValues);

    // Use the function signature from the parser
    ASSERT(m_parser);
    const RTT& functionSignature = m_parser->signatureRTT();

    CallInformation wasmCallInfo = wasmCallingConvention().callInformationFor(functionSignature, CallRole::Callee);
    PatchpointValue* patch = m_proc.add<PatchpointValue>(B3::Void, origin());
    patch->setGenerator([] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        params.code().emitEpilogue(jit);
    });
    patch->effects.terminal = true;

    RELEASE_ASSERT(returnValues.size() >= wasmCallInfo.results.size());
    unsigned offset = returnValues.size() - wasmCallInfo.results.size();
    for (unsigned i = 0; i < wasmCallInfo.results.size(); ++i) {
        B3::ValueRep rep = wasmCallInfo.results[i].location;
        if (rep.isStack()) {
            B3::Value* address = m_currentBlock->appendNew<B3::Value>(m_proc, B3::Add, Origin(), framePointer(), constant(pointerType(), rep.offsetFromFP()));
            m_currentBlock->appendNew<B3::MemoryValue>(m_proc, B3::Store, Origin(), get(returnValues[offset + i]), address);
        } else {
            ASSERT(rep.isReg());
            patch->append(get(returnValues[offset + i]), rep);
        }

        TRACE_VALUE(functionSignature.returnType(i), get(returnValues[offset + i]), "put to return value ", i);
    }

    m_currentBlock->append(patch);
    return { };
}

auto OMGIRGenerator::addBranch(ControlData& data, ExpressionType condition, std::span<const TypedExpression> returnValues) -> PartialResult
{
    unifyValuesWithBlock(returnValues, data);

    BasicBlock* target = data.targetBlockForBranch();
    FrequencyClass targetFrequency = FrequencyClass::Normal;
    FrequencyClass continuationFrequency = FrequencyClass::Normal;

    BranchHint hint = m_info.getBranchHint(m_functionIndex, m_parser->currentOpcodeStartingOffset());
    switch (hint) {
    case BranchHint::Unlikely:
        targetFrequency = FrequencyClass::Rare;
        break;
    case BranchHint::Likely:
        continuationFrequency = FrequencyClass::Rare;
        break;
    case BranchHint::Invalid:
        break;
    }

    TRACE_CF("BRANCH to ", *target);

    if (!condition.isEmpty()) {
        BasicBlock* continuation = m_proc.addBlock();
        m_currentBlock->appendNew<Value>(m_proc, B3::Branch, origin(), get(condition));
        m_currentBlock->setSuccessors(FrequentedBlock(target, targetFrequency), FrequentedBlock(continuation, continuationFrequency));
        target->addPredecessor(m_currentBlock);
        continuation->addPredecessor(m_currentBlock);
        m_currentBlock = continuation;
    } else {
        m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), FrequentedBlock(target, targetFrequency));
        target->addPredecessor(m_currentBlock);
    }

    return { };
}

auto OMGIRGenerator::addBranchNull(ControlData& data, ExpressionType reference, std::span<const TypedExpression> returnValues, bool shouldNegate, ExpressionType& result) -> PartialResult
{
    auto condition = push(m_currentBlock->appendNew<Value>(m_proc, shouldNegate ? B3::NotEqual : B3::Equal, origin(), get(reference), m_currentBlock->appendNew<WasmConstRefValue>(m_proc, origin(), JSValue::encode(jsNull()))));

    WASM_FAIL_IF_HELPER_FAILS(addBranch(data, condition, returnValues));

    if (!shouldNegate)
        result = push(get(reference));

    return { };
}

auto OMGIRGenerator::addBranchCast(ControlData& data, TypedExpression reference, std::span<const TypedExpression> returnValues, bool allowNull, int32_t heapType, bool shouldNegate) -> PartialResult
{
    ExpressionType condition;
    emitRefTestOrCast(CastKind::Test, reference, allowNull, heapType, shouldNegate, condition);

    WASM_FAIL_IF_HELPER_FAILS(addBranch(data, condition, returnValues));

    return { };
}

auto OMGIRGenerator::addSwitch(ExpressionType condition, const Vector<ControlData*>& targets, ControlData& defaultTarget, std::span<const TypedExpression> expressionStack) -> PartialResult
{
    TRACE_CF("SWITCH");
    UNUSED_PARAM(expressionStack);
    for (size_t i = 0; i < targets.size(); ++i)
        unifyValuesWithBlock(expressionStack, *targets[i]);
    unifyValuesWithBlock(expressionStack, defaultTarget);

    SwitchValue* switchValue = m_currentBlock->appendNew<SwitchValue>(m_proc, origin(), get(condition));
    switchValue->setFallThrough(FrequentedBlock(defaultTarget.targetBlockForBranch()));
    for (size_t i = 0; i < targets.size(); ++i)
        switchValue->appendCase(SwitchCase(i, FrequentedBlock(targets[i]->targetBlockForBranch())));

    return { };
}

auto OMGIRGenerator::endBlock(ControlEntry& entry, std::span<TypedExpression> enclosedStack) -> PartialResult
{
    ControlData& data = entry.controlData;
    const auto& blockSignature = data.signature();
    unsigned returnCount = blockSignature.returnCount();

    ASSERT(enclosedStack.size() >= returnCount);
    auto blockResults = enclosedStack.last(returnCount);

    if (data.blockType() != BlockType::Loop)
        unifyValuesWithBlock(blockResults, data);

    m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), data.continuation);
    data.continuation->addPredecessor(m_currentBlock);

    m_currentBlock = data.continuation;

    if (data.blockType() == BlockType::If) {
        data.special->appendNewControlValue(m_proc, Jump, origin(), m_currentBlock);
        m_currentBlock->addPredecessor(data.special);
    } else if (data.blockType() == BlockType::Try || data.blockType() == BlockType::Catch)
        --m_tryCatchDepth;
    else if (data.blockType() == BlockType::TryTable) {
        data.endTryTable(advanceCallSiteIndex());
        auto targets = data.m_tryTableTargets;
        for (auto& target : targets)
            emitCatchTableImpl(data, target);
        --m_tryCatchDepth;
    }

    if (data.blockType() != BlockType::Loop) {
        // Replace block result entries with phi-derived values; the parser keeps these
        // as the resumed parent's stack top.
        for (unsigned i = 0; i < returnCount; ++i) {
            Value* result = data.phis[i];
            m_currentBlock->append(result);
            blockResults[i] = TypedExpression(blockSignature.returnType(i), push(result));
        }
    }
    // For Loop, blockResults already holds the loop's exit values; no replacement needed.

    if (data.blockType() == BlockType::TopLevel)
        return addReturn(entry.controlData, std::span<const TypedExpression>(blockResults));

    return { };
}

auto OMGIRGenerator::addEndToUnreachable(ControlEntry& entry, std::span<TypedExpression> enclosedStack) -> PartialResult
{
    ControlData& data = entry.controlData;
    const auto& blockSignature = data.signature();
    unsigned returnCount = blockSignature.returnCount();
    ASSERT(enclosedStack.size() >= returnCount);
    auto resultSlots = enclosedStack.last(returnCount);

    m_currentBlock = data.continuation;

    if (data.blockType() == BlockType::If) {
        data.special->appendNewControlValue(m_proc, Jump, origin(), m_currentBlock);
        m_currentBlock->addPredecessor(data.special);
    } else if (data.blockType() == BlockType::Try || data.blockType() == BlockType::Catch)
        --m_tryCatchDepth;
    else if (data.blockType() == BlockType::TryTable) {
        // emit each handler as a new basic block
        data.endTryTable(advanceCallSiteIndex());
        auto targets = data.m_tryTableTargets;
        for (auto& target : targets)
            emitCatchTableImpl(data, target);
        --m_tryCatchDepth;
    }

    if (data.blockType() != BlockType::Loop) {
        for (unsigned i = 0; i < returnCount; ++i) {
            Value* result = data.phis[i];
            m_currentBlock->append(result);
            resultSlots[i] = TypedExpression(blockSignature.returnType(i), push(result));
        }
    } else {
        // Loop: any incoming values would have come from the now-unreachable body.
        for (unsigned i = 0; i < returnCount; ++i) {
            Type returnType = blockSignature.returnType(i);
            resultSlots[i] = TypedExpression(returnType, push(constant(toB3Type(returnType), 0xbbadbeef)));
        }
    }

    // TopLevel does not have any code after this so we need to make sure we emit a return here.
    if (data.blockType() == BlockType::TopLevel)
        return addReturn(entry.controlData, std::span<const TypedExpression>(resultSlots));

    return { };
}

Vector<ConstrainedValue> OMGIRGenerator::createCallConstrainedArgs(BasicBlock* block, const CallInformation& wasmCalleeInfo, const ArgumentList& tmpArgs)
{
    Vector<ConstrainedValue> constrainedPatchArgs;
    constrainedPatchArgs.reserveCapacity(tmpArgs.size());
    for (unsigned i = 0; i < tmpArgs.size(); ++i) {
        auto dstLocation = wasmCalleeInfo.params[i];
        constrainedPatchArgs.append(B3::ConstrainedValue(get(block, tmpArgs[i]), dstLocation));
    }

    return constrainedPatchArgs;
}


auto OMGIRGenerator::createCallPatchpoint(BasicBlock* block, const RTT& signature, const CallInformation& wasmCalleeInfo, const ArgumentList& tmpArgs) -> CallPatchpointData
{
    auto returnType = toB3ResultType(&signature);

    auto constrainedPatchArgs = createCallConstrainedArgs(block, wasmCalleeInfo, tmpArgs);

    advanceCallSiteIndex();
    PatchpointValue* patchpoint = m_proc.add<PatchpointValue>(returnType, origin());
    patchpoint->effects.writesPinned = true;
    patchpoint->effects.readsPinned = true;
    patchpoint->clobberEarly(RegisterSet::macroClobberedGPRs());
    patchpoint->clobberLate(RegisterSet::registersToSaveForJSCall(m_proc.usesSIMD() ? RegisterSet::allRegisters() : RegisterSet::allScalarRegisters()));
    patchpoint->appendVector(constrainedPatchArgs);
    auto handle = preparePatchpointForExceptions(block, patchpoint);
    const Vector<ArgumentLocation, 1>& constrainedResultLocations = wasmCalleeInfo.results;
    if (returnType != B3::Void) {
        Vector<B3::ValueRep, 1> resultConstraints;
        for (auto valueLocation : constrainedResultLocations) {
            // FIXME: Graph Coloring has an issue where it runs out of "colors" (aka registers) when passing as an Any so instead place results where they would canonically go.
            // Even though the expected location is SP relative it still works with emitWasmCallStackResultsAndSPRestore because "SP" means FP - frameSize not the semi-random SP we got back from our callee.
            if (valueLocation.location.isStackArgument() && Options::airUseGreedyRegAlloc()) {
                // FIXME: Should these results be ColdAny? The argument in favor of Warm is that we have to move the values anyway so we might as well put in a register if that's what B3 wants
                resultConstraints.append(B3::ValueRep::WarmAny);
            } else
                resultConstraints.append(B3::ValueRep(valueLocation.location));
        }
        patchpoint->resultConstraints = WTF::move(resultConstraints);
    }
    block->append(patchpoint);
    return { patchpoint, WTF::move(handle), nullptr };
}

// See createTailCallPatchpoint for the setup before this.
static inline void prepareForTailCallImpl(unsigned functionIndex, CCallHelpers& jit, const B3::StackmapGenerationParams& params, const RTT& signature, const CallInformation& wasmCalleeInfoAsCallee, unsigned firstPatchArg, unsigned lastPatchArg, int32_t newFPOffsetFromFP, std::optional<unsigned> boxedCalleeArgIndex)
{
    const RTT& functionSignature = signature;
    JIT_COMMENT(jit, "Set up tail call, new FP offset from FP: ", newFPOffsetFromFP);

    const unsigned frameSize = params.code().frameSize();
    ASSERT(WTF::roundUpToMultipleOf<stackAlignmentBytes()>(frameSize) == frameSize);
    ASSERT(WTF::roundUpToMultipleOf<stackAlignmentBytes()>(std::abs(newFPOffsetFromFP)) == static_cast<size_t>(std::abs(newFPOffsetFromFP)));

    auto fpOffsetToSPOffset = [frameSize](int32_t offset) {
        return checkedSum<int>(safeCast<int>(frameSize), offset).value();
    };

    auto newReturnPCOffset = fpOffsetToSPOffset(checkedSum<intptr_t>(CallFrame::returnPCOffset(), newFPOffsetFromFP).value());

    // We requested some extra stack space below via requestCallArgAreaSize
    // ... FP [caller stack space ] [callArgSpace ] SP ...
    // becomes
    // ... FP [danger             ] [ scratch     ] SP ...
    // This scratch space sits at the very bottom of the stack, near sp.
    // AirLowerStackArgs takes care of adding callArgSpace to our total caller frame size.
    // BUT, even though we have this extra space, we need to be careful not to write into the
    // live frame while shuffling. If for some reason we found that the scratch space wasn't big
    // enough for our needs we could always ask B3 for more. We only use it for 32-bit / v128
    // stack arguments to our caller that can't be parallel moved into place directly.
    int spillPointer = 0;
    const int scratchAreaUpperBound = std::min(
        safeCast<int>(WTF::roundUpToMultipleOf<stackAlignmentBytes()>(static_cast<int>(wasmCalleeInfoAsCallee.headerAndArgumentStackSizeInBytes))),
        newReturnPCOffset);
    auto allocateSpill = [&] (Width width) -> int {
        int offset = WTF::roundUpToMultipleOf(bytesForWidth(width), spillPointer);
        spillPointer = offset + bytesForWidth(width);
        RELEASE_ASSERT(spillPointer <= scratchAreaUpperBound);
        RELEASE_ASSERT(offset < scratchAreaUpperBound);
        return offset;
    };

    RegisterAtOffsetList calleeSaves = params.code().calleeSaveRegisterAtOffsetList();

    AllowMacroScratchRegisterUsage allowScratch(jit);
    auto tmp = jit.scratchRegister();

#if ASSERT_ENABLED
    for (unsigned i = firstPatchArg; i < lastPatchArg; ++i) {
        auto arg = params[i];
        ASSERT_IMPLIES(arg.isGPR(), arg.gpr() != tmp);
    }
    ASSERT(!calleeSaves.find(tmp));
#endif

    JIT_COMMENT(jit, "Let's use the caller's frame, so that we always have a valid frame.");
    if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
        jit.probeDebug([frameSize, fpOffsetToSPOffset, newFPOffsetFromFP, signature = Ref<const RTT>(signature), wasmCalleeInfoAsCallee, firstPatchArg, lastPatchArg, params, functionIndex] (Probe::Context& context) {
            const RTT& functionSignature = signature.get();
            auto sp = context.gpr<uintptr_t>(MacroAssembler::stackPointerRegister);
            auto fp = context.gpr<uintptr_t>(GPRInfo::callFrameRegister);
            dataLogLn("Before tail call in function ", functionIndex, " before changing anything: FP: ", RawHex(fp), " SP: ", RawHex(sp));
            dataLogLn("New FP will be at ", RawHex(sp + fpOffsetToSPOffset(newFPOffsetFromFP)));
            CallFrame* fpp = context.gpr<CallFrame*>(GPRInfo::callFrameRegister);
            dataLogLn("callee original: ", RawPointer(fpp->callee().rawPtr()));
            auto& wasmCallee = context.gpr<uintptr_t*>(GPRInfo::callFrameRegister)[CallFrameSlot::callee * 1];
            dataLogLn("callee original: ", RawHex(wasmCallee), " at ", RawPointer(&wasmCallee));
            dataLogLn("retPC original: ", RawPointer(fpp->rawReturnPC()));
            auto& retPC = context.gpr<uintptr_t*>(GPRInfo::callFrameRegister)[CallFrame::returnPCOffset() / sizeof(uint64_t)];
            dataLogLn("retPC original: ", RawHex(retPC), " at ", RawPointer(&retPC));
            dataLogLn("callerFrame original: ", RawPointer(fpp->callerFrame()));
            ASSERT_UNUSED(frameSize, sp + frameSize == fp);

            auto fpl = context.gpr<uint64_t*>(GPRInfo::callFrameRegister);
            auto fpi = context.gpr<uint32_t*>(GPRInfo::callFrameRegister);

            unsigned currentPatchArg = firstPatchArg;
            auto dumpSrc = [&context, fpl, fpi, fpp] (ValueRep src, Width width) {
                dataLog(src, " = ");
                if (src.isGPR())
                    dataLog(context.gpr(src.gpr()), " / ", (int) context.gpr(src.gpr()));
                else if (src.isFPR() && width <= Width64)
                    dataLog(context.fpr(src.fpr()));
                else if (src.isFPR())
                    dataLog(context.vector(src.fpr()));
                else if (src.isConstant())
                    dataLog(src.value(), " / ", src.doubleValue());
                else
                    dataLog(fpl[src.offsetFromFP() / sizeof(*fpl)], " / ", fpi[src.offsetFromFP() / sizeof(*fpi)], " / ", std::bit_cast<double>(fpl[src.offsetFromFP() / sizeof(*fpl)]), " at ", RawPointer(&fpp[src.offsetFromFP() / sizeof(*fpp)]));
            };

            for (unsigned i = 0; i < functionSignature.argumentCount(); ++i) {
                auto width = functionSignature.argumentType(i).width();
                ASSERT(wasmCalleeInfoAsCallee.params[i].width >= width);
                dataLog("Arg source ", i, " located at ");
                ASSERT_UNUSED(lastPatchArg, currentPatchArg < lastPatchArg);
                dumpSrc(params[currentPatchArg++], width);

                dataLogLn(" ->(final) ", wasmCalleeInfoAsCallee.params[i].location);
            }
        });
    }
    jit.loadPtr(CCallHelpers::Address(MacroAssembler::framePointerRegister, CallFrame::callerFrameOffset()), MacroAssembler::framePointerRegister);
    if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
        jit.probeDebug([] (Probe::Context& context) {
            auto sp = context.gpr<uintptr_t>(MacroAssembler::stackPointerRegister);
            auto fp = context.gpr<uintptr_t>(GPRInfo::callFrameRegister);
            dataLogLn("In the new expanded frame, including F's caller: FP: ", RawHex(fp), " SP: ", RawHex(sp));
        });
    }

    // FIXME: This could probably be moved into MacroAssembler, there's not much
    // that's specific to anything here.
    JIT_COMMENT(jit, "Parallel move: shuffle args, callee-save restores, and return PC.");

    struct ShuffleLocation {
        enum class Kind : uint8_t { None, GPR, FPR, Stack };
        using enum Kind;

        static ShuffleLocation none() { return { .stackOffset = 0, .kind = None }; }
        static ShuffleLocation fromGPR(GPRReg r) { return { .gpr = r, .kind = GPR }; }
        static ShuffleLocation fromFPR(FPRReg r) { return { .fpr = r, .kind = FPR }; }
        static ShuffleLocation fromStack(int32_t offset) { return { .stackOffset = offset, .kind = Stack }; }

        bool operator==(const ShuffleLocation& other) const
        {
            if (kind != other.kind)
                return false;
            switch (kind) {
            case GPR: return gpr == other.gpr;
            case FPR: return fpr == other.fpr;
            case Stack: return stackOffset == other.stackOffset;
            // None / constants shouldn't be == to each other, this simplifies the cycle ASSERTs.
            default: return false;
            }
        }

        union {
            GPRReg gpr;
            FPRReg fpr;
            int32_t stackOffset;
        };
        Kind kind { None };
    };

    struct ShuffleEntry {
        ShuffleLocation src;
        ShuffleLocation dst;
        std::optional<int64_t> constant;
        Width width { Width64 };
    };

    Vector<ShuffleEntry> entries;
    entries.reserveInitialCapacity(calleeSaves.registerCount() + functionSignature.argumentCount() + 1);

    for (const auto& regAtOffset : calleeSaves) {
        ShuffleEntry entry;
        entry.src = ShuffleLocation::fromStack(fpOffsetToSPOffset(regAtOffset.offset()));
        if (regAtOffset.reg().isGPR()) {
            ASSERT(!RegisterSet::stackRegisters().contains(regAtOffset.reg().gpr()));
            entry.dst = ShuffleLocation::fromGPR(regAtOffset.reg().gpr());
        } else
            entry.dst = ShuffleLocation::fromFPR(regAtOffset.reg().fpr());
        entries.append(entry);
    }

    // The parallel move algorithm requires each location to be atomic — a write to
    // location X must only conflict with reads from exactly X. This breaks when stack entries
    // have different sizes: a Width64 write to Stack[X] spans [X, X+8) and can silently clobber
    // a Width32 source at Stack[X+4]. Similarly, V128 writes span 16 bytes across two slots.
    //
    // B3/Air can place LateColdAny Width32 values in 4-byte spill slots at 4-byte alignment, so source
    // offsets may not be 8-byte aligned. Destination offsets (from the Wasm calling convention)
    // are always 8-byte aligned, as are callee-save save slots. When the new frame overlaps the
    // current frame's spill area (callee has more stack args than caller), a Width64 destination
    // write can clobber a Width32 source that the algorithm doesn't know overlaps.
    //
    // To preserve correctness:
    // - Width32 stack sources are pre-spilled when they conflict with a destination (their
    //   8-byte-aligned slot matches a stack destination offset).
    // - V128 stack entries are split into two Width64 entries.

    unsigned currentPatchArg = firstPatchArg;
    for (unsigned i = 0; i < functionSignature.argumentCount(); ++i) {
        auto dstParam = wasmCalleeInfoAsCallee.params[i];
        auto dstType = functionSignature.argumentType(i);
        ASSERT(dstParam.width >= dstType.width());
        ASSERT(dstParam.width >= Width32);

        ASSERT_UNUSED(lastPatchArg, currentPatchArg < lastPatchArg);
        auto srcRep = params[currentPatchArg++];

        ShuffleLocation src;
        if (srcRep.isGPR())
            src = ShuffleLocation::fromGPR(srcRep.gpr());
        else if (srcRep.isFPR())
            src = ShuffleLocation::fromFPR(srcRep.fpr());
        else if (srcRep.isStack()) {
            ASSERT(isMultipleOf(sizeof(int32_t), srcRep.offsetFromFP()));
            src = ShuffleLocation::fromStack(fpOffsetToSPOffset(srcRep.offsetFromFP()));
        } else
            ASSERT(srcRep.isConstant());

        ShuffleLocation dst;
        if (dstParam.location.isGPR())
            dst = ShuffleLocation::fromGPR(dstParam.location.jsr().payloadGPR());
        else if (dstParam.location.isFPR())
            dst = ShuffleLocation::fromFPR(dstParam.location.fpr());
        else {
            ASSERT(dstParam.location.isStack());
            dst = ShuffleLocation::fromStack(fpOffsetToSPOffset(checkedSum<int32_t>(dstParam.location.offsetFromFP(), newFPOffsetFromFP).value()));
        }

        if (src == dst)
            continue;

        // V128 args with register destinations have exact patchpoint constraints,
        // so B3 places them directly and src == dst (no move needed). Only stack
        // destinations reach here and need splitting for the parallel move.
        if (dstType.width() == Width128 && dst.kind == ShuffleLocation::Stack) {
            if (src.kind == ShuffleLocation::FPR) {
                // It's annoying to figure out if the full width is available
                // for a store so just write it to a scratch slot and handle it
                // from there.
                // FIXME: We could probably do something better here, especially
                // if the FPR isn't a callee-save.
                int scratchOffset = allocateSpill(Width128);
                auto scratchAddr = CCallHelpers::Address(MacroAssembler::stackPointerRegister, scratchOffset);
                jit.storeVector(src.fpr, scratchAddr);
                src = ShuffleLocation::fromStack(scratchOffset);
            }

            ASSERT_WITH_MESSAGE(src.kind == ShuffleLocation::Stack, "B3 doesn't produce V128 constants");
            ShuffleEntry lo;
            lo.src = src;
            lo.dst = dst;
            entries.append(lo);

            ShuffleEntry hi;
            hi.src = ShuffleLocation::fromStack(src.stackOffset + bytesForWidth(Width64));
            hi.dst = ShuffleLocation::fromStack(dst.stackOffset + bytesForWidth(Width64));
            entries.append(hi);
        } else {
            ShuffleEntry entry;
            entry.width = dstType.width();
            ASSERT(dstType.width() <= Width64);
            entry.src = src;
            entry.dst = dst;
            if (srcRep.isConstant()) {
                entry.src = ShuffleLocation::none();
                entry.constant = srcRep.value();
            }
            entries.append(entry);
        }
    }

    {
        ShuffleEntry entry;
        entry.src = ShuffleLocation::fromStack(fpOffsetToSPOffset(CallFrame::returnPCOffset()));
#if CPU(ARM) || CPU(ARM64) || CPU(RISCV64)
        ASSERT(!calleeSaves.find(MacroAssembler::linkRegister));
        entry.dst = ShuffleLocation::fromGPR(MacroAssembler::linkRegister);
#else
        entry.dst = ShuffleLocation::fromStack(newReturnPCOffset);
#endif
        entries.append(entry);
    }
    JIT_COMMENT(jit, "ReturnPC has srcOffset ", fpOffsetToSPOffset(CallFrame::returnPCOffset()));

    if (boxedCalleeArgIndex) {
        auto srcRep = params[*boxedCalleeArgIndex];
        ShuffleEntry entry;
        if (srcRep.isGPR())
            entry.src = ShuffleLocation::fromGPR(srcRep.gpr());
        else if (srcRep.isStack())
            entry.src = ShuffleLocation::fromStack(fpOffsetToSPOffset(srcRep.offsetFromFP()));
        else if (srcRep.isConstant()) {
            entry.src = ShuffleLocation::none();
            entry.constant = srcRep.value();
        } else
            RELEASE_ASSERT_NOT_REACHED();
        entry.dst = ShuffleLocation::fromStack(fpOffsetToSPOffset(checkedSum<int32_t>(static_cast<int32_t>(CallFrameSlot::callee) * sizeof(Register), newFPOffsetFromFP).value()));
        entries.append(entry);
    }

#if ASSERT_ENABLED
    for (size_t i = 0; i < entries.size(); ++i) {
        if (entries[i].dst.kind != ShuffleLocation::Stack)
            continue;
        ASSERT(!(entries[i].dst.stackOffset % bytesForWidth(Width64)));
        for (size_t j = i + 1; j < entries.size(); ++j) {
            if (entries[j].dst.kind != ShuffleLocation::Stack)
                continue;
            ASSERT(entries[i].dst.stackOffset != entries[j].dst.stackOffset);
        }
    }
#endif

    // Pre-spill Width32 stack sources whose 8-byte-aligned slot conflicts with a destination and are not themselves 8-byte-aligned.
    // B3/Air can place LateColdAny inputs in 4-byte spill slots at 4-byte alignment, so a
    // Width32 source may sit at an offset the parallel move can't match to a destination write.
    for (auto& entry : entries) {
        if (entry.width >= Width64 || entry.src.kind != ShuffleLocation::Stack)
            continue;
        if (!(entry.src.stackOffset % bytesForWidth(Width64)))
            continue;
        int alignedBase = entry.src.stackOffset & ~(bytesForWidth(Width64) - 1);
        bool conflicts = false;
        for (const auto& other : entries) {
            if (other.dst.kind == ShuffleLocation::Stack && other.dst.stackOffset == alignedBase) {
                conflicts = true;
                break;
            }
        }
        if (conflicts) {
            int scratchOffset = allocateSpill(Width64);
            auto scratchAddr = CCallHelpers::Address(MacroAssembler::stackPointerRegister, scratchOffset);
            auto srcAddr = CCallHelpers::Address(MacroAssembler::stackPointerRegister, entry.src.stackOffset);
            jit.transfer32(srcAddr, scratchAddr);
            entry.src = ShuffleLocation::fromStack(scratchOffset);
        }
    }

    auto emitSingleMove = [&](const ShuffleEntry& e) {
        const auto& src = e.src;
        const auto& dst = e.dst;

        ASSERT(dst.kind != ShuffleLocation::None);
        switch (src.kind) {
        case ShuffleLocation::None: {
            ASSERT(e.constant);
            if (dst.kind == ShuffleLocation::GPR) {
                jit.move(MacroAssembler::TrustedImmPtr(*e.constant), dst.gpr);
            } else if (dst.kind == ShuffleLocation::FPR) {
                ASSERT_WITH_MESSAGE(e.width != Width128, "B3 doesn't produce V128 constants");
                if (e.width == Width32)
                    jit.move32ToFloat(MacroAssembler::TrustedImm32(*e.constant), dst.fpr);
                else
                    jit.move64ToDouble(MacroAssembler::TrustedImm64(*e.constant), dst.fpr);
            } else {
                ASSERT(dst.kind == ShuffleLocation::Stack);
                auto dstAddr = CCallHelpers::Address(MacroAssembler::stackPointerRegister, dst.stackOffset);
                if (e.width == Width32) {
                    jit.move(MacroAssembler::TrustedImm32(static_cast<int32_t>(*e.constant)), tmp);
                    jit.store32(tmp, dstAddr);
                } else {
                    jit.move(MacroAssembler::TrustedImm64(*e.constant), tmp);
                    jit.store64(tmp, dstAddr);
                }
            }
            return;
        }
        case ShuffleLocation::GPR: {
            if (dst.kind == ShuffleLocation::GPR)
                jit.move(src.gpr, dst.gpr);
            else {
                ASSERT(dst.kind == ShuffleLocation::Stack);
                jit.storeWidth(e.width, src.gpr, CCallHelpers::Address(MacroAssembler::stackPointerRegister, dst.stackOffset));
            }
            return;
        }
        case ShuffleLocation::FPR: {
            if (dst.kind == ShuffleLocation::FPR) {
                ASSERT(e.width < Width128);
                jit.moveDouble(src.fpr, dst.fpr);
            } else {
                ASSERT(dst.kind == ShuffleLocation::Stack);
                jit.storeWidth(e.width, src.fpr, CCallHelpers::Address(MacroAssembler::stackPointerRegister, dst.stackOffset));
            }
            return;
        }
        case ShuffleLocation::Stack: {
            ASSERT(src.kind == ShuffleLocation::Stack);
            auto srcAddr = CCallHelpers::Address(MacroAssembler::stackPointerRegister, src.stackOffset);
            ASSERT_WITH_MESSAGE(e.width != Width128, "V128 values should have been split during setup.");
            if (dst.kind == ShuffleLocation::GPR)
                jit.loadWidth(e.width, srcAddr, dst.gpr);
            else if (dst.kind == ShuffleLocation::FPR)
                jit.loadWidth(e.width, srcAddr, dst.fpr);
            else {
                ASSERT(dst.kind == ShuffleLocation::Stack);
                auto dstAddr = CCallHelpers::Address(MacroAssembler::stackPointerRegister, dst.stackOffset);
                jit.transferWidth(e.width, srcAddr, dstAddr);
            }
            return;
        }
        default:
            RELEASE_ASSERT_NOT_REACHED();
            break;
        }
    };

    auto spillToScratch = [&](unsigned index) {
        auto& e = entries[index];
        // FIXME: Early-clobber nonPreservedNonArgumentGPR1 + nonPreservedNonArgumentFPR0
        // and use them as scratch registers instead. transfer64 only clobbers tmp so a
        // separate scratch GPR/FPR is safe across intervening moves.
        int scratchOffset = allocateSpill(Width64);
        auto scratchAddr = CCallHelpers::Address(MacroAssembler::stackPointerRegister, scratchOffset);

        switch (e.src.kind) {
        case ShuffleLocation::GPR:
            jit.storePtr(e.src.gpr, scratchAddr);
            break;
        case ShuffleLocation::FPR:
            jit.storeDouble(e.src.fpr, scratchAddr);
            break;
        case ShuffleLocation::Stack: {
            jit.transferWidth(e.width, CCallHelpers::Address(MacroAssembler::stackPointerRegister, e.src.stackOffset), scratchAddr);
            break;
        }
        default:
            RELEASE_ASSERT_NOT_REACHED();
        }

        e.src = ShuffleLocation::fromStack(scratchOffset);
    };

    Vector<CCallHelpers::ShuffleStatus> status(FillWith { }, entries.size(), CCallHelpers::ShuffleStatus::ToMove);

    auto emitShuffleMove = recursableLambda([&](auto self, unsigned index) -> void {
        auto& entry = entries[index];
        if (!entry.constant && entry.src == entry.dst) {
            status[index] = CCallHelpers::ShuffleStatus::Moved;
            return;
        }

        status[index] = CCallHelpers::ShuffleStatus::BeingMoved;

        for (unsigned i = 0; i < entries.size(); ++i) {
            if (entries[i].constant || i == index)
                continue;
            if (entries[i].src == entries[index].dst) {
                switch (status[i]) {
                case CCallHelpers::ShuffleStatus::ToMove:
                    self(i);
                    break;
                case CCallHelpers::ShuffleStatus::BeingMoved:
                    spillToScratch(i);
                    break;
                case CCallHelpers::ShuffleStatus::Moved:
                    break;
                }
            }
        }

        emitSingleMove(entries[index]);
        status[index] = CCallHelpers::ShuffleStatus::Moved;
    });

    for (unsigned i = 0; i < entries.size(); ++i) {
        if (status[i] == CCallHelpers::ShuffleStatus::ToMove)
            emitShuffleMove(i);
    }

    JIT_COMMENT(jit, "Now we can restore / resign lr.");

    // Pop our locals, leaving only the new frame behind as though our original caller had called the callee.
    // Also pop callee.
    auto newFPOffsetFromSP = fpOffsetToSPOffset(newFPOffsetFromFP);
    ASSERT(newFPOffsetFromSP > 0);
    ASSERT(WTF::roundUpToMultipleOf<stackAlignmentBytes()>(std::abs(newFPOffsetFromSP)) == static_cast<size_t>(std::abs(newFPOffsetFromSP)));

    auto newSPAtPrologueOffsetFromSP = newFPOffsetFromSP + prologueStackPointerDelta();

#if CPU(ARM) || CPU(ARM64) || CPU(RISCV64)
    // the return PC should already be in the linkRegister from the shuffle above.
    if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
        jit.probeDebug([] (Probe::Context& context) {
            dataLogLn("tagged return pc: ", RawHex(context.gpr<uintptr_t>(MacroAssembler::linkRegister)));
        });
    }
#if CPU(ARM64E)
    JIT_COMMENT(jit, "The return pointer was signed with the stack height before we pushed lr, fp, see emitFunctionPrologue. newFPOffsetFromSP: ", newFPOffsetFromSP, " newFPOffsetFromFP ", newFPOffsetFromFP);
    jit.addPtr(MacroAssembler::TrustedImm32(params.code().frameSize() + sizeof(CallerFrameAndPC)), MacroAssembler::stackPointerRegister, tmp);
    jit.untagPtr(tmp, MacroAssembler::linkRegister);
    if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
        jit.probeDebug([] (Probe::Context& context) {
            dataLogLn("untagged return pc: ", RawHex(context.gpr<uintptr_t>(MacroAssembler::linkRegister)));
        });
    }
    jit.validateUntaggedPtr(MacroAssembler::linkRegister);
#endif
#endif

    {
        jit.addPtr(MacroAssembler::TrustedImm32(newSPAtPrologueOffsetFromSP), MacroAssembler::stackPointerRegister);

#if CPU(X86_64)
        if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
            jit.probeDebug([] (Probe::Context& context) {
                dataLogLn("return pc on the top of the stack: ", RawHex(*context.gpr<uintptr_t*>(MacroAssembler::stackPointerRegister)), " at ", RawHex(context.gpr<uintptr_t>(MacroAssembler::stackPointerRegister)));
            });
        }
#endif

        JIT_COMMENT(jit, "OK, now we can jump.");
        if (WasmOMGIRGeneratorInternal::verboseTailCalls) {
            jit.probeDebug([wasmCalleeInfoAsCallee] (Probe::Context& context) {
                dataLogLn("Can now jump: FP: ", RawHex(context.gpr<uintptr_t>(GPRInfo::callFrameRegister)), " SP: ", RawHex(context.gpr<uintptr_t>(MacroAssembler::stackPointerRegister)));
                auto* newFP = context.gpr<uintptr_t*>(MacroAssembler::stackPointerRegister) - prologueStackPointerDelta() / sizeof(uintptr_t);
                dataLogLn("New (callee) FP at prologue will be at ", RawPointer(newFP));
                auto fpl = std::bit_cast<uint64_t*>(newFP);
                auto fpi = std::bit_cast<uint32_t*>(newFP);

                for (unsigned i = 0; i < wasmCalleeInfoAsCallee.params.size(); ++i) {
                    auto arg = wasmCalleeInfoAsCallee.params[i];
                    auto src = arg.location;
                    dataLog("Arg ", i, " located at ", arg.location, " = ");
                    if (arg.location.isGPR())
                        dataLog(context.gpr(arg.location.jsr().payloadGPR()), " / ", (int) context.gpr(arg.location.jsr().payloadGPR()));
                    else if (arg.location.isFPR() && arg.width <= Width::Width64)
                        dataLog(context.fpr(arg.location.fpr()));
                    else if (arg.location.isFPR())
                        dataLog(context.vector(arg.location.fpr()));
                    else
                        dataLog(fpl[src.offsetFromFP() / sizeof(*fpl)], " / ", fpi[src.offsetFromFP() / sizeof(*fpi)],  " / ", RawHex(fpi[src.offsetFromFP() / sizeof(*fpi)]), " / ", std::bit_cast<double>(fpl[src.offsetFromFP() / sizeof(*fpl)]), " at ", RawPointer(&fpi[src.offsetFromFP() / sizeof(*fpi)]));
                    dataLogLn();
                }
            });
        }

#if ASSERT_ENABLED
        // Everything in the old stack might be overwritten anyway. Clobber for easier debugging.
        JIT_COMMENT(jit, "Clobbering the old frame");
        jit.move(MacroAssembler::TrustedImm32(0xBFFF), tmp);
        constexpr int stackSlotsToClobber = 50;
        constexpr int stackBytesToClobber = stackSlotsToClobber * registerSize();
        static_assert(!(stackBytesToClobber & (stackAlignmentBytes() - 1)), "Size in bytes to clobber on stack is aligned");
        for (int i = 0; i < stackSlotsToClobber / 2; ++i)
            jit.pushPair(tmp, tmp);
        jit.addPtr(MacroAssembler::TrustedImm32(stackBytesToClobber), MacroAssembler::stackPointerRegister);
#endif
    }
}

// See also: https://leaningtech.com/fantastic-tail-calls-and-how-to-implement-them/, a blog post about contributing this feature.
auto OMGIRGenerator::createTailCallPatchpoint(BasicBlock* block, const RTT& signature, const CallInformation& wasmCallerInfoAsCallee, const CallInformation& wasmCalleeInfoAsCallee, const ArgumentList& tmpArgSourceLocations, Value* boxedCalleeCallee) -> CallPatchpointData
{
    m_makesTailCalls = true;
    // Our args are placed in argument registers or locals.
    // We must:
    // - Restore callee saves
    // - Restore and re-sign lr
    // - Restore our caller's FP so that the stack area we write to is always valid
    // - Move stack args from our stack to their final resting spots. Note that they might overlap.
    // - Move argumentCountIncludingThis (a.k.a. callSiteIndex) to its final spot, since WASM uses it for exceptions.
    // Layout of stack right now, and after this patchpoint.
    //
    //
    //    |          Original Caller   |                                                                      |          ......            |
    //    +----------------------------+ <--                                                                  +----------------------------+ <--
    //    |           F.argN           |    |                                    +-------------------->       |           G.argM           |    |                            Safe to clobber
    //    +----------------------------+    | lower address                      |                            +----------------------------+    | lower address
    //    |           F.arg1           |    v                                    |                            |           arg1             |    v
    //    +----------------------------+                                         |                            +----------------------------+
    //    |           F.arg0           |                                         |                            |           arg0             |                                   .......... < Danger froniter, grows down as args get moved out of the way
    //    +----------------------------+                                         |                            +----------------------------+
    //    |           F.this           |                                         |                            |           this'            |                                Dangerous to clobber
    //    +----------------------------+                                         |                            +----------------------------+
    //    | argumentCountIncludingThis |                                         |                            |          A.C.I.T.'         |
    //    +----------------------------+                                         |                            +----------------------------+
    //    |          F.callee          |                                         |                            |        G.callee            |
    //    +----------------------------+                                         |                            +----------------------------+
    //    |        F.codeBlock         |                               (shuffleStackArgs...)                  |        G.codeBlock         |
    //    +----------------------------+                                         |                     (arm) >+----------------------------+
    //    | return-address after F     |                                         |                            |   return-address after F   |
    //    +----------------------------+                                         | SP at G prologue (intel) ->+----------------------------+
    //    |          F.caller.FP       |                                         |                            |          F.caller.FP       |
    //    +----------------------------+  <- F.FP                                |    G.FP after G prologue-> +----------------------------+
    //    |          callee saves      |                                         |                            |          callee saves      |
    //    +----------------------------+   <----+   argM to G  ------------------+                            +----------------------------+
    //    |          F.local0          |        |   ....                                                      |          G.local0          |
    //    +----------------------------+        |   arg0 to G                                                 +----------------------------+
    //    |          F.local1          |        |                                                             |          G.local1          |
    //    +----------------------------+        |                                                             +----------------------------+
    //    |          F.localN          |        |                                                             |          G.localM          |
    //    +----------------------------|        |                                                             +----------------------------+
    //    |          ......            |        |                                                             |          ......            |
    //    +----------------------------|  <- SP |                                       SP after G prologue-> +----------------------------+
    //                                          |
    //    Note that F.FP is not the same as G.FP because the number of args may differ.
    // We must not clobber any local because source args may be located anywhere.
    // The final resting place of G.argM (F.argN) up to the return address after F is fair game to clobber; we do not permit StackArgument value reps.

    // First slot here is the last argument to F, a.k.a the first stack slot that belongs to F.
    const Checked<int32_t> offsetOfFirstSlotFromFP = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCallerInfoAsCallee.headerAndArgumentStackSizeInBytes);
    ASSERT(offsetOfFirstSlotFromFP > 0);
    const Checked<int32_t> offsetOfNewFPFromFirstSlot = checkedProduct<int32_t>(-1, WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCalleeInfoAsCallee.headerAndArgumentStackSizeInBytes));
    const Checked<int32_t> newFPOffsetFromFP = offsetOfFirstSlotFromFP + offsetOfNewFPFromFirstSlot;
    m_tailCallStackOffsetFromFP = std::min(m_tailCallStackOffsetFromFP, newFPOffsetFromFP);

    RegisterSet scratchRegisters = RegisterSet::macroClobberedGPRs();
    RegisterSet forbiddenArgumentRegisters = RegisterSet::calleeSaveRegisters().merge(scratchRegisters);

    ASSERT(wasmCalleeInfoAsCallee.params.size() == tmpArgSourceLocations.size());

    auto constrainedArgPatchArgs = createCallConstrainedArgs(block, wasmCalleeInfoAsCallee, tmpArgSourceLocations);

    Vector<ConstrainedValue> patchArgs;
    unsigned firstPatchArg = 0;
    for (unsigned i = 0; i < constrainedArgPatchArgs.size(); ++i) {
        auto src = constrainedArgPatchArgs[i].value();
        auto dst = constrainedArgPatchArgs[i].rep();
        ASSERT(dst.isStack() || dst.isFPR() || dst.isGPR());
        if (!dst.isStack()) {
            // We will restore callee saves before jumping to the callee.
            // The calling convention should guarantee this anyway, but let's document it just in case.
            ASSERT_UNUSED(forbiddenArgumentRegisters, !forbiddenArgumentRegisters.contains(dst.isGPR() ? Reg(dst.gpr()) : Reg(dst.fpr()), IgnoreVectors));
            patchArgs.append(constrainedArgPatchArgs[i]);
            continue;
        }
        patchArgs.append(ConstrainedValue(src, ValueRep::LateColdAny));
    }
    unsigned lastPatchArg = patchArgs.size();

    std::optional<unsigned> boxedCalleeArgIndex;
    if (boxedCalleeCallee) {
        boxedCalleeArgIndex = patchArgs.size();
        patchArgs.append(ConstrainedValue(boxedCalleeCallee, ValueRep::LateColdAny));
    }

    PatchpointValue* patchpoint = m_proc.add<PatchpointValue>(B3::Void, origin());
    patchpoint->effects.terminal = true;
    patchpoint->effects.readsPinned = true;
    patchpoint->effects.writesPinned = true;

    patchpoint->clobberEarly(RegisterSet::macroClobberedGPRs());
    patchpoint->appendVector(WTF::move(patchArgs));
    // See prepareForTailCallImpl for the heart of this patchpoint.
    block->append(patchpoint);

    firstPatchArg += m_proc.resultCount(patchpoint->type());
    lastPatchArg += m_proc.resultCount(patchpoint->type());
    if (boxedCalleeArgIndex)
        *boxedCalleeArgIndex += m_proc.resultCount(patchpoint->type());

    auto prepareForCall = createSharedTask<B3::StackmapGeneratorFunction>([signature = Ref<const RTT>(signature), wasmCalleeInfoAsCallee, newFPOffsetFromFP, firstPatchArg, lastPatchArg, boxedCalleeArgIndex, functionIndex = m_functionIndex](CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
        ASSERT(newFPOffsetFromFP >= 0 || params.code().frameSize() >= static_cast<uint32_t>(-newFPOffsetFromFP));
        prepareForTailCallImpl(functionIndex, jit, params, signature, wasmCalleeInfoAsCallee, firstPatchArg, lastPatchArg, newFPOffsetFromFP, boxedCalleeArgIndex);
    });

    return { patchpoint, nullptr, WTF::move(prepareForCall) };
}

InliningNode* OMGIRGenerator::canInline(FunctionSpaceIndex functionIndexSpace, unsigned callProfileIndex) const
{
    auto* result = m_inlining->callTarget(functionIndexSpace, callProfileIndex);
    if (!result)
        return nullptr;

    if (result->depth() > 1 && !StackCheck(Thread::currentSingleton().stack(), StackBounds::DefaultReservedZone * 2).isSafeToRecurse())
        return nullptr;

    return result;
}

auto OMGIRGenerator::emitInlineDirectCall(InliningNode* inlining, FunctionCodeIndex calleeFunctionIndex, const RTT& calleeSignature, const ArgumentList& args, ValueResults& results) -> PartialResult
{
    Vector<Value*> getArgs;
    for (auto& arg : args)
        getArgs.append(get(arg));

    BasicBlock* continuation = m_proc.addBlock();

    // Not all inine frames need to save state, but we still need to make sure that there is at least
    // one unique CallSiteIndex per inline frame for stack traces to work.
    advanceCallSiteIndex();
    auto firstInlineCallSiteIndex = advanceCallSiteIndex();

    const FunctionData& function = m_info.functions[calleeFunctionIndex];
    Ref<IPIntCallee> profiledCallee = m_calleeGroup.ipintCalleeFromFunctionIndexSpace(m_calleeGroup.toSpaceIndex(calleeFunctionIndex));
    m_protectedInlineeGenerators.append(makeUnique<OMGIRGenerator>(m_heaps, m_context, *this, *m_inlineRoot, m_module, m_calleeGroup, calleeFunctionIndex, profiledCallee.get(), inlining, continuation, WTF::move(getArgs)));
    auto& irGenerator = *m_protectedInlineeGenerators.last();

    for (unsigned i = 0; i < calleeSignature.returnCount(); ++i) {
        Value* phi = continuation->appendNew<Value>(m_proc, B3::Phi, toB3Type(calleeSignature.returnType(i)), origin());
        irGenerator.m_inlinedResultPhis.append(phi);
    }

    m_protectedInlineeParsers.append(makeUnique<FunctionParser<OMGIRGenerator>>(irGenerator, function.data, calleeSignature, m_info));
    auto& parser = *m_protectedInlineeParsers.last();
    WASM_FAIL_IF_HELPER_FAILS(parser.parse());

    irGenerator.insertConstants();
    for (unsigned i = 1; i < irGenerator.m_rootBlocks.size(); ++i) {
        auto block = irGenerator.m_rootBlocks[i];
        dataLogLnIf(WasmOMGIRGeneratorInternal::verboseInlining, "Block (", i, ")", block, " is an inline catch handler");
        m_rootBlocks.append(block);
    }
    m_exceptionHandlers.appendVector(WTF::move(irGenerator.m_exceptionHandlers));
    if (irGenerator.m_exceptionHandlers.size())
        m_hasExceptionHandlers = true;
    RELEASE_ASSERT(!irGenerator.m_callSiteIndex);

    irGenerator.m_topLevelBlock->appendNewControlValue(m_proc, B3::Jump, origin(), FrequentedBlock(irGenerator.m_rootBlocks[0]));
    m_makesCalls |= irGenerator.m_makesCalls;
    ASSERT(&irGenerator.m_proc == &m_proc);

    dataLogLnIf(WasmOMGIRGeneratorInternal::verboseInlining, "Block ", *m_currentBlock, " is going to do an inline call to block ", *irGenerator.m_topLevelBlock, " then continue at ", *continuation);
    m_currentBlock->appendNewControlValue(m_proc, B3::Jump, origin(), FrequentedBlock(irGenerator.m_topLevelBlock));
    m_currentBlock = continuation;

    results = WTF::move(irGenerator.m_inlinedResultPhis);

    auto lastInlineCallSiteIndex = advanceCallSiteIndex();
    advanceCallSiteIndex();
    m_callee->addCodeOrigin(firstInlineCallSiteIndex, lastInlineCallSiteIndex, m_info, calleeFunctionIndex + m_numImportFunctions);

    dataLogLnIf(WasmOMGIRGeneratorInternal::verboseInlining, "Inlining CallSiteIndex range: ", firstInlineCallSiteIndex, " -> ", lastInlineCallSiteIndex, " [", inlining->depth(), "]");

    return { };
}

auto OMGIRGenerator::addCall(unsigned callProfileIndex, FunctionSpaceIndex functionIndexSpace, const RTT& signature, ArgumentList& args, ResultList& results, CallType callType) -> PartialResult
{
    TRACE_CF("Call: entered with ", signature);

    ValueResults values;
    auto result = emitDirectCall(callProfileIndex, functionIndexSpace, signature, args, values, callType);
    if (!result.has_value()) [[unlikely]]
        return result;

    const bool isTailCallRootCaller = callType == CallType::TailCall && !m_inlineParent;
    const bool isTailCallInlineCaller = callType == CallType::TailCall && m_inlineParent;

    if (!isTailCallRootCaller) {
        for (Value* value : values)
            results.append(push(value));
        if (isTailCallInlineCaller)
            return addInlinedReturn(results);
    }

    return { };
}

auto OMGIRGenerator::emitDirectCall(unsigned callProfileIndex, FunctionSpaceIndex functionIndexSpace, const RTT& signature, const ArgumentList& args, ValueResults& results, CallType callType) -> PartialResult
{
    if (!m_info.isImportedFunctionFromFunctionIndexSpace(functionIndexSpace)) {
        // Record the callee so the callee knows to look for it in updateCallsitesToCallUs.
        // FIXME: This could only record the callees from inlined functions since BBQ should have reported any direct callees before so we don't do the extra
        // bookkeeping for edges we already know about.
        m_directCallees.testAndSet(m_info.toCodeIndex(functionIndexSpace));
    }

    const bool isTailCallRootCaller = callType == CallType::TailCall && !m_inlineParent;
    ASSERT(signature.argumentCount() == args.size());

    const auto& callingConvention = wasmCallingConvention();
    Checked<int32_t> tailCallStackOffsetFromFP;
    CallInformation wasmCalleeInfo = callingConvention.callInformationFor(signature, CallRole::Caller);
    CallInformation wasmCalleeInfoAsCallee = callingConvention.callInformationFor(signature, CallRole::Callee);
    Checked<int32_t> calleeStackSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCalleeInfo.headerAndArgumentStackSizeInBytes);
    if (isTailCallRootCaller)
        calleeStackSize = WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCalleeInfo.headerAndArgumentStackSizeInBytes * 2 + sizeof(Register));
    const TypeSignatureIndex callerTypeSignatureIndex = m_info.internalFunctionTypeSignatureIndices[m_functionIndex];
    const RTT& callerType = m_info.rtt(callerTypeSignatureIndex);
    CallInformation wasmCallerInfoAsCallee = callingConvention.callInformationFor(callerType, CallRole::Callee);

    B3::Type returnType = toB3ResultType(&signature);
    Value* jumpDestination = nullptr;

    m_makesCalls = true;
    if (callType == CallType::TailCall)
        m_makesTailCalls = true;

    m_proc.requestCallArgAreaSizeInBytes(calleeStackSize);

    if (m_info.isImportedFunctionFromFunctionIndexSpace(functionIndexSpace)) {
        auto emitCallToImport = [&, this](PatchpointValue* patchpoint, RefPtr<PatchpointExceptionHandle> handle, RefPtr<B3::StackmapGenerator> prepareForCall) -> void {
            unsigned patchArgsIndex = patchpoint->reps().size();
            patchpoint->append(jumpDestination, ValueRep(GPRInfo::nonPreservedNonArgumentGPR0));
            // We need to clobber all potential pinned registers since we might be leaving the instance.
            // We pessimistically assume we could be calling to something that is bounds checking.
            // FIXME: We shouldn't have to do this: https://bugs.webkit.org/show_bug.cgi?id=172181
            patchpoint->clobberLate(RegisterSet::wasmPinnedRegisters());
            // emitRestoreInstanceFrameIfNeeded needs two scratches. wasmBaseMemoryPointer is
            // always pinned so B3 won't allocate it. wasmBoundsCheckingSizeRegister
            // is only pinned in BoundsChecking mode, so in Signaling mode we need B3 to give us a
            // scratch that avoids the inputs.
            if (isTailCallRootCaller && m_mode == MemoryMode::Signaling)
                patchpoint->numGPScratchRegisters = 1;
            patchArgsIndex += m_proc.resultCount(patchpoint->type());
            patchpoint->setGenerator([this, patchArgsIndex, handle, isTailCallRootCaller, tailCallStackOffsetFromFP, prepareForCall, signature = Ref<const RTT>(signature), wasmCalleeInfo, callerStackSize = static_cast<int32_t>(WTF::roundUpToMultipleOf<stackAlignmentBytes()>(wasmCallerInfoAsCallee.headerAndArgumentStackSizeInBytes)), mode = m_mode](CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
                AllowMacroScratchRegisterUsage allowScratch(jit);
                if (isTailCallRootCaller) {
                    int32_t topSource = -static_cast<int32_t>(params.code().frameSize());
                    for (unsigned i = 0; i < params.size(); ++i) {
                        if (params[i].isStack())
                            topSource = std::max(topSource, params[i].offsetFromFP() + static_cast<int32_t>(sizeof(Register)));
                    }
                    for (const auto& entry : params.code().calleeSaveRegisterAtOffsetList())
                        topSource = std::max<int32_t>(topSource, entry.offset() + entry.byteSize());
                    Checked<int32_t> topSourceOffsetFromFP = static_cast<int32_t>(roundUpToMultipleOf<stackAlignmentBytes()>(topSource));
                    GPRReg scratch2 = mode == MemoryMode::Signaling ? params.gpScratch(0) : GPRInfo::wasmBoundsCheckingSizeRegister;
                    emitRestoreInstanceFrameIfNeeded(jit, GPRInfo::wasmContextInstancePointer, callerStackSize, params.code().frameSize(), topSourceOffsetFromFP, GPRInfo::wasmBaseMemoryPointer, scratch2);
                    // Import stub sets up the pinned registers for us so we don't have to do anything here.
                }
                if (prepareForCall)
                    prepareForCall->run(jit, params);
                ASSERT(!isTailCallRootCaller || !handle);
                if (handle)
                    handle->collectStackMap(this, params);
                if (isTailCallRootCaller)
                    jit.farJump(params[patchArgsIndex].gpr(), WasmEntryPtrTag);
                else {
                    jit.call(params[patchArgsIndex].gpr(), WasmEntryPtrTag);
                    emitWasmCallStackResultsAndSPRestore(jit, params, signature, wasmCalleeInfo);
                }
            });
        };

        m_maxNumJSCallArguments = std::max(m_maxNumJSCallArguments, static_cast<uint32_t>(args.size()));

        // FIXME: Let's remove this indirection by creating a PIC friendly IC
        // for calls out to the js. This shouldn't be that hard to do. We could probably
        // implement the IC to be over Context*.
        // https://bugs.webkit.org/show_bug.cgi?id=170375
        jumpDestination = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfImportFunctionStub(m_module.moduleInformation(), functionIndexSpace)));
        m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_importFunctionStubs[functionIndexSpace], jumpDestination);

        if (isTailCallRootCaller) {
            auto [patchpoint, handle, prepareForCall] = createTailCallPatchpoint(m_currentBlock, signature, wasmCallerInfoAsCallee, wasmCalleeInfoAsCallee, args);
            emitCallToImport(patchpoint, handle, prepareForCall);
            return { };
        }

        auto [patchpoint, handle, prepareForCall] = createCallPatchpoint(m_currentBlock, signature, wasmCalleeInfo, args);
        emitCallToImport(patchpoint, handle, prepareForCall);

        if (returnType != B3::Void)
            fillCallResults(patchpoint, signature, results);

        // The call could have been to another WebAssembly instance, and / or could have modified our Memory.
        restoreWebAssemblyGlobalState(m_info.memories, instanceValue(), m_currentBlock);
        return { };
    } // isImportedFunctionFromFunctionIndexSpace

    Vector<UnlinkedWasmToWasmCall>* unlinkedWasmToWasmCalls = &m_unlinkedWasmToWasmCalls;

    auto emitUnlinkedWasmToWasmCall = [&, this](PatchpointValue* patchpoint, RefPtr<PatchpointExceptionHandle> handle, RefPtr<B3::StackmapGenerator> prepareForCall) -> void {
        patchpoint->setGenerator([this, handle, unlinkedWasmToWasmCalls, functionIndexSpace, isTailCallRootCaller, tailCallStackOffsetFromFP, prepareForCall, signature = Ref<const RTT>(signature), wasmCalleeInfo](CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
            AllowMacroScratchRegisterUsage allowScratch(jit);
            if (prepareForCall)
                prepareForCall->run(jit, params);
            if (handle)
                handle->collectStackMap(this, params);

            ASSERT(!m_info.isImportedFunctionFromFunctionIndexSpace(functionIndexSpace));

            // If the call is self-recursion, it is guaranteed that callee will be OMG as well since it ends up calling itself.
            // Since the OMG function prologue will put callee, the caller does not need to place it.
            // For tail calls, the shuffle already placed the callee.
            bool selfRecursion = &m_inlineRoot->m_info == &m_info && m_info.toCodeIndex(functionIndexSpace) == m_inlineRoot->m_functionIndex;
            if (!isTailCallRootCaller && !selfRecursion) {
                Ref<IPIntCallee> callee = m_calleeGroup.ipintCalleeFromFunctionIndexSpace(functionIndexSpace);
                jit.storeWasmCalleeToCalleeCallFrame(CCallHelpers::TrustedImmPtr(CalleeBits::boxNativeCallee(callee.ptr())));
            }
            auto call = isTailCallRootCaller ? jit.threadSafePatchableNearTailCall() : jit.threadSafePatchableNearCall();

            jit.addLinkTask([unlinkedWasmToWasmCalls, call, functionIndexSpace](LinkBuffer& linkBuffer) {
                unlinkedWasmToWasmCalls->append({ linkBuffer.locationOfNearCall<WasmEntryPtrTag>(call), functionIndexSpace });
            });
            if (!isTailCallRootCaller)
                emitWasmCallStackResultsAndSPRestore(jit, params, signature, wasmCalleeInfo);
        });
    };

    if (isTailCallRootCaller) {
        Ref<IPIntCallee> ipintCallee = m_calleeGroup.ipintCalleeFromFunctionIndexSpace(functionIndexSpace);
        auto* boxedCallee = constant(pointerType(), std::bit_cast<uintptr_t>(CalleeBits::boxNativeCallee(ipintCallee.ptr())));
        auto [patchpoint, handle, prepareForCall] = createTailCallPatchpoint(m_currentBlock, signature, wasmCallerInfoAsCallee, wasmCalleeInfoAsCallee, args, boxedCallee);
        emitUnlinkedWasmToWasmCall(patchpoint, handle, prepareForCall);
        return { };
    }

    if (callType == CallType::Call) {
        if (auto* inlining = canInline(functionIndexSpace, callProfileIndex)) {
            auto functionIndex = m_info.toCodeIndex(functionIndexSpace);
            dataLogLnIf(WasmOMGIRGeneratorInternal::verboseInlining, " inlining call to ", functionIndex, " from ", m_functionIndex, " depth ", inlining->depth());
            return emitInlineDirectCall(inlining, functionIndex, signature, args, results);
        }
    }

    // We do not need to store |this| with JS instance since,
    // 1. It is not tail-call. So this does not clobber the arguments of this function.
    // 2. We are not changing instance. Thus, |this| of this function's arguments are the same and OK.

    auto [patchpoint, handle, prepareForCall] = createCallPatchpoint(m_currentBlock, signature, wasmCalleeInfo, args);
    emitUnlinkedWasmToWasmCall(patchpoint, handle, prepareForCall);
    // We need to clobber the size register since the IPInt always bounds checks
    if (useSignalingMemory0() || (m_info.memoryCount() && m_info.memory(0).isShared()))
        patchpoint->clobberLate(RegisterSet { GPRInfo::wasmBoundsCheckingSizeRegister });

    fillCallResults(patchpoint, signature, results);

    return { };
}

auto OMGIRGenerator::tryInliningPolymorphicCalls(unsigned callProfileIndex, Value* calleeInstance, Value* calleeCallee, const RTT& signature, const ArgumentList& args, CallType callType, bool isTailCallRootCaller, BasicBlock* continuation) -> Expected<Vector<ValueResults>, ErrorType>
{
    if (callProfileIndex >= m_inlining->callSites().size())
        return { };

    auto& callSite = m_inlining->callSites()[callProfileIndex];
    if (callSite.isEmpty())
        return { };

    Vector<ValueResults> fastValuesList;
    BasicBlock* slowCase = m_proc.addBlock();
    BasicBlock* calleeCheck = m_proc.addBlock();

    Value* isSameContextInstance = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), calleeInstance, instanceValue());
    m_currentBlock->appendNewControlValue(m_proc, Branch, origin(), isSameContextInstance, FrequentedBlock(calleeCheck), FrequentedBlock(slowCase, FrequencyClass::Rare));
    calleeCheck->addPredecessor(m_currentBlock);
    slowCase->addPredecessor(m_currentBlock);

    for (unsigned i = 0; i < callSite.size(); ++i) {
        auto* inlining = callSite[i];
        auto& callee = inlining->callee();

        BasicBlock* nextCase = slowCase;
        if ((i + 1) != callSite.size())
            nextCase = m_proc.addBlock();
        BasicBlock* directCall = m_proc.addBlock();

        m_currentBlock = calleeCheck;
        ValueResults fastValues;
        Value* isSameCallee = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), calleeCallee, constant(pointerType(), std::bit_cast<uintptr_t>(CalleeBits::boxNativeCallee(&const_cast<IPIntCallee&>(callee)))));
        m_currentBlock->appendNewControlValue(m_proc, Branch, origin(), isSameCallee, FrequentedBlock(directCall), FrequentedBlock(nextCase, nextCase == slowCase ? FrequencyClass::Rare : FrequencyClass::Normal));
        directCall->addPredecessor(m_currentBlock);
        nextCase->addPredecessor(m_currentBlock);

        m_currentBlock = directCall;
        auto result = emitDirectCall(callProfileIndex, callee.index(), signature, args, fastValues, callType);
        if (!result.has_value()) [[unlikely]]
            return makeUnexpected(result.error());

        if (!isTailCallRootCaller) {
            for (Value*& value : fastValues) {
                auto* input = value;
                value = m_currentBlock->appendNew<UpsilonValue>(m_proc, origin(), input);
            }
            m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);
            continuation->addPredecessor(m_currentBlock);
        }

        calleeCheck = nextCase;
        fastValuesList.append(WTF::move(fastValues));
    }

    m_currentBlock = slowCase;

    return fastValuesList;
}


auto OMGIRGenerator::addCallIndirect(unsigned callProfileIndex, unsigned tableIndex, const RTT& signature, ArgumentList& args, ResultList& results, CallType callType) -> PartialResult
{
    UNUSED_PARAM(callProfileIndex);
    Value* calleeIndex = get(args.takeLast());
    const bool isTailCallRootCaller = callType == CallType::TailCall && !m_inlineParent;
    const bool isTailCallInlineCaller = callType == CallType::TailCall && m_inlineParent;
    ASSERT(signature.argumentCount() == args.size());

    TRACE_CF("Call_indirect: entered with table index: ", tableIndex, " ", signature);

    // Note: call indirect can call either WebAssemblyFunction or WebAssemblyWrapperFunction. Because
    // WebAssemblyWrapperFunction is like calling into the js, we conservatively assume all call indirects
    // can be to the js for our stack check calculation.
    m_maxNumJSCallArguments = std::max(m_maxNumJSCallArguments, static_cast<uint32_t>(args.size()));

    Value* callableFunctionBuffer = nullptr;
    Value* callableFunctionBufferLength;
    {
        ASSERT(tableIndex < m_info.tableCount());
        auto& tableInformation = m_info.table(tableIndex);

        if (tableInformation.maximum() && tableInformation.maximum().value() == tableInformation.initial()) {
            // The buffer is immutable & non-control-dependent since this table is not resizable / reaching to the maximum size.
            callableFunctionBufferLength = constant(B3::Int32, tableInformation.initial(), origin());
            if (!tableIndex) {
                auto* result = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfCachedTable0Buffer()));
                m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_cachedTable0Buffer, result);
                result->setReadsMutability(B3::Mutability::Immutable);
                result->setControlDependent(false);
                callableFunctionBuffer = result;
            } else {
                auto* table = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfTable(m_info, tableIndex)));
                m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_tables[tableIndex], table);
                table->setReadsMutability(B3::Mutability::Immutable);
                table->setControlDependent(false);

                if (!tableInformation.isImport()) {
                    // Table is fixed-sized and it is not imported one. Thus this is definitely fixed-sized FuncRefTable.
                    callableFunctionBuffer = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), table, constant(pointerType(), safeCast<int32_t>(FuncRefTable::offsetOfFunctionsForFixedSizedTable())));
                } else {
                    auto* result = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), table, safeCast<int32_t>(FuncRefTable::offsetOfFunctions()));
                    m_heaps.decorateMemory(&m_heaps.WasmFuncRefTable_functions, result);
                    result->setReadsMutability(B3::Mutability::Immutable);
                    result->setControlDependent(false);
                    callableFunctionBuffer = result;
                }
            }
        } else {
            if (!tableIndex) {
                callableFunctionBufferLength = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int32, origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfCachedTable0Length()));
                m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_cachedTable0Length, callableFunctionBufferLength);

                callableFunctionBuffer = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfCachedTable0Buffer()));
                m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_cachedTable0Buffer, callableFunctionBuffer);
            } else {
                auto* table = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfTable(m_info, tableIndex)));
                m_heaps.decorateMemory(&m_heaps.JSWebAssemblyInstance_tables[tableIndex], table);
                table->setReadsMutability(B3::Mutability::Immutable);
                table->setControlDependent(false);

                callableFunctionBufferLength = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int32, origin(), table, safeCast<int32_t>(Table::offsetOfLength()));
                m_heaps.decorateMemory(&m_heaps.WasmTable_length, callableFunctionBufferLength);

                callableFunctionBuffer = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), table, safeCast<int32_t>(FuncRefTable::offsetOfFunctions()));
                m_heaps.decorateMemory(&m_heaps.WasmFuncRefTable_functions, callableFunctionBuffer);
            }
        }
    }

    // Check the index we are looking for is valid.
    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, AboveEqual, origin(), calleeIndex, callableFunctionBufferLength));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsCallIndirect);
        });
    }

    calleeIndex = pointerOfInt32(calleeIndex);

    BasicBlock* continuation = m_proc.addBlock();

    Value* callableFunction = m_currentBlock->appendNew<Value>(m_proc, Add, origin(), callableFunctionBuffer, m_currentBlock->appendNew<Value>(m_proc, Mul, origin(), calleeIndex, constant(pointerType(), sizeof(FuncRefTable::Function))));

    // Check that the WasmToWasmImportableFunction is initialized. We trap if it isn't. A null `rtt` indicates it's not initialized.
    // FIXME: when we have trap handlers, we can just let the call fail because RTT is nullptr.
    // https://bugs.webkit.org/show_bug.cgi?id=177210
    static_assert(sizeof(WasmToWasmImportableFunction::rtt) == sizeof(uintptr_t), "Load codegen assumes ptr");
    Value* calleeCallee = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), callableFunction, safeCast<int32_t>(FuncRefTable::Function::offsetOfBoxedCallee()));
    m_heaps.decorateMemory(&m_heaps.WasmFuncRefTableFunction_boxedCallee, calleeCallee);

    Value* calleeInstance = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), callableFunction, safeCast<int32_t>(FuncRefTable::Function::offsetOfTargetInstance()));
    m_heaps.decorateMemory(&m_heaps.WasmFuncRefTableFunction_targetInstance, calleeInstance);

    auto inliningResult = tryInliningPolymorphicCalls(callProfileIndex, calleeInstance, calleeCallee, signature, args, callType, isTailCallRootCaller, continuation);
    if (!inliningResult.has_value()) [[unlikely]]
        return makeUnexpected(WTF::move(inliningResult.error()));

    auto fastValuesList = WTF::move(inliningResult.value());

    Value* calleeCodeLocation = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), callableFunction, safeCast<int32_t>(FuncRefTable::Function::offsetOfEntrypointLoadLocation()));
    m_heaps.decorateMemory(&m_heaps.WasmFuncRefTableFunction_entrypointLoadLocation, calleeCodeLocation);

    Value* calleeRTT = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), callableFunction, safeCast<int32_t>(FuncRefTable::Function::offsetOfRTT()));
    m_heaps.decorateMemory(&m_heaps.WasmFuncRefTableFunction_rtt, calleeRTT);

    Value* expectedRTT = constant(pointerType(), std::bit_cast<uintptr_t>(&signature));

    if (signature.isFinalType()) {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), m_currentBlock->appendNew<Value>(m_proc, NotEqual, origin(), calleeRTT, expectedRTT));
        check->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::BadSignature);
        });
    } else {
        BasicBlock* checkDone = m_proc.addBlock();
        BasicBlock* moreChecks = m_proc.addBlock();

        Value* hasEqualSignatures = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), calleeRTT, expectedRTT);
        m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(), hasEqualSignatures, FrequentedBlock(checkDone), FrequentedBlock(moreChecks, FrequencyClass::Rare));
        moreChecks->addPredecessor(m_currentBlock);
        checkDone->addPredecessor(m_currentBlock);

        m_currentBlock = moreChecks;
        CheckValue* checkNull = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), calleeRTT, constant(pointerType(), 0)));
        checkNull->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::BadSignature);
        });

        auto* rttSize = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int32, origin(), calleeRTT, safeCast<int32_t>(RTT::offsetOfDisplaySizeExcludingThis()));
        m_heaps.decorateMemory(&m_heaps.WasmRTT_displaySizeExcludingThis, rttSize);

        CheckValue* checkRTTSize = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), m_currentBlock->appendNew<Value>(m_proc, BelowEqual, origin(), rttSize, constant(Int32, signature.displaySizeExcludingThis())));
        checkRTTSize->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::BadSignature);
        });

        auto* displayEntry = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), calleeRTT, safeCast<int32_t>(RTT::offsetOfData() + signature.displaySizeExcludingThis() * sizeof(RefPtr<const RTT>)));
        m_heaps.decorateMemory(&m_heaps.WasmRTT_data[signature.displaySizeExcludingThis()], displayEntry);
        displayEntry->setReadsMutability(B3::Mutability::Immutable);
        displayEntry->setControlDependent(false);

        CheckValue* checkRTTDisplayEntry = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), m_currentBlock->appendNew<Value>(m_proc, NotEqual, origin(), displayEntry, constant(pointerType(), std::bit_cast<uintptr_t>(&signature))));
        checkRTTDisplayEntry->setGenerator([=, this, origin = this->origin()](CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::BadSignature);
        });

        m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), checkDone);
        checkDone->addPredecessor(m_currentBlock);

        m_currentBlock = checkDone;
    }

    Value* calleeCode = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), calleeCodeLocation);
    m_heaps.decorateMemory(&m_heaps.WasmWasmCallableFunctionLocation_value, calleeCode);

    ValueResults slowValues;
    auto result = emitIndirectCall(calleeInstance, calleeCode, calleeCallee, signature, args, slowValues, callType);
    if (!result.has_value()) [[unlikely]]
        return result;

    if (!isTailCallRootCaller) {
        for (Value*& value : slowValues) {
            auto* input = value;
            value = m_currentBlock->appendNew<UpsilonValue>(m_proc, origin(), input);
        }
        m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);
        continuation->addPredecessor(m_currentBlock);

        m_currentBlock = continuation;
        for (unsigned i = 0; i < slowValues.size(); ++i) {
            auto* slowValue = slowValues[i];
            auto* phi = m_currentBlock->appendNew<Value>(m_proc, Phi, slowValue->child(0)->type(), origin());
            slowValue->as<UpsilonValue>()->setPhi(phi);
            for (auto& fastValues : fastValuesList) {
                auto* fastValue = fastValues[i];
                fastValue->as<B3::UpsilonValue>()->setPhi(phi);
            }
            results.append(push(phi));
        }

        if (isTailCallInlineCaller) {
            ASSERT(m_returnContinuation);
            return addInlinedReturn(results);
        }
    }

    return { };
}

auto OMGIRGenerator::addCallRef(unsigned callProfileIndex, const RTT& signature, ArgumentList& args, ResultList& results, CallType callType) -> PartialResult
{
    UNUSED_PARAM(callProfileIndex);
    TypedExpression calleeArg = args.takeLast();
    Value* callee = get(calleeArg);
    TRACE_VALUE(Wasm::Types::Void, callee, "call_ref: ", signature);
    const bool isTailCallRootCaller = callType == CallType::TailCall && !m_inlineParent;
    const bool isTailCallInlineCaller = callType == CallType::TailCall && m_inlineParent;
    ASSERT(signature.argumentCount() == args.size());
    m_makesCalls = true;

    TRACE_CF("CallRef: entered with ", signature);

    // Note: call ref can call either WebAssemblyFunction or WebAssemblyWrapperFunction. Because
    // WebAssemblyWrapperFunction is like calling into the js, we conservatively assume all call indirects
    // can be to the js for our stack check calculation.
    m_maxNumJSCallArguments = std::max(m_maxNumJSCallArguments, static_cast<uint32_t>(args.size()));

    int32_t offset = safeCast<int32_t>(WebAssemblyFunctionBase::offsetOfTargetInstance());
    bool canTrap = false;
    if (calleeArg.type().isNullable())
        canTrap = emitNullCheckBeforeAccess(callee, offset);
    auto wrapTrapping = [&](auto input) -> B3::Kind {
        if (canTrap)
            return trapping(input);
        return input;
    };

    Value* calleeInstance = m_currentBlock->appendNew<MemoryValue>(m_proc, wrapTrapping(Load), pointerType(), origin(), pointerOfWasmRef(callee), offset);
    m_heaps.decorateMemory(&m_heaps.WebAssemblyFunctionBase_targetInstance, calleeInstance);

    Value* calleeCallee = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), pointerOfWasmRef(callee), safeCast<int32_t>(WebAssemblyFunctionBase::offsetOfBoxedCallee()));
    m_heaps.decorateMemory(&m_heaps.WebAssemblyFunctionBase_boxedCallee, calleeCallee);

    BasicBlock* continuation = m_proc.addBlock();

    auto inliningResult = tryInliningPolymorphicCalls(callProfileIndex, calleeInstance, calleeCallee, signature, args, callType, isTailCallRootCaller, continuation);
    if (!inliningResult.has_value()) [[unlikely]]
        return makeUnexpected(WTF::move(inliningResult.error()));

    auto fastValuesList = WTF::move(inliningResult.value());

    Value* calleeCodeLocation = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), pointerOfWasmRef(callee), safeCast<int32_t>(WebAssemblyFunctionBase::offsetOfEntrypointLoadLocation()));
    m_heaps.decorateMemory(&m_heaps.WebAssemblyFunctionBase_entrypointLoadLocation, calleeCodeLocation);

    Value* calleeCode = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), calleeCodeLocation);
    m_heaps.decorateMemory(&m_heaps.WasmWasmCallableFunctionLocation_value, calleeCode);

    ValueResults slowValues;
    auto result = emitIndirectCall(calleeInstance, calleeCode, calleeCallee, signature, args, slowValues, callType);
    if (!result.has_value()) [[unlikely]]
        return result;

    if (!isTailCallRootCaller) {
        for (Value*& value : slowValues) {
            auto* input = value;
            value = m_currentBlock->appendNew<UpsilonValue>(m_proc, origin(), input);
        }
        m_currentBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);
        continuation->addPredecessor(m_currentBlock);

        m_currentBlock = continuation;
        for (unsigned i = 0; i < slowValues.size(); ++i) {
            auto* slowValue = slowValues[i];
            auto* phi = m_currentBlock->appendNew<Value>(m_proc, Phi, slowValue->child(0)->type(), origin());
            slowValue->as<B3::UpsilonValue>()->setPhi(phi);
            for (auto& fastValues : fastValuesList) {
                auto* fastValue = fastValues[i];
                fastValue->as<B3::UpsilonValue>()->setPhi(phi);
            }
            results.append(push(phi));
        }

        if (isTailCallInlineCaller) {
            ASSERT(m_returnContinuation);
            return addInlinedReturn(results);
        }
    }
    return { };
}

void OMGIRGenerator::unify(Value* phi, const ExpressionType& source)
{
    m_currentBlock->appendNew<UpsilonValue>(m_proc, origin(), get(source), phi);
}

void OMGIRGenerator::unifyValuesWithBlock(std::span<const TypedExpression> resultStack, const ControlData& block)
{
    const Vector<Value*>& phis = block.phis;
    size_t resultSize = phis.size();

    ASSERT(resultSize <= resultStack.size());

    for (size_t i = 0; i < resultSize; ++i)
        unify(phis[resultSize - 1 - i], resultStack[resultStack.size() - 1 - i]);
}

static void dumpExpressionStack(const CommaPrinter& comma, std::span<const OMGIRGenerator::TypedExpression> expressionStack)
{
    dataLog(comma, "ExpressionStack:");
    for (const auto& expression : expressionStack)
        dataLog(comma, expression);
}

void OMGIRGenerator::dump(const ControlStack& controlStack, const Stack* expressionStack)
{
    UNUSED_PARAM(expressionStack);
    dataLogLn("Constants:");
    for (const auto& constant : m_constantPool)
        dataLogLn(deepDump(m_proc, constant.value));

    dataLogLn("Processing Graph:");
    dataLog(m_proc);
    dataLogLn("With current block:", *m_currentBlock);
    dataLogLn("Control stack:");
    ASSERT(controlStack.size());
    std::span<const TypedExpression> currentSlice = m_parser->expressionStack();
    for (size_t i = controlStack.size(); i--;) {
        dataLog("  ", controlStack[i].controlData, ": ");
        CommaPrinter comma(", "_s, ""_s);
        dumpExpressionStack(comma, currentSlice);
        currentSlice = m_parser->enclosedSliceOf(i);
        dataLogLn();
    }
    dataLogLn();
}

auto OMGIRGenerator::origin() -> Origin
{
    if (!m_parser)
        return Origin();

    OpcodeOrigin opcodeOrigin = OpcodeOrigin(m_parser->currentOpcode(), m_parser->currentOpcodeStartingOffset());
    switch (m_parser->currentOpcode()) {
    case OpType::Ext1:
    case OpType::ExtGC:
    case OpType::ExtAtomic:
    case OpType::ExtSIMD:
        opcodeOrigin = OpcodeOrigin(m_parser->currentOpcode(), m_parser->currentExtendedOpcode(), m_parser->currentOpcodeStartingOffset());
        break;
    default:
        break;
    }
    ASSERT(isValidOpType(static_cast<uint8_t>(opcodeOrigin.opcode())));
    WasmOrigin result { CallSiteIndex(callSiteIndex()), opcodeOrigin };
    if (m_context.origins.isEmpty() || m_context.origins.last() != result)
        m_context.origins.append(result);
    return Origin(&m_context.origins.last());
}

static bool shouldDumpIRFor(uint32_t functionIndex)
{
    static LazyNeverDestroyed<FunctionAllowlist> dumpAllowlist;
    static std::once_flag initializeAllowlistFlag;
    std::call_once(initializeAllowlistFlag, [] {
        const char* functionAllowlistFile = Options::wasmOMGFunctionsToDump();
        dumpAllowlist.construct(functionAllowlistFile);
    });
    return dumpAllowlist->shouldDumpWasmFunction(functionIndex);
}

Expected<std::unique_ptr<InternalFunction>, String> parseAndCompileOMG(CompilationContext& compilationContext, IPIntCallee& profiledCallee, OptimizingJITCallee& callee, const FunctionData& function, const RTT& signature, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, Module& module, CalleeGroup& calleeGroup, const ModuleInformation& info, MemoryMode mode, CompilationMode compilationMode, FunctionCodeIndex functionIndex, uint32_t loopIndexForOSREntry)
{
    CompilerTimingScope totalScope("B3"_s, "Total OMG compilation"_s);

    Wasm::Thunks::singleton().stub(Wasm::catchInWasmThunkGenerator);

    RefPtr<JSON::Object> ionGraphFunction;
    RefPtr<JSON::Array> ionGraphPasses;
    auto functionIndexSpace = info.toSpaceIndex(profiledCallee.functionIndex());
    if (Options::dumpIonGraph()) [[unlikely]] {
        ionGraphFunction = JSON::Object::create();
        auto passes = JSON::Array::create();
        ionGraphPasses = passes.get();
        ionGraphFunction->setString("name"_s, callee.nameWithHash());
        ionGraphFunction->setString("tier"_s, "OMG"_s);
        ionGraphFunction->setBoolean("osr"_s, compilationMode == CompilationMode::OMGForOSREntryMode);
        ionGraphFunction->setArray("passes"_s, WTF::move(passes));
    }
    auto result = makeUnique<InternalFunction>();
    InliningDecision inliningDecision(module, profiledCallee);
    inliningDecision.expand();

    compilationContext.wasmEntrypointJIT = makeUnique<CCallHelpers>();
    compilationContext.procedure = makeUniqueWithoutFastMallocCheck<Procedure>(info.usesSIMD(functionIndex));

    Procedure& procedure = *compilationContext.procedure;
    procedure.setIsWasm(true);
    procedure.setName(callee.nameWithHash());
    if (shouldDumpIRFor(functionIndex + info.importFunctionCount()))
        procedure.setShouldDumpIR();

    procedure.setNeedsPCToOriginMap();
    procedure.setOriginPrinter([](PrintStream& out, Origin origin) {
        if (auto* impl = origin.maybeWasmOrigin())
            out.print("Wasm: ", impl->m_opcodeOrigin, " CallSiteIndex: ", impl->m_callSiteIndex.bits());
    });
    if (ionGraphPasses) [[unlikely]]
        procedure.setIonGraphPasses(*ionGraphPasses);

    // This means we cannot use either StackmapGenerationParams::usedRegisters() or
    // StackmapGenerationParams::unavailableRegisters(). In exchange for this concession, we
    // don't strictly need to run Air::reportUsedRegisters(), which saves a bit of CPU time at
    // optLevel=1.
    procedure.setNeedsUsedRegisters(false);
    
    procedure.setOptLevel(Options::wasmOMGOptimizationLevel());

    procedure.code().setForceIRCRegisterAllocation();

    result->outgoingJITDirectCallees = FixedBitVector(info.internalFunctionCount());
    OMGIRGenerator irGenerator(procedure.heaps(), compilationContext, module, calleeGroup, info, profiledCallee, inliningDecision.root(), callee, procedure, unlinkedWasmToWasmCalls, result->outgoingJITDirectCallees, result->osrEntryScratchBufferSize, mode, compilationMode, functionIndex, loopIndexForOSREntry);
    FunctionParser<OMGIRGenerator> parser(irGenerator, function.data, signature, info);
    WASM_FAIL_IF_HELPER_FAILS(parser.parse());

    irGenerator.insertEntrySwitch();
    irGenerator.insertConstants();

    // Make sure everything is decorated. This does a bunch of deferred decorating. This has
    // to happen last because our abstract heaps are generated lazily. They have to be
    // generated lazily because we have an infinite number of numbered, indexed, and
    // absolute heaps. We only become aware of the ones we actually mention while lowering.
    procedure.heaps().computeRangesAndDecorateInstructions();

    procedure.resetReachability();
    if (ASSERT_ENABLED)
        validate(procedure, "After parsing:\n");

    estimateStaticExecutionCounts(procedure);

    dataLogIf(WasmOMGIRGeneratorInternal::verbose, "Pre SSA: ", procedure);
    fixSSA(procedure);
    dataLogIf(WasmOMGIRGeneratorInternal::verbose, "Post SSA: ", procedure);

    {
        if (shouldDumpDisassemblyFor(compilationMode))
            procedure.code().setDisassembler(makeUniqueWithoutFastMallocCheck<B3::Air::Disassembler>());
        B3::prepareForGeneration(procedure);
        B3::generate(procedure, *compilationContext.wasmEntrypointJIT);
        compilationContext.wasmEntrypointByproducts = procedure.releaseByproducts();
        result->entrypoint.calleeSaveRegisters = procedure.calleeSaveRegisterAtOffsetList();
    }

    result->stackmaps = irGenerator.takeStackmaps();
    result->exceptionHandlers = irGenerator.takeExceptionHandlers();

    if (compilationMode == CompilationMode::OMGForOSREntryMode) {
        int32_t checkSize = 0;
        bool needsOverflowCheck = false;
        irGenerator.computeStackCheckSize(needsOverflowCheck, checkSize);
        ASSERT(checkSize || !needsOverflowCheck);
        if (!needsOverflowCheck)
            checkSize = stackCheckNotNeeded;
        uncheckedDowncast<OMGOSREntryCallee>(callee).setStackCheckSize(checkSize);
    }

    if (ionGraphFunction) [[unlikely]]
        ProfilerSupport::dumpIonGraphFunction(makeString("wasm-function-"_s, functionIndexSpace.rawIndex()), "OMG"_s, compilationMode == CompilationMode::OMGForOSREntryMode, ionGraphFunction.releaseNonNull());

    return result;
}

// Custom wasm ops. These are the ones too messy to do in wasm.json.

void OMGIRGenerator::emitChecksForModOrDiv(B3::Opcode operation, Value* left, Value* right)
{
    ASSERT(operation == Div || operation == Mod || operation == UDiv || operation == UMod);
    const B3::Type type = left->type();

    {
        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), right, constant(type, 0)));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::DivisionByZero);
        });
    }

    if (operation == Div) {
        int64_t min = type == Int32 ? std::numeric_limits<int32_t>::min() : std::numeric_limits<int64_t>::min();

        CheckValue* check = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(),
            m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
                m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), left, constant(type, min)),
                m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), right, constant(type, -1))));

        check->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
            this->emitExceptionCheck(jit, origin, ExceptionType::IntegerOverflow);
        });
    }
}

auto OMGIRGenerator::addI32DivS(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = Div;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, op, origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI32RemS(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = Mod;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, chill(op), origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI32DivU(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = UDiv;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, op, origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI32RemU(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = UMod;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, op, origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI64DivS(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = Div;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, op, origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI64RemS(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = Mod;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, chill(op), origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI64DivU(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = UDiv;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, op, origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI64RemU(ExpressionType leftVar, ExpressionType rightVar, ExpressionType& result) -> PartialResult
{
    const B3::Opcode op = UMod;
    Value* left = get(leftVar);
    Value* right = get(rightVar);
    emitChecksForModOrDiv(op, left, right);
    result = push(m_currentBlock->appendNew<Value>(m_proc, op, origin(), left, right));
    return { };
}

auto OMGIRGenerator::addI32Ctz(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int32, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.countTrailingZeros32(params[1].gpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI64Ctz(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int64, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.countTrailingZeros64(params[1].gpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI32Popcnt(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    if (MacroAssembler::supportsCountPopulation()) {
        PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int32, origin());
        patchpoint->append(arg, ValueRep::SomeRegister);
#if CPU(X86_64)
        patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
            jit.countPopulation32(params[1].gpr(), params[0].gpr());
        });
#else
        patchpoint->numFPScratchRegisters = 1;
        patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
            jit.countPopulation32(params[1].gpr(), params[0].gpr(), params.fpScratch(0));
        });
#endif
        patchpoint->effects = Effects::none();
        result = push(patchpoint);
        return { };
    }

    // Pure math function does not need to call emitPrepareWasmOperation.
    Value* funcAddress = m_currentBlock->appendNew<ConstPtrValue>(m_proc, origin(), tagCFunction<OperationPtrTag>(operationPopcount32));
    result = push(m_currentBlock->appendNew<CCallValue>(m_proc, Int32, origin(), Effects::none(), funcAddress, arg));
    return { };
}

auto OMGIRGenerator::addI64Popcnt(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    if (MacroAssembler::supportsCountPopulation()) {
        PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int64, origin());
        patchpoint->append(arg, ValueRep::SomeRegister);
#if CPU(X86_64)
        patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
            jit.countPopulation64(params[1].gpr(), params[0].gpr());
        });
#else
        patchpoint->numFPScratchRegisters = 1;
        patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
            jit.countPopulation64(params[1].gpr(), params[0].gpr(), params.fpScratch(0));
        });
#endif
        patchpoint->effects = Effects::none();
        result = push(patchpoint);
        return { };
    }

    // Pure math function does not need to call emitPrepareWasmOperation.
    Value* funcAddress = m_currentBlock->appendNew<ConstPtrValue>(m_proc, origin(), tagCFunction<OperationPtrTag>(operationPopcount64));
    result = push(m_currentBlock->appendNew<CCallValue>(m_proc, Int64, origin(), Effects::none(), funcAddress, arg));
    return { };
}

auto OMGIRGenerator::addF64ConvertUI64(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Double, origin());
    if (isX86())
        patchpoint->numGPScratchRegisters = 1;
    patchpoint->clobber(RegisterSet::macroClobberedGPRs());
    patchpoint->append(ConstrainedValue(arg, ValueRep::SomeRegister));
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
#if CPU(X86_64)
        jit.convertUInt64ToDouble(params[1].gpr(), params[0].fpr(), params.gpScratch(0));
#else
        jit.convertUInt64ToDouble(params[1].gpr(), params[0].fpr());
#endif
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addF32ConvertUI64(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Float, origin());
    if (isX86())
        patchpoint->numGPScratchRegisters = 1;
    patchpoint->clobber(RegisterSet::macroClobberedGPRs());
    patchpoint->append(ConstrainedValue(arg, ValueRep::SomeRegister));
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
#if CPU(X86_64)
        jit.convertUInt64ToFloat(params[1].gpr(), params[0].fpr(), params.gpScratch(0));
#else
        jit.convertUInt64ToFloat(params[1].gpr(), params[0].fpr());
#endif
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addF64Nearest(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Double, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.roundTowardNearestIntDouble(params[1].fpr(), params[0].fpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addF32Nearest(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Float, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.roundTowardNearestIntFloat(params[1].fpr(), params[0].fpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI32TruncSF64(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Double, std::bit_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int32_t>::min())));
    Value* min = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) - 1.0));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterThan, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int32, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.truncateDoubleToInt32(params[1].fpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI32TruncSF32(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Float, std::bit_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int32_t>::min())));
    Value* min = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min())));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterEqual, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int32, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.truncateFloatToInt32(params[1].fpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}


auto OMGIRGenerator::addI32TruncUF64(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) * -2.0));
    Value* min = constant(Double, std::bit_cast<uint64_t>(-1.0));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterThan, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int32, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.truncateDoubleToUint32(params[1].fpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI32TruncUF32(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min()) * static_cast<float>(-2.0)));
    Value* min = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(-1.0)));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterThan, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int32, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.truncateFloatToUint32(params[1].fpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI64TruncSF64(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Double, std::bit_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int64_t>::min())));
    Value* min = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min())));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterEqual, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int64, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.truncateDoubleToInt64(params[1].fpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI64TruncUF64(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min()) * -2.0));
    Value* min = constant(Double, std::bit_cast<uint64_t>(-1.0));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterThan, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });

    Value* signBitConstant;
    if (isX86()) {
        // Since x86 doesn't have an instruction to convert floating points to unsigned integers, we at least try to do the smart thing if
        // the numbers are would be positive anyway as a signed integer. Since we cannot materialize constants into fprs we have b3 do it
        // so we can pool them if needed.
        signBitConstant = constant(Double, std::bit_cast<uint64_t>(static_cast<double>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
    }
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int64, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    if (isX86()) {
        patchpoint->append(signBitConstant, ValueRep::SomeRegister);
        patchpoint->numFPScratchRegisters = 1;
    }
    patchpoint->clobber(RegisterSet::macroClobberedGPRs());
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        FPRReg scratch = InvalidFPRReg;
        FPRReg constant = InvalidFPRReg;
        if (isX86()) {
            scratch = params.fpScratch(0);
            constant = params[2].fpr();
        }
        jit.truncateDoubleToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI64TruncSF32(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Float, std::bit_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int64_t>::min())));
    Value* min = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min())));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterEqual, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int64, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        jit.truncateFloatToInt64(params[1].fpr(), params[0].gpr());
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

auto OMGIRGenerator::addI64TruncUF32(ExpressionType argVar, ExpressionType& result) -> PartialResult
{
    Value* arg = get(argVar);
    Value* max = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min()) * static_cast<float>(-2.0)));
    Value* min = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(-1.0)));
    Value* outOfBounds = m_currentBlock->appendNew<Value>(m_proc, BitAnd, origin(),
        m_currentBlock->appendNew<Value>(m_proc, LessThan, origin(), arg, max),
        m_currentBlock->appendNew<Value>(m_proc, GreaterThan, origin(), arg, min));
    outOfBounds = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), outOfBounds, constant(Int32, 0));
    CheckValue* trap = m_currentBlock->appendNew<CheckValue>(m_proc, Check, origin(), outOfBounds);
    trap->setGenerator([=, this, origin = this->origin()] (CCallHelpers& jit, const StackmapGenerationParams&) {
        this->emitExceptionCheck(jit, origin, ExceptionType::OutOfBoundsTrunc);
    });

    Value* signBitConstant;
    if (isX86()) {
        // Since x86 doesn't have an instruction to convert floating points to unsigned integers, we at least try to do the smart thing if
        // the numbers would be positive anyway as a signed integer. Since we cannot materialize constants into fprs we have b3 do it
        // so we can pool them if needed.
        signBitConstant = constant(Float, std::bit_cast<uint32_t>(static_cast<float>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
    }
    PatchpointValue* patchpoint = m_currentBlock->appendNew<PatchpointValue>(m_proc, Int64, origin());
    patchpoint->append(arg, ValueRep::SomeRegister);
    if (isX86()) {
        patchpoint->append(signBitConstant, ValueRep::SomeRegister);
        patchpoint->numFPScratchRegisters = 1;
    }
    patchpoint->clobber(RegisterSet::macroClobberedGPRs());
    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
        AllowMacroScratchRegisterUsage allowScratch(jit);
        FPRReg scratch = InvalidFPRReg;
        FPRReg constant = InvalidFPRReg;
        if (isX86()) {
            scratch = params.fpScratch(0);
            constant = params[2].fpr();
        }
        jit.truncateFloatToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
    });
    patchpoint->effects = Effects::none();
    result = push(patchpoint);
    return { };
}

} } // namespace JSC::Wasm

#include "WasmOMGIRGeneratorInlines.h"

WTF_ALLOW_UNSAFE_BUFFER_USAGE_END

#endif // ENABLE(WEBASSEMBLY_OMGJIT)
