aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/jit/qv4assemblercommon.cpp
blob: 831496a628b7e817fbdd1622932f37505c96b0c5 (plain)
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QBuffer>
#include <QFile>

#include "qv4engine_p.h"
#include "qv4assemblercommon_p.h"
#include <private/qv4function_p.h>
#include <private/qv4runtime_p.h>

#include <assembler/MacroAssemblerCodeRef.h>
#include <assembler/LinkBuffer.h>
#include <WTFStubs.h>

#undef ENABLE_ALL_ASSEMBLERS_FOR_REFACTORING_PURPOSES

#ifdef V4_ENABLE_JIT

QT_BEGIN_NAMESPACE
namespace QV4 {
namespace JIT {

namespace {
class QIODevicePrintStream: public FilePrintStream
{
    Q_DISABLE_COPY(QIODevicePrintStream)

public:
    explicit QIODevicePrintStream(QIODevice *dest)
        : FilePrintStream(nullptr)
        , dest(dest)
        , buf(4096, '0')
    {
        Q_ASSERT(dest);
    }

    ~QIODevicePrintStream()
    {}

    void vprintf(const char* format, va_list argList) WTF_ATTRIBUTE_PRINTF(2, 0)
    {
        const int written = qvsnprintf(buf.data(), buf.size(), format, argList);
        if (written > 0)
            dest->write(buf.constData(), written);
        memset(buf.data(), 0, qMin(written, buf.size()));
    }

    void flush()
    {}

private:
    QIODevice *dest;
    QByteArray buf;
};
} // anonymous namespace

static void printDisassembledOutputWithCalls(QByteArray processedOutput,
                                             const QHash<const void*, const char*>& functions)
{
    for (QHash<const void*, const char*>::ConstIterator it = functions.begin(), end = functions.end();
         it != end; ++it) {
        const QByteArray ptrString = "0x" + QByteArray::number(quintptr(it.key()), 16);
        int idx = 0;
        while (idx >= 0) {
            idx = processedOutput.indexOf(ptrString, idx);
            if (idx < 0)
                break;
            idx = processedOutput.indexOf('\n', idx);
            if (idx < 0)
                break;
            processedOutput = processedOutput.insert(idx, QByteArrayLiteral("                          ; ") + it.value());
        }
    }

    qDebug("%s", processedOutput.constData());
}

static QByteArray functionName(Function *function)
{
    QByteArray name = function->name()->toQString().toUtf8();
    if (name.isEmpty()) {
        name = QByteArray::number(reinterpret_cast<quintptr>(function), 16);
        name.prepend("QV4::Function(0x");
        name.append(')');
    }
    return name;
}

JIT::PlatformAssemblerCommon::~PlatformAssemblerCommon()
{}

void PlatformAssemblerCommon::link(Function *function, const char *jitKind)
{
    for (const auto &jumpTarget : jumpsToLink)
        jumpTarget.jump.linkTo(labelForOffset[jumpTarget.offset], this);

    JSC::JSGlobalData dummy(function->internalClass->engine->executableAllocator);
    JSC::LinkBuffer<MacroAssembler> linkBuffer(dummy, this, nullptr);

    for (const auto &ehTarget : ehTargets) {
        auto targetLabel = labelForOffset.value(ehTarget.offset);
        linkBuffer.patch(ehTarget.label, linkBuffer.locationOf(targetLabel));
    }

    JSC::MacroAssemblerCodeRef codeRef;

    static const bool showCode = qEnvironmentVariableIsSet("QV4_SHOW_ASM");
    if (showCode) {
        QBuffer buf;
        buf.open(QIODevice::WriteOnly);
        WTF::setDataFile(new QIODevicePrintStream(&buf));

        QByteArray name = functionName(function);
        codeRef = linkBuffer.finalizeCodeWithDisassembly(jitKind, "function %s", name.constData());

        WTF::setDataFile(stderr);
        printDisassembledOutputWithCalls(buf.data(), functions);
    } else {
        codeRef = linkBuffer.finalizeCodeWithoutDisassembly();
    }

    function->codeRef = new JSC::MacroAssemblerCodeRef(codeRef);
    function->jittedCode = reinterpret_cast<Function::JittedCode>(function->codeRef->code().executableAddress());

    // This implements writing of JIT'd addresses so that perf can find the
    // symbol names.
    //
    // Perf expects the mapping to be in a certain place and have certain
    // content, for more information, see:
    // https://github.com/torvalds/linux/blob/master/tools/perf/Documentation/jit-interface.txt
    static bool doProfile = !qEnvironmentVariableIsEmpty("QV4_PROFILE_WRITE_PERF_MAP");
    if (Q_UNLIKELY(doProfile)) {
        static QFile perfMapFile(QString::fromLatin1("/tmp/perf-%1.map")
                                 .arg(QCoreApplication::applicationPid()));
        static const bool isOpen = perfMapFile.open(QIODevice::WriteOnly);
        if (!isOpen) {
            qWarning("QV4::JIT::Assembler: Cannot write perf map file.");
            doProfile = false;
        } else {
            perfMapFile.write(QByteArray::number(reinterpret_cast<quintptr>(
                                                     codeRef.code().executableAddress()), 16));
            perfMapFile.putChar(' ');
            perfMapFile.write(QByteArray::number(static_cast<qsizetype>(codeRef.size()), 16));
            perfMapFile.putChar(' ');
            perfMapFile.write(functionName(function));
            perfMapFile.putChar('\n');
            perfMapFile.flush();
        }
    }
}

void PlatformAssemblerCommon::prepareCallWithArgCount(int argc)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(remainingArgcForCall == NoCall);
    remainingArgcForCall = argc;
#endif

    if (argc > ArgInRegCount) {
        argcOnStackForCall = int(WTF::roundUpToMultipleOf(16, size_t(argc - ArgInRegCount) * PointerSize));
        subPtr(TrustedImm32(argcOnStackForCall), StackPointerRegister);
    }
}

void PlatformAssemblerCommon::storeInstructionPointer(int instructionOffset)
{
    Address addr(CppStackFrameRegister, offsetof(QV4::CppStackFrame, instructionPointer));
    store32(TrustedImm32(instructionOffset), addr);
}

PlatformAssemblerCommon::Address PlatformAssemblerCommon::argStackAddress(int arg)
{
    int offset = arg - ArgInRegCount;
    Q_ASSERT(offset >= 0);
    return Address(StackPointerRegister, offset * PointerSize);
}

void PlatformAssemblerCommon::passAccumulatorAsArg(int arg)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(arg < remainingArgcForCall);
    --remainingArgcForCall;
#endif

    passAccumulatorAsArg_internal(arg, false);
}

void JIT::PlatformAssemblerCommon::pushAccumulatorAsArg(int arg)
{
    passAccumulatorAsArg_internal(arg, true);
}

void PlatformAssemblerCommon::passAccumulatorAsArg_internal(int arg, bool doPush)
{
    if (arg < ArgInRegCount) {
        addPtr(TrustedImm32(offsetof(CallData, accumulator)), JSStackFrameRegister, registerForArg(arg));
    } else {
        addPtr(TrustedImm32(offsetof(CallData, accumulator)), JSStackFrameRegister, ScratchRegister);
        if (doPush)
            push(ScratchRegister);
        else
            storePtr(ScratchRegister, argStackAddress(arg));
    }
}

void PlatformAssemblerCommon::passFunctionAsArg(int arg)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(arg < remainingArgcForCall);
    --remainingArgcForCall;
#endif

    if (arg < ArgInRegCount) {
        loadFunctionPtr(registerForArg(arg));
    } else {
        loadFunctionPtr(ScratchRegister);
        storePtr(ScratchRegister, argStackAddress(arg));
    }
}

void PlatformAssemblerCommon::passEngineAsArg(int arg)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(arg < remainingArgcForCall);
    --remainingArgcForCall;
#endif

    if (arg < ArgInRegCount) {
        move(EngineRegister, registerForArg(arg));
    } else {
        storePtr(EngineRegister, argStackAddress(arg));
    }
}

void PlatformAssemblerCommon::passJSSlotAsArg(int reg, int arg)
{
    Address addr(JSStackFrameRegister, reg * int(sizeof(QV4::Value)));
    passAddressAsArg(addr, arg);
}

void JIT::PlatformAssemblerCommon::passAddressAsArg(Address addr, int arg)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(arg < remainingArgcForCall);
    --remainingArgcForCall;
#endif

    if (arg < ArgInRegCount) {
        addPtr(TrustedImm32(addr.offset), addr.base, registerForArg(arg));
    } else {
        addPtr(TrustedImm32(addr.offset), addr.base, ScratchRegister);
        storePtr(ScratchRegister, argStackAddress(arg));
    }
}

void PlatformAssemblerCommon::passCppFrameAsArg(int arg)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(arg < remainingArgcForCall);
    --remainingArgcForCall;
#endif

    if (arg < ArgInRegCount)
        move(CppStackFrameRegister, registerForArg(arg));
    else
        store32(CppStackFrameRegister, argStackAddress(arg));
}

void PlatformAssemblerCommon::passInt32AsArg(int value, int arg)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(arg < remainingArgcForCall);
    --remainingArgcForCall;
#endif

    if (arg < ArgInRegCount)
        move(TrustedImm32(value), registerForArg(arg));
    else
        store32(TrustedImm32(value), argStackAddress(arg));
}

void PlatformAssemblerCommon::callRuntime(const char *functionName, const void *funcPtr)
{
#ifndef QT_NO_DEBUG
    Q_ASSERT(remainingArgcForCall == 0);
    remainingArgcForCall = NoCall;
#endif
    callRuntimeUnchecked(functionName, funcPtr);
    if (argcOnStackForCall > 0) {
        addPtr(TrustedImm32(argcOnStackForCall), StackPointerRegister);
        argcOnStackForCall = 0;
    }
}

void PlatformAssemblerCommon::callRuntimeUnchecked(const char *functionName, const void *funcPtr)
{
    functions.insert(funcPtr, functionName);
    callAbsolute(funcPtr);
}

void PlatformAssemblerCommon::tailCallRuntime(const char *functionName, const void *funcPtr)
{
    functions.insert(funcPtr, functionName);
    setTailCallArg(EngineRegister, 1);
    setTailCallArg(CppStackFrameRegister, 0);
    freeStackSpace();
    generatePlatformFunctionExit(/*tailCall =*/ true);
    jumpAbsolute(funcPtr);
}

void PlatformAssemblerCommon::setTailCallArg(RegisterID src, int arg)
{
    if (arg < ArgInRegCount) {
        move(src, registerForArg(arg));
    } else {
        // We never write to the incoming arguments space on the stack, and the tail call runtime
        // method has the same signature as the jitted function, so it is safe for us to just reuse
        // the arguments that we got in.
    }
}

JSC::MacroAssemblerBase::Address PlatformAssemblerCommon::jsAlloca(int slotCount)
{
    Address jsStackTopAddr(EngineRegister, offsetof(EngineBase, jsStackTop));
    RegisterID jsStackTop = AccumulatorRegisterValue;
    loadPtr(jsStackTopAddr, jsStackTop);
    addPtr(TrustedImm32(sizeof(Value) * slotCount), jsStackTop);
    storePtr(jsStackTop, jsStackTopAddr);
    return Address(jsStackTop, 0);
}

void PlatformAssemblerCommon::storeInt32AsValue(int srcInt, Address destAddr)
{
    store32(TrustedImm32(srcInt),
            Address(destAddr.base, destAddr.offset + QV4::Value::valueOffset()));
    store32(TrustedImm32(int(QV4::Value::ValueTypeInternal::Integer)),
            Address(destAddr.base, destAddr.offset + QV4::Value::tagOffset()));
}

} // JIT namespace
} // QV4 namepsace

QT_END_NAMESPACE

#endif // V4_ENABLE_JIT