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
qqmljsbasicblocks.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3// Qt-Security score:significant
4
6
7#include <private/qqmlglobal_p.h>
8#include <private/qqmljsutils_p.h>
9#include <private/qv4instr_moth_p.h>
10
12
13using namespace Qt::Literals::StringLiterals;
14
15DEFINE_BOOL_CONFIG_OPTION(qv4DumpBasicBlocks, QV4_DUMP_BASIC_BLOCKS)
16DEFINE_BOOL_CONFIG_OPTION(qv4ValidateBasicBlocks, QV4_VALIDATE_BASIC_BLOCKS)
17
18void QQmlJSBasicBlocks::dumpBasicBlocks()
19{
20 qDebug().noquote() << "=== Basic Blocks for \"%1\""_L1.arg(m_context->name);
21 for (const auto &[blockOffset, block] : m_basicBlocks) {
22 QDebug debug = qDebug().nospace();
23 debug << "Block " << (blockOffset < 0 ? "Function prolog"_L1 : QString::number(blockOffset))
24 << ":\n";
25 debug << " jumpOrigins[" << block.jumpOrigins.size() << "]: ";
26 for (auto origin : std::as_const(block.jumpOrigins)) {
27 debug << origin << ", ";
28 }
29 debug << "\n readRegisters[" << block.readRegisters.size() << "]: ";
30 for (auto reg : std::as_const(block.readRegisters)) {
31 debug << reg << ", ";
32 }
33 debug << "\n jumpTarget: " << block.jumpTarget;
34 debug << "\n jumpIsUnConditional: " << block.jumpIsUnconditional;
35 debug << "\n isReturnBlock: " << block.isReturnBlock;
36 debug << "\n isThrowBlock: " << block.isThrowBlock;
37 }
38 qDebug() << "\n";
39}
40
41void QQmlJSBasicBlocks::dumpDOTGraph()
42{
43 QString output;
44 QTextStream s{ &output };
45 s << "=== Basic Blocks Graph in DOT format for \"%1\" (spaces are encoded as"
46 " &#160; to preserve formatting)\n"_L1.arg(m_context->name);
47 s << "digraph BasicBlocks {\n"_L1;
48
49 QFlatMap<int, BasicBlock> blocks{ m_basicBlocks };
50 for (const auto &[blockOffset, block] : blocks) {
51 for (int originOffset : std::as_const(block.jumpOrigins)) {
52 const auto originBlockIt = basicBlockForInstruction(blocks, originOffset);
53 const auto isBackEdge = originOffset > blockOffset && originBlockIt->second.jumpIsUnconditional;
54 s << " %1 -> %2%3\n"_L1.arg(QString::number(originBlockIt.key()),
55 QString::number(blockOffset),
56 isBackEdge ? " [color=blue]"_L1 : ""_L1);
57 }
58 }
59
60 for (const auto &[blockOffset, block] : blocks) {
61 if (blockOffset < 0) {
62 s << " %1 [shape=record, fontname=\"Monospace\", label=\"Function Prolog\"]\n"_L1
63 .arg(QString::number(blockOffset));
64 continue;
65 }
66
67 auto nextBlockIt = blocks.lower_bound(blockOffset + 1);
68 int nextBlockOffset = nextBlockIt == blocks.end() ? m_context->code.size() : nextBlockIt->first;
69 QString dump = QV4::Moth::dumpBytecode(
70 m_context->code.constData(), m_context->code.size(), m_context->locals.size(),
71 m_context->formals->length(), blockOffset, nextBlockOffset - 1,
72 m_context->lineAndStatementNumberMapping);
73 dump = dump.replace(" "_L1, "&#160;"_L1); // prevent collapse of extra whitespace for formatting
74 dump = dump.replace("\n"_L1, "\\l"_L1); // new line + left aligned
75 dump = dump.replace("<"_L1, "\<"_L1).replace(">"_L1, "\>"_L1); // escape < and > for "SetUnwindHandler <null>" instruction
76 s << " %1 [shape=record, fontname=\"Monospace\", label=\"{Block %1: | %2}\"]\n"_L1
77 .arg(QString::number(blockOffset), dump);
78 }
79 s << "}\n"_L1;
80
81 // Have unique names to prevent overwriting of functions with the same name (eg. anonymous functions).
82 static int functionCount = 0;
83 static const auto dumpFolderPath = qEnvironmentVariable("QV4_DUMP_BASIC_BLOCKS");
84
85 QString expressionName = m_context->name == ""_L1
86 ? "anonymous"_L1
87 : QString(m_context->name).replace(" "_L1, "_"_L1);
88 QString fileName = "function"_L1 + QString::number(functionCount++) + "_"_L1 + expressionName + ".gv"_L1;
89 QFile dumpFile(dumpFolderPath + (dumpFolderPath.endsWith("/"_L1) ? ""_L1 : "/"_L1) + fileName);
90
91 if (dumpFolderPath == "-"_L1 || dumpFolderPath == "1"_L1 || dumpFolderPath == "true"_L1) {
92 qDebug().noquote() << output;
93 } else {
94 if (!dumpFile.open(QIODeviceBase::Truncate | QIODevice::WriteOnly)) {
95 qDebug() << "Error: Could not open file to dump the basic blocks into";
96 } else {
97 dumpFile.write(("//"_L1 + output).toLatin1().toStdString().c_str());
98 dumpFile.close();
99 }
100 }
101}
102
103QQmlJSCompilePass::BlocksAndAnnotations
104QQmlJSBasicBlocks::run(const Function *function, QQmlJSAotCompiler::Flags compileFlags,
105 bool &basicBlocksValidationFailed)
106{
107 basicBlocksValidationFailed = false;
108
109 m_function = function;
110
111 for (int i = 0, end = function->argumentTypes.size(); i != end; ++i) {
112 InstructionAnnotation annotation;
113 annotation.changedRegisterIndex = FirstArgument + i;
114 annotation.changedRegister = function->argumentTypes[i];
115 m_annotations[-annotation.changedRegisterIndex] = annotation;
116 }
117
118 for (int i = 0, end = function->registerTypes.size(); i != end; ++i) {
119 InstructionAnnotation annotation;
120 annotation.changedRegisterIndex = firstRegisterIndex() + i;
121 annotation.changedRegister = function->registerTypes[i];
122 m_annotations[-annotation.changedRegisterIndex] = annotation;
123 }
124
125 // Insert the function prolog block followed by the first "real" block.
126 m_basicBlocks.insert_or_assign(m_annotations.begin().key(), BasicBlock());
127 BasicBlock zeroBlock;
128 zeroBlock.jumpOrigins.append(m_basicBlocks.begin().key());
129 m_basicBlocks.insert(0, zeroBlock);
130
131 const QByteArray &byteCode = function->code;
132 decode(byteCode.constData(), static_cast<uint>(byteCode.size()));
133 if (m_hadBackJumps) {
134 // We may have missed some connections between basic blocks if there were back jumps.
135 // Fill them in via a second pass.
136
137 // We also need to re-calculate the jump targets then because the basic block boundaries
138 // may have shifted.
139 for (auto it = m_basicBlocks.begin(), end = m_basicBlocks.end(); it != end; ++it) {
140 it->second.jumpTarget = -1;
141 it->second.jumpIsUnconditional = false;
142 }
143
144 reset();
145 decode(byteCode.constData(), static_cast<uint>(byteCode.size()));
146 for (auto it = m_basicBlocks.begin(), end = m_basicBlocks.end(); it != end; ++it)
147 QQmlJSUtils::deduplicate(it->second.jumpOrigins);
148 }
149
150 if (compileFlags.testFlag(QQmlJSAotCompiler::ValidateBasicBlocks) || qv4ValidateBasicBlocks()) {
151 if (auto validationResult = basicBlocksValidation(); !validationResult.success) {
152 qDebug() << "Basic blocks validation failed: %1."_L1.arg(validationResult.errorMessage);
153 basicBlocksValidationFailed = true;
154 }
155 }
156
157 if (qv4DumpBasicBlocks()) {
158 dumpBasicBlocks();
159 dumpDOTGraph();
160 }
161
162 return { std::move(m_basicBlocks), std::move(m_annotations) };
163}
164
165QV4::Moth::ByteCodeHandler::Verdict QQmlJSBasicBlocks::startInstruction(QV4::Moth::Instr::Type)
166{
167 return ProcessInstruction;
168}
169
170void QQmlJSBasicBlocks::endInstruction(QV4::Moth::Instr::Type type)
171{
172 if (!instructionFallsThrough(type))
173 return;
174 auto it = m_basicBlocks.find(nextInstructionOffset());
175 if (it != m_basicBlocks.end())
176 it->second.jumpOrigins.append(currentInstructionOffset());
177}
178
179void QQmlJSBasicBlocks::generate_Jump(int offset)
180{
181 processJump(offset, Unconditional);
182}
183
184void QQmlJSBasicBlocks::generate_JumpTrue(int offset)
185{
186 processJump(offset, Conditional);
187}
188
189void QQmlJSBasicBlocks::generate_JumpFalse(int offset)
190{
191 processJump(offset, Conditional);
192}
193
194void QQmlJSBasicBlocks::generate_JumpNoException(int offset)
195{
196 processJump(offset, Conditional);
197}
198
199void QQmlJSBasicBlocks::generate_JumpNotUndefined(int offset)
200{
201 processJump(offset, Conditional);
202}
203
204void QQmlJSBasicBlocks::generate_IteratorNext(int value, int offset)
205{
206 Q_UNUSED(value);
207 processJump(offset, Conditional);
208}
209
210void QQmlJSBasicBlocks::generate_GetOptionalLookup(int index, int offset)
211{
212 Q_UNUSED(index);
213 processJump(offset, Conditional);
214}
215
216void QQmlJSBasicBlocks::generate_SetUnwindHandler(int offset)
217{
218 // An exception handler may only be reachable from where it is installed.
219 // Offset 0 means "no handler", or the handler is the next instruction anyway.
220 if (offset != 0)
221 processJump(offset, Conditional);
222}
223
224void QQmlJSBasicBlocks::generate_Ret()
225{
226 auto currentBlock = basicBlockForInstruction(m_basicBlocks, currentInstructionOffset());
227 currentBlock.value().isReturnBlock = true;
228}
229
230void QQmlJSBasicBlocks::generate_ThrowException()
231{
232 auto currentBlock = basicBlockForInstruction(m_basicBlocks, currentInstructionOffset());
233 currentBlock.value().isThrowBlock = true;
234}
235
236void QQmlJSBasicBlocks::generate_DefineArray(int argc, int argv)
237{
238 if (argc == 0)
239 return; // empty array/list, nothing to do
240
241 m_objectAndArrayDefinitions.append({
242 currentInstructionOffset(), ObjectOrArrayDefinition::ArrayClassId, argc, argv
243 });
244}
245
246void QQmlJSBasicBlocks::generate_DefineObjectLiteral(int internalClassId, int argc, int argv)
247{
248 if (argc == 0)
249 return;
250
251 m_objectAndArrayDefinitions.append({ currentInstructionOffset(), internalClassId, argc, argv });
252}
253
254void QQmlJSBasicBlocks::generate_Construct(int func, int argc, int argv)
255{
256 Q_UNUSED(func)
257 if (argc == 0)
258 return; // empty array/list, nothing to do
259
260 m_objectAndArrayDefinitions.append({
261 currentInstructionOffset(),
262 argc == 1
263 ? ObjectOrArrayDefinition::ArrayConstruct1ArgId
264 : ObjectOrArrayDefinition::ArrayClassId,
265 argc,
266 argv
267 });
268}
269
270void QQmlJSBasicBlocks::processJump(int offset, JumpMode mode)
271{
272 if (offset < 0)
273 m_hadBackJumps = true;
274 const int jumpTarget = absoluteOffset(offset);
275 Q_ASSERT(!m_basicBlocks.isEmpty());
276 auto currentBlock = basicBlockForInstruction(m_basicBlocks, currentInstructionOffset());
277 currentBlock->second.jumpTarget = jumpTarget;
278 currentBlock->second.jumpIsUnconditional = (mode == Unconditional);
279 m_basicBlocks[jumpTarget].jumpOrigins.append(currentInstructionOffset());
280 if (mode == Conditional)
281 m_basicBlocks.insert(nextInstructionOffset(), BasicBlock());
282}
283
284QQmlJSBasicBlocks::BasicBlocksValidationResult QQmlJSBasicBlocks::basicBlocksValidation()
285{
286 if (m_basicBlocks.empty())
287 return {};
288
289 const QFlatMap<int, BasicBlock> blocks{ m_basicBlocks };
290 QList<QFlatMap<int, BasicBlock>::const_iterator> returnOrThrowBlocks;
291 for (auto it = blocks.cbegin(); it != blocks.cend(); ++it) {
292 if (it.value().isReturnBlock || it.value().isThrowBlock)
293 returnOrThrowBlocks.append(it);
294 }
295
296 // 1. Return blocks and throw blocks must not have a jump target
297 for (const auto &it : returnOrThrowBlocks) {
298 if (it.value().jumpTarget != -1)
299 return { false, "Return or throw block jumps to somewhere"_L1 };
300 }
301
302 // 2. Every basic block must be reachable from the entry block.
303 // The recorded jump origins (which include fall-through edges) describe the reverse
304 // edges of the control flow graph, so we invert them to obtain the forward edges and
305 // then traverse forward from the entry block. Traversing backward from the return and
306 // throw blocks instead would wrongly flag infinite loops, whose blocks have no path to
307 // any terminal block but are nonetheless legitimately reachable.
308 QMultiHash<int, int> forwardEdges;
309 for (auto it = blocks.cbegin(), end = blocks.cend(); it != end; ++it) {
310 for (int originOffset : it.value().jumpOrigins)
311 forwardEdges.insert(constBasicBlockForInstruction(blocks, originOffset).key(), it.key());
312 }
313
314 QSet<int> visitedBlockOffsets;
315 QList<int> toVisit{ blocks.cbegin().key() };
316 while (!toVisit.empty()) {
317 const int offset = toVisit.takeLast();
318 if (visitedBlockOffsets.contains(offset))
319 continue;
320 visitedBlockOffsets.insert(offset);
321 for (auto [it, end] = forwardEdges.equal_range(offset); it != end; ++it) {
322 if (!visitedBlockOffsets.contains(*it))
323 toVisit.append(*it);
324 }
325 }
326
327 if (visitedBlockOffsets.size() != blocks.size())
328 return { false, "Basic blocks graph is not fully connected"_L1 };
329
330 // 3. A block's jump target must be the first offset of a block.
331 for (const auto &[blockOffset, block] : blocks) {
332 auto target = block.jumpTarget;
333 if (target != -1 && blocks.find(target) == blocks.end())
334 return { false, "Invalid jump; target is not the start of a block"_L1 };
335 }
336
337 return {};
338}
339
340QT_END_NAMESPACE
Combined button and popup list for selecting options.