File: WasmIRGeneratorHelpers.h

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (233 lines) | stat: -rw-r--r-- 10,459 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
 * Copyright (C) 2022-2024 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.
 */

#pragma once

#if ENABLE(WEBASSEMBLY_OMGJIT) || ENABLE(WEBASSEMBLY_BBQJIT)

#include "AirCode.h"
#include "B3StackmapGenerationParams.h"
#include "B3StackmapValue.h"
#include "CCallHelpers.h"
#include "JSWebAssemblyException.h"
#include "JSWebAssemblyInstance.h"
#include "LinkBuffer.h"
#include "ProbeContext.h"
#include "WasmOperations.h"

namespace JSC { namespace Wasm {

struct PatchpointExceptionHandleBase {
    static constexpr unsigned s_invalidCallSiteIndex = std::numeric_limits<unsigned>::max();
};

#if ENABLE(WEBASSEMBLY_OMGJIT)

struct PatchpointExceptionHandle : public PatchpointExceptionHandleBase {
    PatchpointExceptionHandle(std::optional<bool> hasExceptionHandlers, unsigned callSiteIndex)
        : m_hasExceptionHandlers(hasExceptionHandlers)
        , m_callSiteIndex(callSiteIndex)
    { }

    PatchpointExceptionHandle(std::optional<bool> hasExceptionHandlers, unsigned callSiteIndex, unsigned numLiveValues, unsigned firstStackmapParamOffset, unsigned firstStackmapChildOffset)
        : m_hasExceptionHandlers(hasExceptionHandlers)
        , m_callSiteIndex(callSiteIndex)
        , m_numLiveValues(numLiveValues)
        , m_firstStackmapParamOffset(firstStackmapParamOffset)
        , m_firstStackmapChildOffset(firstStackmapChildOffset)
    { }

    template <typename Generator>
    void generate(CCallHelpers& jit, const B3::StackmapGenerationParams& params, Generator* generator) const
    {
        JIT_COMMENT(jit, "Store call site index ", m_callSiteIndex, " at throw or call site.");
        jit.store32(CCallHelpers::TrustedImm32(m_callSiteIndex), CCallHelpers::tagFor(CallFrameSlot::argumentCountIncludingThis));

        if (m_hasExceptionHandlers && !*m_hasExceptionHandlers)
            return;
        if (!m_numLiveValues)
            return;

        StackMap values(*m_numLiveValues);
        for (unsigned i = 0; i < *m_numLiveValues; ++i)
            values[i] = OSREntryValue(params[i + m_firstStackmapParamOffset], params.value()->child(i + m_firstStackmapChildOffset)->type());

        generator->addStackMap(m_callSiteIndex, WTFMove(values));
    }

    std::optional<bool> m_hasExceptionHandlers;
    unsigned m_callSiteIndex { s_invalidCallSiteIndex };
    std::optional<unsigned> m_numLiveValues { };
    unsigned m_firstStackmapParamOffset { };
    unsigned m_firstStackmapChildOffset { };
};

#else

using PatchpointExceptionHandle = PatchpointExceptionHandleBase;

#endif


static inline void computeExceptionHandlerAndLoopEntrypointLocations(Vector<CodeLocationLabel<ExceptionHandlerPtrTag>>& handlers, Vector<CodeLocationLabel<WasmEntryPtrTag>>& loopEntrypoints, const InternalFunction* function, const CompilationContext& context, LinkBuffer& linkBuffer)
{
    if (!context.procedure) {
        ASSERT(Options::useBBQJIT());

        for (auto label : function->bbqLoopEntrypoints)
            loopEntrypoints.append(linkBuffer.locationOf<WasmEntryPtrTag>(label));

        unsigned index = 0;
        for (const UnlinkedHandlerInfo& handlerInfo : function->exceptionHandlers) {
            if (handlerInfo.m_type == HandlerType::Delegate) {
                handlers.append({ });
                continue;
            }
            handlers.append(linkBuffer.locationOf<ExceptionHandlerPtrTag>(context.catchEntrypoints[index++]));
        }
        return;
    }

#if ENABLE(WEBASSEMBLY_OMGJIT)

    unsigned entrypointIndex = 1;
    unsigned numEntrypoints = context.procedure->numEntrypoints();
    for (const UnlinkedHandlerInfo& handlerInfo : function->exceptionHandlers) {
        if (handlerInfo.m_type == HandlerType::Delegate) {
            handlers.append({ });
            continue;
        }

        RELEASE_ASSERT(entrypointIndex < numEntrypoints);
        handlers.append(linkBuffer.locationOf<ExceptionHandlerPtrTag>(context.procedure->code().entrypointLabel(entrypointIndex)));
        ++entrypointIndex;
    }

    for (; entrypointIndex < numEntrypoints; ++entrypointIndex)
        loopEntrypoints.append(linkBuffer.locationOf<WasmEntryPtrTag>(context.procedure->code().entrypointLabel(entrypointIndex)));
#else
    RELEASE_ASSERT_NOT_REACHED();
#endif

}

static inline void computeExceptionHandlerLocations(Vector<CodeLocationLabel<ExceptionHandlerPtrTag>>& handlers, const InternalFunction* function, const CompilationContext& context, LinkBuffer& linkBuffer)
{
    Vector<CodeLocationLabel<WasmEntryPtrTag>> ignored;
    computeExceptionHandlerAndLoopEntrypointLocations(handlers, ignored, function, context, linkBuffer);
}

static inline void emitThrowRefImpl(CCallHelpers& jit)
{
    // JSWebAssemblyInstance in argumentGPR0
    // exception pointer in argumentGPR1

    GPRReg scratch = GPRInfo::nonPreservedNonArgumentGPR0;
    jit.loadPtr(CCallHelpers::Address(GPRInfo::argumentGPR0, JSWebAssemblyInstance::offsetOfVM()), scratch);
    jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(scratch);

    jit.prepareWasmCallOperation(GPRInfo::argumentGPR0);
    jit.callOperation<OperationPtrTag>(operationWasmRethrow);
    jit.farJump(GPRInfo::returnValueGPR, ExceptionHandlerPtrTag);
}

static inline void emitThrowImpl(CCallHelpers& jit, unsigned exceptionIndex)
{
    JIT_COMMENT(jit, "throw impl, index: ", exceptionIndex);
    // JSWebAssemblyInstance in argumentGPR0
    // arguments to the exception off of stack pointer

    GPRReg scratch = GPRInfo::nonPreservedNonArgumentGPR0;
    jit.loadPtr(CCallHelpers::Address(GPRInfo::argumentGPR0, JSWebAssemblyInstance::offsetOfVM()), scratch);
    jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(scratch);

    jit.move(MacroAssembler::TrustedImm32(exceptionIndex), GPRInfo::argumentGPR1);
    jit.move(MacroAssembler::stackPointerRegister, GPRInfo::argumentGPR2);
    jit.prepareWasmCallOperation(GPRInfo::argumentGPR0);
    jit.callOperation<OperationPtrTag>(operationWasmThrow);
    jit.farJump(GPRInfo::returnValueGPR, ExceptionHandlerPtrTag);
}

#if ENABLE(WEBASSEMBLY_OMGJIT)
template<SavedFPWidth savedFPWidth>
static ALWAYS_INLINE void buildEntryBufferForCatch(Probe::Context& context)
{
    unsigned valueSize = (savedFPWidth == SavedFPWidth::SaveVectors) ? 2 : 1;
    CallFrame* callFrame = context.fp<CallFrame*>();
    CallSiteIndex callSiteIndex = callFrame->callSiteIndex();
    OptimizingJITCallee* callee = std::bit_cast<OptimizingJITCallee*>(callFrame->callee().asNativeCallee());
    const StackMap& stackmap = callee->stackmap(callSiteIndex);
    JSWebAssemblyInstance* instance = context.gpr<JSWebAssemblyInstance*>(GPRInfo::wasmContextInstancePointer);
    EncodedJSValue exception = context.gpr<EncodedJSValue>(GPRInfo::returnValueGPR);
    uint64_t* buffer = instance->vm().wasmContext.scratchBufferForSize(stackmap.size() * valueSize * 8);
    loadValuesIntoBuffer(context, stackmap, buffer, savedFPWidth);

    JSValue thrownValue = JSValue::decode(exception);
    void* payload = nullptr;
    if (JSWebAssemblyException* wasmException = jsDynamicCast<JSWebAssemblyException*>(thrownValue))
        payload = std::bit_cast<void*>(wasmException->payload().span().data());

    context.gpr(GPRInfo::argumentGPR0) = std::bit_cast<uintptr_t>(buffer);
    context.gpr(GPRInfo::argumentGPR1) = exception;
    context.gpr(GPRInfo::argumentGPR2) = std::bit_cast<uintptr_t>(payload);
}

static inline void SYSV_ABI buildEntryBufferForCatchSIMD(Probe::Context& context) { buildEntryBufferForCatch<SavedFPWidth::SaveVectors>(context); }
static inline void SYSV_ABI buildEntryBufferForCatchNoSIMD(Probe::Context& context) { buildEntryBufferForCatch<SavedFPWidth::DontSaveVectors>(context); }


static inline void prepareForTailCall(CCallHelpers& jit, const B3::StackmapGenerationParams& params, const Checked<int32_t>& tailCallStackOffsetFromFP)
{
    Checked<int32_t> frameSize = params.code().frameSize();
    Checked<int32_t> newStackOffset = frameSize + tailCallStackOffsetFromFP;

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

    // We will use sp-based offsets since the frame pointer is already pointing to the previous frame.
    calleeSaves.adjustOffsets(frameSize);
    jit.emitRestore(calleeSaves, MacroAssembler::stackPointerRegister);

    // The return PC was saved on the stack in the tail call patchpoint.
#if CPU(X86_64)
    newStackOffset -= Checked<int32_t>(sizeof(Register));
#elif CPU(ARM) || CPU(ARM64) || CPU(RISCV64)
    jit.loadPtr(CCallHelpers::Address(MacroAssembler::stackPointerRegister, newStackOffset - Checked<int32_t>(sizeof(Register))), MacroAssembler::linkRegister);
#if CPU(ARM64E)
    GPRReg callerSP = jit.scratchRegister();
    jit.addPtr(MacroAssembler::TrustedImm32(frameSize + Checked<int32_t>(sizeof(CallerFrameAndPC))), MacroAssembler::stackPointerRegister, callerSP);
    jit.untagPtr(callerSP, MacroAssembler::linkRegister);
    jit.validateUntaggedPtr(MacroAssembler::linkRegister);
#endif
#else
    UNREACHABLE_FOR_PLATFORM();
#endif

    jit.addPtr(MacroAssembler::TrustedImm32(newStackOffset), MacroAssembler::stackPointerRegister);
}

#endif // ENABLE(WEBASSEMBLY_OMGJIT)
} } // namespace JSC::Wasm

#endif // ENABLE(WEBASSEMBLY_OMGJIT) || ENABLE(WEBASSEMBLY_BBQJIT)