Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qv4bytecodegenerator_p.h
Go to the documentation of this file.
1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
5#ifndef QV4BYTECODEGENERATOR_P_H
6#define QV4BYTECODEGENERATOR_P_H
7
8//
9// W A R N I N G
10// -------------
11//
12// This file is not part of the Qt API. It exists purely as an
13// implementation detail. This header file may change from version to
14// version without notice, or even be removed.
15//
16// We mean it.
17//
18#include <private/qv4instr_moth_p.h>
19#include <private/qv4compileddata_p.h>
20#include <private/qv4compilercontext_p.h>
21#include <private/qqmljssourcelocation_p.h>
22
23#include <memory>
24
26
27namespace QQmlJS {
28class SourceLocation;
29}
30
31namespace QV4 {
32
33namespace Compiler {
34struct Context;
35}
36
37namespace Moth {
38
40public:
41 BytecodeGenerator(int line, DebugInstructionPass debugInstructionPass,
42 bool storeSourceLocation = false)
45 {
46 if (storeSourceLocation)
47 m_sourceLocationTable.reset(new QV4::Compiler::Context::SourceLocationTable {});
48 }
49
50 struct Label {
51 enum Special: int {
53 Dead = -2,
54 };
55
60 Label() = default;
62 : generator(generator),
63 index(generator->labels.size()) {
64 generator->labels.append(Unlinked);
65 generator->labelReachable.append(false);
66 if (mode == LinkNow)
67 link();
68 }
69
70 void link() const {
71 Q_ASSERT(index >= 0);
72 Q_ASSERT(generator->labels[index] == Unlinked);
73 generator->locationSetAfterLabel = false;
75 if (generator->labelReachable[index])
76 generator->reachable = true;
77 else
78 generator->labelReachable[index] = generator->reachable;
79
80 // A label that nothing can reach doesn't need a position. Code following it is only
81 // emitted if another label makes it reachable, and that label gets its own position.
82 generator->labels[index] = generator->labelReachable[index]
83 ? int(generator->instructions.size())
84 : Dead;
85 }
86 bool isValid() const { return generator != nullptr; }
87
89 int index = -1;
90 };
91
92 struct Jump {
93 // instruction is -1 if the jump was not emitted because it is unreachable.
94 Jump(BytecodeGenerator *generator, int instruction)
95 : generator(generator),
96 index(instruction)
97 { Q_ASSERT(generator); }
98
99 ~Jump() {
100 Q_ASSERT(index == -1 || generator->hasError || generator->instructions[index].linkedLabel != -1); // make sure link() got called
101 }
102
103 Jump(Jump &&j) {
104 std::swap(generator, j.generator);
105 std::swap(index, j.index);
106 }
107
109 int index = -1;
110
111 void link() {
112 // Link the jump first, so that the label knows it is reachable.
114 link(l);
115 l.link();
116 }
117 void link(Label l) {
118 Q_ASSERT(l.index >= 0);
119 if (index == -1)
120 return;
121 Q_ASSERT(generator->instructions[index].linkedLabel == -1);
122 generator->instructions[index].linkedLabel = l.index;
123
124 // We only drop code that cannot be reached when we see it. Therefore, the target of a
125 // backward jump has to be reachable already. Code generation has to make sure of
126 // this by entering loops by fall-through.
127 Q_ASSERT(generator->labels[l.index] == Label::Unlinked
128 || generator->labelReachable[l.index]);
129 generator->labelReachable[l.index] = true;
130 }
131
132 private:
133 // make this type move-only:
135 // we never move-assign this type anywhere, so disable it:
136 Jump &operator=(Jump &&) = delete;
137 };
138
139 struct ExceptionHandler : public Label {
140 ExceptionHandler() = default;
142 : Label(generator, LinkLater)
143 {
144 }
146 {
147 Q_ASSERT(!generator || generator->currentExceptionHandler != this);
148 }
153 bool isValid() const { return generator != nullptr; }
154 };
155
157 return Label(this, Label::LinkNow);
158 }
159
161 return Label(this, Label::LinkLater);
162 }
163
167
168 template<typename Data>
169 void addInstruction(const Data &data)
170 {
171 addInstructionHelper(Data::type, Moth::Instr::Factory<Data>::create(data));
172 }
173
178
183
188
194
200
207
214
222
230
236
247
248 void unwindToLabel(int level, const Label &target)
249 {
250 if (level) {
254 } else {
255 jump().link(target);
256 }
257 }
258
259
260
261 void setLocation(const QQmlJS::SourceLocation &loc);
262 void incrementStatement();
263
265 return currentExceptionHandler;
266 }
267
268 int newRegister();
269 int newRegisterArray(int n);
270 int registerCount() const { return regCount; }
271 int currentRegister() const { return currentReg; }
272
273 void finalize(Compiler::Context *context);
274
275 template<typename Data>
276 Jump addJumpInstruction(const Data &data)
277 {
278 return Jump(this, addInstructionHelper(Data::type, Moth::Instr::Factory<Data>::create(data),
279 offsetof(Data, offset)));
280 }
281
282 void addCJumpInstruction(bool jumpOnFalse, const Label *trueLabel, const Label *falseLabel)
283 {
284 if (jumpOnFalse)
285 addJumpInstruction(Instruction::JumpFalse()).link(*falseLabel);
286 else
287 addJumpInstruction(Instruction::JumpTrue()).link(*trueLabel);
288 }
289
291 {
292 lastInstrType = -1;
293 }
294
295 void addLoopStart(const Label &start)
296 {
297 _labelInfos.push_back({ start.index });
298 }
299
300 void setError(bool b) { hasError = b; }
301
302private:
303 friend struct Jump;
304 friend struct Label;
305 friend struct ExceptionHandler;
306 friend class DebugInstructions;
307
308 int addInstructionHelper(Moth::Instr::Type type, const Instr &i, int offsetOfOffset = -1);
309
310 struct I {
311 Moth::Instr::Type type;
312 short size;
313 uint position;
314 int line;
315 int statement;
316 int offsetForJump;
317 int linkedLabel;
318 // Whether code generation set a location between the last label and this instruction.
319 bool locationSetAfterLabel;
320 unsigned char packed[sizeof(Instr) + 2]; // 2 for instruction type
321 };
322
323 static bool endsFlow(Moth::Instr::Type type)
324 {
325 switch (type) {
326 case Instr::Type::Ret:
327 case Instr::Type::Jump:
328 case Instr::Type::UnwindToLabel:
329 case Instr::Type::ThrowException:
330 return true;
331 default:
332 return false;
333 }
334 }
335
336 static I makeInstruction(Moth::Instr::Type type, const Instr &i, int offsetOfOffset, int line,
337 int statement)
338 {
339 const int argCount = Moth::InstrInfo::argumentCount[static_cast<int>(type)];
340 int s = argCount * sizeof(int);
341 if (offsetOfOffset != -1)
342 offsetOfOffset += Instr::encodedLength(type);
343 I instr{ type, static_cast<short>(s + Instr::encodedLength(type)),
344 0, line,
345 statement, offsetOfOffset,
346 -1, false,
347 "\0\0" };
348 uchar *code = instr.packed;
349 code = Instr::pack(code, Instr::wideInstructionType(type));
350
351 for (int j = 0; j < argCount; ++j) {
352 qToLittleEndian<qint32>(i[j], code);
353 code += sizeof(int);
354 }
355 return instr;
356 }
357
358 void compressInstructions();
359 void packInstruction(I &i);
360 void adjustJumpOffsets();
361 bool isLabelValid(int position) const { return labels.at(position) >= 0; }
362
363 QList<I> instructions;
364 QList<int> labels;
365
366 // Whether a label can be reached. Before it is linked, whether a reachable jump targets it.
367 QList<bool> labelReachable;
368 ExceptionHandler *currentExceptionHandler = nullptr;
369 DebugInstructionPass debugInstructionPass = nullptr;
370 int regCount = 0;
371public:
372 int currentReg = 0;
373private:
374 int startLine = 0;
375 int currentLine = 0;
376 QQmlJS::SourceLocation currentSourceLocation;
377 bool locationSetAfterLabel = true;
378 std::unique_ptr<QV4::Compiler::Context::SourceLocationTable> m_sourceLocationTable;
379 int currentStatement = 0;
380 bool hasError = false;
381
382 // Whether control flow can reach the next instruction. Unreachable instructions are dropped.
383 bool reachable = true;
384
385 int lastInstrType = -1;
386 Moth::Instr lastInstr;
387
388 struct LabelInfo {
389 int labelIndex;
390 };
391 std::vector<LabelInfo> _labelInfos;
392};
393
394}
395}
396
397QT_END_NAMESPACE
398
399#endif
void addInstruction(const Data &data)
BytecodeGenerator(int line, DebugInstructionPass debugInstructionPass, bool storeSourceLocation=false)
ExceptionHandler * exceptionHandler() const
void addLoopStart(const Label &start)
void addCJumpInstruction(bool jumpOnFalse, const Label *trueLabel, const Label *falseLabel)
void finalize(Compiler::Context *context)
Jump addJumpInstruction(const Data &data)
Combined button and popup list for selecting options.
Definition qjsvalue.h:24
QList< Method > staticMethods
KeyValuePair(quint32 key, quint32 value)
QQmlJS::AST::FunctionExpression * function
bool requiresTDZCheck(const QQmlJS::SourceLocation &accessLocation, bool accessAcrossContextBoundaries) const
QQmlJS::SourceLocation declarationLocation
QQmlJS::AST::VariableScope scope
QList< Context * > nestedContexts
bool memberInfo(const QString &name, const Member **m) const
void emitBlockFooter(Compiler::Codegen *codegen)
QQmlJS::AST::FormalParameterList * formals
bool hasArgument(const QString &name) const
void emitBlockHeader(Compiler::Codegen *codegen)
QQmlJS::AST::BoundNames arguments
std::unique_ptr< SourceLocationTable > sourceLocationTable
UsesArgumentsObject usesArgumentsObject
QList< CompiledData::CodeOffsetToLineAndStatement > lineAndStatementNumberMapping
QList< ImportEntry > importEntries
QMap< QString, Member > MemberMap
QQmlJS::AST::Type * returnType
Context(Context *parent, ContextType type)
ResolvedName resolveName(const QString &name, const QQmlJS::SourceLocation &accessLocation)
void setupFunctionIndices(Moth::BytecodeGenerator *bytecodeGenerator)
QQmlJS::SourceLocation lastBlockInitializerLocation
void addUsedVariable(const QString &name)
void promoteFormalParameterForTDZ(const QString &name, const QQmlJS::SourceLocation &loc)
QList< ExportEntry > exportEntries
std::vector< unsigned > labelInfo
Member findMember(const QString &name) const
bool addLocalVar(const QString &name, MemberType contextType, QQmlJS::AST::VariableScope scope, QQmlJS::AST::FunctionExpression *function=nullptr, const QQmlJS::SourceLocation &declarationLocation=QQmlJS::SourceLocation(), bool isInjected=false)
int findArgument(const QString &name, bool *isInjected) const
CompiledData::Location location
static bool lessThan(const ExportEntry &lhs, const ExportEntry &rhs)
CompiledData::Location location
Context * newContext(QQmlJS::AST::Node *node, Context *parent, ContextType compilationMode)
QHash< QQmlJS::AST::Node *, Context * > contextMap
QList< ExportEntry > indirectExportEntries
QList< Context * > functions
Module(const QString &fileName, const QString &finalUrl, Moth::DebugInstructionPass debugInstructionPass)
QList< ExportEntry > starExportEntries
QList< TemplateObject > templateObjects
Moth::DebugInstructionPass debugInstructionPass
QList< ImportEntry > importEntries
QList< ExportEntry > localExportEntries
bool operator==(const TemplateObject &other)
ExceptionHandler & operator=(ExceptionHandler &&)=default
ExceptionHandler & operator=(const ExceptionHandler &)=default
ExceptionHandler(ExceptionHandler &&)=default
ExceptionHandler(const ExceptionHandler &)=default
Jump(BytecodeGenerator *generator, int instruction)
Label(BytecodeGenerator *generator, LinkMode mode=LinkNow)