2 * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4 * Copyright (C) 2012 Igalia, S.L.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of Apple Inc. ("Apple") nor the names of
16 * its contributors may be used to endorse or promote products derived
17 * from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "CodeBlock.h"
34 #include "Instruction.h"
35 #include "Interpreter.h"
36 #include "JSGeneratorFunction.h"
38 #include "LabelScope.h"
40 #include "ParserError.h"
41 #include "RegisterID.h"
42 #include "StaticPropertyAnalyzer.h"
43 #include "SymbolTable.h"
44 #include "TemplateRegistryKey.h"
45 #include "UnlinkedCodeBlock.h"
47 #include <wtf/CheckedArithmetic.h>
48 #include <wtf/HashTraits.h>
49 #include <wtf/SegmentedVector.h>
50 #include <wtf/SetForScope.h>
51 #include <wtf/Vector.h>
56 class JSTemplateRegistryKey;
58 enum ExpectedFunction {
60 ExpectObjectConstructor,
61 ExpectArrayConstructor
64 enum class DebuggableCall { Yes, No };
65 enum class ThisResolutionType { Local, Scoped };
69 CallArguments(BytecodeGenerator&, ArgumentsNode*, unsigned additionalArguments = 0);
71 RegisterID* thisRegister() { return m_argv[0].get(); }
72 RegisterID* argumentRegister(unsigned i) { return m_argv[i + 1].get(); }
73 unsigned stackOffset() { return -m_argv[0]->index() + CallFrame::headerSizeInRegisters; }
74 unsigned argumentCountIncludingThis() { return m_argv.size() - m_padding; }
75 ArgumentsNode* argumentsNode() { return m_argumentsNode; }
78 ArgumentsNode* m_argumentsNode;
79 Vector<RefPtr<RegisterID>, 8, UnsafeVectorOverflow> m_argv;
83 // https://tc39.github.io/ecma262/#sec-completion-record-specification-type
85 // For the Break and Continue cases, instead of using the Break and Continue enum values
86 // below, we use the unique jumpID of the break and continue statement as the encoding
87 // for the CompletionType value. emitFinallyCompletion() uses this jumpID value later
88 // to determine the appropriate jump target to jump to after executing the relevant finally
89 // blocks. The jumpID is computed as:
90 // jumpID = bytecodeOffset (of the break/continue node) + CompletionType::NumberOfTypes.
91 // Hence, there won't be any collision between jumpIDs and CompletionType enums.
92 enum class CompletionType : int {
102 inline CompletionType bytecodeOffsetToJumpID(unsigned offset)
104 int jumpIDAsInt = offset + static_cast<int>(CompletionType::NumberOfTypes);
105 ASSERT(jumpIDAsInt >= static_cast<int>(CompletionType::NumberOfTypes));
106 return static_cast<CompletionType>(jumpIDAsInt);
110 FinallyJump(CompletionType jumpID, int targetLexicalScopeIndex, Label& targetLabel)
112 , targetLexicalScopeIndex(targetLexicalScopeIndex)
113 , targetLabel(targetLabel)
116 CompletionType jumpID;
117 int targetLexicalScopeIndex;
118 Ref<Label> targetLabel;
121 struct FinallyContext {
123 FinallyContext(FinallyContext* outerContext, Label& finallyLabel)
124 : m_outerContext(outerContext)
125 , m_finallyLabel(&finallyLabel)
127 ASSERT(m_jumps.isEmpty());
130 FinallyContext* outerContext() const { return m_outerContext; }
131 Label* finallyLabel() const { return m_finallyLabel; }
133 uint32_t numberOfBreaksOrContinues() const { return m_numberOfBreaksOrContinues.unsafeGet(); }
134 void incNumberOfBreaksOrContinues() { m_numberOfBreaksOrContinues++; }
136 bool handlesReturns() const { return m_handlesReturns; }
137 void setHandlesReturns() { m_handlesReturns = true; }
139 void registerJump(CompletionType jumpID, int lexicalScopeIndex, Label& targetLabel)
141 m_jumps.append(FinallyJump(jumpID, lexicalScopeIndex, targetLabel));
144 size_t numberOfJumps() const { return m_jumps.size(); }
145 FinallyJump& jumps(size_t i) { return m_jumps[i]; }
148 FinallyContext* m_outerContext { nullptr };
149 Label* m_finallyLabel { nullptr };
150 Checked<uint32_t, WTF::CrashOnOverflow> m_numberOfBreaksOrContinues;
151 bool m_handlesReturns { false };
152 Vector<FinallyJump> m_jumps;
155 struct ControlFlowScope {
156 typedef uint8_t Type;
161 ControlFlowScope(Type type, int lexicalScopeIndex, FinallyContext&& finallyContext = FinallyContext())
163 , lexicalScopeIndex(lexicalScopeIndex)
164 , finallyContext(std::forward<FinallyContext>(finallyContext))
167 bool isLabelScope() const { return type == Label; }
168 bool isFinallyScope() const { return type == Finally; }
171 int lexicalScopeIndex;
172 FinallyContext finallyContext;
175 class ForInContext : public RefCounted<ForInContext> {
176 WTF_MAKE_FAST_ALLOCATED;
177 WTF_MAKE_NONCOPYABLE(ForInContext);
179 ForInContext(RegisterID* localRegister)
180 : m_localRegister(localRegister)
185 virtual ~ForInContext()
189 bool isValid() const { return m_isValid; }
190 void invalidate() { m_isValid = false; }
192 enum ForInContextType {
193 StructureForInContextType,
194 IndexedForInContextType
196 virtual ForInContextType type() const = 0;
198 RegisterID* local() const { return m_localRegister.get(); }
201 RefPtr<RegisterID> m_localRegister;
205 class StructureForInContext : public ForInContext {
207 StructureForInContext(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister)
208 : ForInContext(localRegister)
209 , m_indexRegister(indexRegister)
210 , m_propertyRegister(propertyRegister)
211 , m_enumeratorRegister(enumeratorRegister)
215 ForInContextType type() const override
217 return StructureForInContextType;
220 RegisterID* index() const { return m_indexRegister.get(); }
221 RegisterID* property() const { return m_propertyRegister.get(); }
222 RegisterID* enumerator() const { return m_enumeratorRegister.get(); }
225 RefPtr<RegisterID> m_indexRegister;
226 RefPtr<RegisterID> m_propertyRegister;
227 RefPtr<RegisterID> m_enumeratorRegister;
230 class IndexedForInContext : public ForInContext {
232 IndexedForInContext(RegisterID* localRegister, RegisterID* indexRegister)
233 : ForInContext(localRegister)
234 , m_indexRegister(indexRegister)
238 ForInContextType type() const override
240 return IndexedForInContextType;
243 RegisterID* index() const { return m_indexRegister.get(); }
246 RefPtr<RegisterID> m_indexRegister;
251 HandlerType handlerType;
261 enum VariableKind { NormalVariable, SpecialVariable };
267 , m_kind(NormalVariable)
268 , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
269 , m_isLexicallyScoped(false)
273 Variable(const Identifier& ident)
277 , m_kind(NormalVariable) // This is somewhat meaningless here for this kind of Variable.
278 , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
279 , m_isLexicallyScoped(false)
283 Variable(const Identifier& ident, VarOffset offset, RegisterID* local, unsigned attributes, VariableKind kind, int symbolTableConstantIndex, bool isLexicallyScoped)
287 , m_attributes(attributes)
289 , m_symbolTableConstantIndex(symbolTableConstantIndex)
290 , m_isLexicallyScoped(isLexicallyScoped)
294 // If it's unset, then it is a non-locally-scoped variable. If it is set, then it could be
295 // a stack variable, a scoped variable in a local scope, or a variable captured in the
296 // direct arguments object.
297 bool isResolved() const { return !!m_offset; }
298 int symbolTableConstantIndex() const { ASSERT(isResolved() && !isSpecial()); return m_symbolTableConstantIndex; }
300 const Identifier& ident() const { return m_ident; }
302 VarOffset offset() const { return m_offset; }
303 bool isLocal() const { return m_offset.isStack(); }
304 RegisterID* local() const { return m_local; }
306 bool isReadOnly() const { return m_attributes & ReadOnly; }
307 bool isSpecial() const { return m_kind != NormalVariable; }
308 bool isConst() const { return isReadOnly() && m_isLexicallyScoped; }
309 void setIsReadOnly() { m_attributes |= ReadOnly; }
311 void dump(PrintStream&) const;
317 unsigned m_attributes;
319 int m_symbolTableConstantIndex;
320 bool m_isLexicallyScoped;
329 enum ProfileTypeBytecodeFlag {
330 ProfileTypeBytecodeClosureVar,
331 ProfileTypeBytecodeLocallyResolved,
332 ProfileTypeBytecodeDoesNotHaveGlobalID,
333 ProfileTypeBytecodeFunctionArgument,
334 ProfileTypeBytecodeFunctionReturnStatement
337 class BytecodeGenerator {
338 WTF_MAKE_FAST_ALLOCATED;
339 WTF_MAKE_NONCOPYABLE(BytecodeGenerator);
341 typedef DeclarationStacks::FunctionStack FunctionStack;
343 BytecodeGenerator(VM&, ProgramNode*, UnlinkedProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
344 BytecodeGenerator(VM&, FunctionNode*, UnlinkedFunctionCodeBlock*, DebuggerMode, const VariableEnvironment*);
345 BytecodeGenerator(VM&, EvalNode*, UnlinkedEvalCodeBlock*, DebuggerMode, const VariableEnvironment*);
346 BytecodeGenerator(VM&, ModuleProgramNode*, UnlinkedModuleProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
348 ~BytecodeGenerator();
350 VM* vm() const { return m_vm; }
351 ParserArena& parserArena() const { return m_scopeNode->parserArena(); }
352 const CommonIdentifiers& propertyNames() const { return *m_vm->propertyNames; }
354 bool isConstructor() const { return m_codeBlock->isConstructor(); }
355 DerivedContextType derivedContextType() const { return m_derivedContextType; }
356 bool usesArrowFunction() const { return m_scopeNode->usesArrowFunction(); }
357 bool needsToUpdateArrowFunctionContext() const { return m_needsToUpdateArrowFunctionContext; }
358 bool usesEval() const { return m_scopeNode->usesEval(); }
359 bool usesThis() const { return m_scopeNode->usesThis(); }
360 ConstructorKind constructorKind() const { return m_codeBlock->constructorKind(); }
361 SuperBinding superBinding() const { return m_codeBlock->superBinding(); }
362 JSParserScriptMode scriptMode() const { return m_codeBlock->scriptMode(); }
364 template<typename... Args>
365 static ParserError generate(VM& vm, Args&& ...args)
367 DeferGC deferGC(vm.heap);
368 auto bytecodeGenerator = std::make_unique<BytecodeGenerator>(vm, std::forward<Args>(args)...);
369 return bytecodeGenerator->generate();
372 bool isArgumentNumber(const Identifier&, int);
374 Variable variable(const Identifier&, ThisResolutionType = ThisResolutionType::Local);
376 enum ExistingVariableMode { VerifyExisting, IgnoreExisting };
377 void createVariable(const Identifier&, VarKind, SymbolTable*, ExistingVariableMode = VerifyExisting); // Creates the variable, or asserts that the already-created variable is sufficiently compatible.
379 // Returns the register storing "this"
380 RegisterID* thisRegister() { return &m_thisRegister; }
381 RegisterID* argumentsRegister() { return m_argumentsRegister; }
382 RegisterID* newTarget()
384 return m_newTargetRegister;
387 RegisterID* scopeRegister() { return m_scopeRegister; }
389 RegisterID* generatorRegister() { return m_generatorRegister; }
391 RegisterID* promiseCapabilityRegister() { return m_promiseCapabilityRegister; }
393 // Returns the next available temporary register. Registers returned by
394 // newTemporary require a modified form of reference counting: any
395 // register with a refcount of 0 is considered "available", meaning that
396 // the next instruction may overwrite it.
397 RegisterID* newTemporary();
399 // The same as newTemporary(), but this function returns "suggestion" if
400 // "suggestion" is a temporary. This function is helpful in situations
401 // where you've put "suggestion" in a RefPtr, but you'd like to allow
402 // the next instruction to overwrite it anyway.
403 RegisterID* newTemporaryOr(RegisterID* suggestion) { return suggestion->isTemporary() ? suggestion : newTemporary(); }
405 // Functions for handling of dst register
407 RegisterID* ignoredResult() { return &m_ignoredResultRegister; }
409 // This will be allocated in the temporary region of registers, but it will
410 // not be marked as a temporary. This will ensure that finalDestination() does
411 // not overwrite a block scope variable that it mistakes as a temporary. These
412 // registers can be (and are) reclaimed when the lexical scope they belong to
413 // is no longer on the symbol table stack.
414 RegisterID* newBlockScopeVariable();
416 // Returns a place to write intermediate values of an operation
417 // which reuses dst if it is safe to do so.
418 RegisterID* tempDestination(RegisterID* dst)
420 return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary();
423 // Returns the place to write the final output of an operation.
424 RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0)
426 if (originalDst && originalDst != ignoredResult())
428 ASSERT(tempDst != ignoredResult());
429 if (tempDst && tempDst->isTemporary())
431 return newTemporary();
434 RegisterID* destinationForAssignResult(RegisterID* dst)
436 if (dst && dst != ignoredResult())
437 return dst->isTemporary() ? dst : newTemporary();
441 // Moves src to dst if dst is not null and is different from src, otherwise just returns src.
442 RegisterID* moveToDestinationIfNeeded(RegisterID* dst, RegisterID* src)
444 return dst == ignoredResult() ? 0 : (dst && dst != src) ? emitMove(dst, src) : src;
447 LabelScopePtr newLabelScope(LabelScope::Type, const Identifier* = 0);
448 Ref<Label> newLabel();
449 Ref<Label> newEmittedLabel();
451 void emitNode(RegisterID* dst, StatementNode* n)
453 SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
454 return emitNodeInTailPosition(dst, n);
457 void emitNodeInTailPosition(RegisterID* dst, StatementNode* n)
459 // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
460 ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
461 if (UNLIKELY(!m_vm->isSafeToRecurse())) {
462 emitThrowExpressionTooDeepException();
465 if (UNLIKELY(n->needsDebugHook()))
467 n->emitBytecode(*this, dst);
470 void emitNode(StatementNode* n)
472 emitNode(nullptr, n);
475 void emitNodeInTailPosition(StatementNode* n)
477 emitNodeInTailPosition(nullptr, n);
480 RegisterID* emitNode(RegisterID* dst, ExpressionNode* n)
482 SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
483 return emitNodeInTailPosition(dst, n);
486 RegisterID* emitNodeInTailPosition(RegisterID* dst, ExpressionNode* n)
488 // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
489 ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
490 if (UNLIKELY(!m_vm->isSafeToRecurse()))
491 return emitThrowExpressionTooDeepException();
492 if (UNLIKELY(n->needsDebugHook()))
494 return n->emitBytecode(*this, dst);
497 RegisterID* emitNode(ExpressionNode* n)
499 return emitNode(nullptr, n);
502 RegisterID* emitNodeInTailPosition(ExpressionNode* n)
504 return emitNodeInTailPosition(nullptr, n);
507 void emitNodeInConditionContext(ExpressionNode* n, Label& trueTarget, Label& falseTarget, FallThroughMode fallThroughMode)
509 if (UNLIKELY(!m_vm->isSafeToRecurse())) {
510 emitThrowExpressionTooDeepException();
513 n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMode);
516 void emitExpressionInfo(const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
518 ASSERT(divot.offset >= divotStart.offset);
519 ASSERT(divotEnd.offset >= divot.offset);
521 int sourceOffset = m_scopeNode->source().startOffset();
522 unsigned firstLine = m_scopeNode->source().firstLine().oneBasedInt();
524 int divotOffset = divot.offset - sourceOffset;
525 int startOffset = divot.offset - divotStart.offset;
526 int endOffset = divotEnd.offset - divot.offset;
528 unsigned line = divot.line;
529 ASSERT(line >= firstLine);
532 int lineStart = divot.lineStartOffset;
533 if (lineStart > sourceOffset)
534 lineStart -= sourceOffset;
538 if (divotOffset < lineStart)
541 unsigned column = divotOffset - lineStart;
543 unsigned instructionOffset = instructions().size();
544 if (!m_isBuiltinFunction)
545 m_codeBlock->addExpressionInfo(instructionOffset, divotOffset, startOffset, endOffset, line, column);
549 ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure)
551 return (m_codeType != FunctionCode || rightHasAssignments) && !rightIsPure;
554 ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
556 if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
557 RefPtr<RegisterID> dst = newTemporary();
558 emitNode(dst.get(), n);
565 void hoistSloppyModeFunctionIfNecessary(const Identifier& functionName);
568 void emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot);
571 // This doesn't emit expression info. If using this, make sure you shouldn't be emitting text offset.
572 void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag);
573 // These variables are associated with variables in a program. They could be Locals, LocalClosureVar, or ClosureVar.
574 void emitProfileType(RegisterID* registerToProfile, const Variable&, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
576 void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
577 // These are not associated with variables and don't have a global id.
578 void emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
580 void emitProfileControlFlow(int);
582 RegisterID* emitLoadArrowFunctionLexicalEnvironment(const Identifier&);
583 RegisterID* ensureThis();
584 void emitLoadThisFromArrowFunctionLexicalEnvironment();
585 RegisterID* emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
587 RegisterID* emitLoad(RegisterID* dst, bool);
588 RegisterID* emitLoad(RegisterID* dst, const Identifier&);
589 RegisterID* emitLoad(RegisterID* dst, JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
590 RegisterID* emitLoad(RegisterID* dst, IdentifierSet& excludedList);
591 RegisterID* emitLoadGlobalObject(RegisterID* dst);
593 RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src);
594 RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src, OperandTypes);
595 RegisterID* emitUnaryOpProfiled(OpcodeID, RegisterID* dst, RegisterID* src);
596 RegisterID* emitBinaryOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes);
597 RegisterID* emitEqualityOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2);
598 RegisterID* emitUnaryNoDstOp(OpcodeID, RegisterID* src);
600 RegisterID* emitCreateThis(RegisterID* dst);
601 void emitTDZCheck(RegisterID* target);
602 bool needsTDZCheck(const Variable&);
603 void emitTDZCheckIfNecessary(const Variable&, RegisterID* target, RegisterID* scope);
604 void liftTDZCheckIfPossible(const Variable&);
605 RegisterID* emitNewObject(RegisterID* dst);
606 RegisterID* emitNewArray(RegisterID* dst, ElementNode*, unsigned length); // stops at first elision
607 RegisterID* emitNewArrayWithSpread(RegisterID* dst, ElementNode*);
608 RegisterID* emitNewArrayWithSize(RegisterID* dst, RegisterID* length);
610 RegisterID* emitNewFunction(RegisterID* dst, FunctionMetadataNode*);
611 RegisterID* emitNewFunctionExpression(RegisterID* dst, FuncExprNode*);
612 RegisterID* emitNewDefaultConstructor(RegisterID* dst, ConstructorKind, const Identifier& name, const Identifier& ecmaName, const SourceCode& classSource);
613 RegisterID* emitNewArrowFunctionExpression(RegisterID*, ArrowFuncExprNode*);
614 RegisterID* emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode*);
615 RegisterID* emitNewRegExp(RegisterID* dst, RegExp*);
617 void emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name);
619 RegisterID* emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant);
620 RegisterID* emitMoveEmptyValue(RegisterID* dst);
621 RegisterID* emitMove(RegisterID* dst, RegisterID* src);
623 RegisterID* emitToNumber(RegisterID* dst, RegisterID* src) { return emitUnaryOpProfiled(op_to_number, dst, src); }
624 RegisterID* emitToString(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_to_string, dst, src); }
625 RegisterID* emitInc(RegisterID* srcDst);
626 RegisterID* emitDec(RegisterID* srcDst);
628 RegisterID* emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue);
629 RegisterID* emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype);
630 RegisterID* emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue);
631 RegisterID* emitTypeOf(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_typeof, dst, src); }
632 RegisterID* emitIn(RegisterID* dst, RegisterID* property, RegisterID* base);
634 RegisterID* emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
635 RegisterID* emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
636 RegisterID* emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property);
637 RegisterID* emitPutById(RegisterID* base, const Identifier& property, RegisterID* value);
638 RegisterID* emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value);
639 RegisterID* emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType);
640 RegisterID* emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier&);
641 RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
642 RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property);
643 RegisterID* emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
644 RegisterID* emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value);
645 RegisterID* emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
646 RegisterID* emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
647 RegisterID* emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value);
649 RegisterID* emitAssert(RegisterID* condition, int line);
651 void emitPutGetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* getter);
652 void emitPutSetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* setter);
653 void emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter);
654 void emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* getter);
655 void emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* setter);
657 RegisterID* emitGetArgument(RegisterID* dst, int32_t index);
659 // Initialize object with generator fields (@generatorThis, @generatorNext, @generatorState, @generatorFrame)
660 void emitPutGeneratorFields(RegisterID* nextFunction);
662 ExpectedFunction expectedFunctionForIdentifier(const Identifier&);
663 RegisterID* emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
664 RegisterID* emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
665 RegisterID* emitCallEval(RegisterID* dst, RegisterID* func, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
666 RegisterID* emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
667 RegisterID* emitCallVarargsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
668 RegisterID* emitCallForwardArgumentsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
670 enum PropertyDescriptorOption {
671 PropertyConfigurable = 1,
672 PropertyWritable = 1 << 1,
673 PropertyEnumerable = 1 << 2,
675 void emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
676 RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition&);
678 void emitEnumeration(ThrowableExpressionData* enumerationNode, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, ForOfNode* = nullptr, RegisterID* forLoopSymbolTable = nullptr);
680 RegisterID* emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode*);
681 RegisterID* emitGetGlobalPrivate(RegisterID* dst, const Identifier& property);
683 enum class ReturnFrom { Normal, Finally };
684 RegisterID* emitReturn(RegisterID* src, ReturnFrom = ReturnFrom::Normal);
685 RegisterID* emitEnd(RegisterID* src) { return emitUnaryNoDstOp(op_end, src); }
687 RegisterID* emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd);
688 RegisterID* emitStrcat(RegisterID* dst, RegisterID* src, int count);
689 void emitToPrimitive(RegisterID* dst, RegisterID* src);
691 ResolveType resolveType();
692 RegisterID* emitResolveConstantLocal(RegisterID* dst, const Variable&);
693 RegisterID* emitResolveScope(RegisterID* dst, const Variable&);
694 RegisterID* emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable&, ResolveMode);
695 RegisterID* emitPutToScope(RegisterID* scope, const Variable&, RegisterID* value, ResolveMode, InitializationMode);
696 RegisterID* initializeVariable(const Variable&, RegisterID* value);
698 void emitLabel(Label&);
700 void emitJump(Label& target);
701 void emitJumpIfTrue(RegisterID* cond, Label& target);
702 void emitJumpIfFalse(RegisterID* cond, Label& target);
703 void emitJumpIfNotFunctionCall(RegisterID* cond, Label& target);
704 void emitJumpIfNotFunctionApply(RegisterID* cond, Label& target);
707 void emitCheckTraps();
709 RegisterID* emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
710 RegisterID* emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator);
711 RegisterID* emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
712 RegisterID* emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base);
713 RegisterID* emitGetEnumerableLength(RegisterID* dst, RegisterID* base);
714 RegisterID* emitGetStructurePropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length);
715 RegisterID* emitGetGenericPropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length, RegisterID* structureEnumerator);
716 RegisterID* emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
717 RegisterID* emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
718 RegisterID* emitToIndexString(RegisterID* dst, RegisterID* index);
720 RegisterID* emitIsCellWithType(RegisterID* dst, RegisterID* src, JSType);
721 RegisterID* emitIsJSArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ArrayType); }
722 RegisterID* emitIsProxyObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ProxyObjectType); }
723 RegisterID* emitIsRegExpObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, RegExpObjectType); }
724 RegisterID* emitIsMap(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSMapType); }
725 RegisterID* emitIsSet(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSSetType); }
726 RegisterID* emitIsObject(RegisterID* dst, RegisterID* src);
727 RegisterID* emitIsNumber(RegisterID* dst, RegisterID* src);
728 RegisterID* emitIsUndefined(RegisterID* dst, RegisterID* src);
729 RegisterID* emitIsEmpty(RegisterID* dst, RegisterID* src);
730 RegisterID* emitIsDerivedArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, DerivedArrayType); }
731 void emitRequireObjectCoercible(RegisterID* value, const String& error);
733 RegisterID* emitIteratorNext(RegisterID* dst, RegisterID* iterator, const ThrowableExpressionData* node);
734 RegisterID* emitIteratorNextWithValue(RegisterID* dst, RegisterID* iterator, RegisterID* value, const ThrowableExpressionData* node);
735 void emitIteratorClose(RegisterID* iterator, const ThrowableExpressionData* node);
737 RegisterID* emitRestParameter(RegisterID* result, unsigned numParametersToSkip);
739 bool emitReadOnlyExceptionIfNeeded(const Variable&);
741 // Start a try block. 'start' must have been emitted.
742 TryData* pushTry(Label& start, Label& handlerLabel, HandlerType);
743 // End a try block. 'end' must have been emitted.
744 void popTry(TryData*, Label& end);
745 void emitCatch(RegisterID* exceptionRegister, RegisterID* thrownValueRegister);
748 static const int CurrentLexicalScopeIndex = -2;
749 static const int OutermostLexicalScopeIndex = -1;
751 int currentLexicalScopeIndex() const
753 int size = static_cast<int>(m_lexicalScopeStack.size());
754 ASSERT(static_cast<size_t>(size) == m_lexicalScopeStack.size());
757 return OutermostLexicalScopeIndex;
762 void restoreScopeRegister();
763 void restoreScopeRegister(int lexicalScopeIndex);
765 int labelScopeDepthToLexicalScopeIndex(int labelScopeDepth);
767 void emitThrow(RegisterID* exc)
769 m_usesExceptions = true;
770 emitUnaryNoDstOp(op_throw, exc);
773 void emitThrowStaticError(ErrorType, RegisterID*);
774 void emitThrowStaticError(ErrorType, const Identifier& message);
775 void emitThrowReferenceError(const String& message);
776 void emitThrowTypeError(const String& message);
777 void emitThrowTypeError(const Identifier& message);
778 void emitThrowRangeError(const Identifier& message);
779 void emitThrowOutOfMemoryError();
781 void emitPushCatchScope(VariableEnvironment&);
782 void emitPopCatchScope(VariableEnvironment&);
785 RegisterID* emitPushWithScope(RegisterID* objectScope);
786 void emitPopWithScope();
787 void emitPutThisToArrowFunctionContextScope();
788 void emitPutNewTargetToArrowFunctionContextScope();
789 void emitPutDerivedConstructorToArrowFunctionContextScope();
790 RegisterID* emitLoadDerivedConstructorFromArrowFunctionLexicalEnvironment();
792 void emitDebugHook(DebugHookType, const JSTextPosition&);
793 void emitDebugHook(DebugHookType, unsigned line, unsigned charOffset, unsigned lineStart);
794 void emitDebugHook(StatementNode*);
795 void emitDebugHook(ExpressionNode*);
796 void emitWillLeaveCallFrameDebugHook();
798 class CompletionRecordScope {
800 CompletionRecordScope(BytecodeGenerator& generator, bool needCompletionRecordRegisters = true)
801 : m_generator(generator)
803 if (needCompletionRecordRegisters && m_generator.allocateCompletionRecordRegisters())
804 m_needToReleaseOnDestruction = true;
806 ~CompletionRecordScope()
808 if (m_needToReleaseOnDestruction)
809 m_generator.releaseCompletionRecordRegisters();
813 BytecodeGenerator& m_generator;
814 bool m_needToReleaseOnDestruction { false };
817 RegisterID* completionTypeRegister() const
819 ASSERT(m_completionTypeRegister);
820 return m_completionTypeRegister.get();
822 RegisterID* completionValueRegister() const
824 ASSERT(m_completionValueRegister);
825 return m_completionValueRegister.get();
828 void emitSetCompletionType(CompletionType type)
830 emitLoad(completionTypeRegister(), JSValue(static_cast<int>(type)));
832 void emitSetCompletionValue(RegisterID* reg)
834 emitMove(completionValueRegister(), reg);
837 void emitJumpIf(OpcodeID compareOpcode, RegisterID* completionTypeRegister, CompletionType, Label& jumpTarget);
839 bool emitJumpViaFinallyIfNeeded(int targetLabelScopeDepth, Label& jumpTarget);
840 bool emitReturnViaFinallyIfNeeded(RegisterID* returnRegister);
841 void emitFinallyCompletion(FinallyContext&, RegisterID* completionTypeRegister, Label& normalCompletionLabel);
844 bool allocateCompletionRecordRegisters();
845 void releaseCompletionRecordRegisters();
848 FinallyContext* pushFinallyControlFlowScope(Label& finallyLabel);
849 FinallyContext popFinallyControlFlowScope();
851 void pushIndexedForInScope(RegisterID* local, RegisterID* index);
852 void popIndexedForInScope(RegisterID* local);
853 void pushStructureForInScope(RegisterID* local, RegisterID* index, RegisterID* property, RegisterID* enumerator);
854 void popStructureForInScope(RegisterID* local);
855 void invalidateForInContextForLocal(RegisterID* local);
857 LabelScopePtr breakTarget(const Identifier&);
858 LabelScopePtr continueTarget(const Identifier&);
860 void beginSwitch(RegisterID*, SwitchInfo::SwitchType);
861 void endSwitch(uint32_t clauseCount, const Vector<Ref<Label>, 8>&, ExpressionNode**, Label& defaultLabel, int32_t min, int32_t range);
863 void emitYieldPoint(RegisterID*);
865 void emitGeneratorStateLabel();
866 void emitGeneratorStateChange(int32_t state);
867 RegisterID* emitYield(RegisterID* argument);
868 RegisterID* emitDelegateYield(RegisterID* argument, ThrowableExpressionData*);
869 RegisterID* generatorStateRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::State)]; }
870 RegisterID* generatorValueRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Value)]; }
871 RegisterID* generatorResumeModeRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::ResumeMode)]; }
872 RegisterID* generatorFrameRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Frame)]; }
874 CodeType codeType() const { return m_codeType; }
876 bool shouldEmitDebugHooks() { return m_shouldEmitDebugHooks; }
878 bool isStrictMode() const { return m_codeBlock->isStrictMode(); }
880 SourceParseMode parseMode() const { return m_codeBlock->parseMode(); }
882 bool isBuiltinFunction() const { return m_isBuiltinFunction; }
884 OpcodeID lastOpcodeID() const { return m_lastOpcodeID; }
886 bool isDerivedConstructorContext() { return m_derivedContextType == DerivedContextType::DerivedConstructorContext; }
887 bool isDerivedClassContext() { return m_derivedContextType == DerivedContextType::DerivedMethodContext; }
888 bool isArrowFunction() { return m_codeBlock->isArrowFunction(); }
890 enum class TDZCheckOptimization { Optimize, DoNotOptimize };
891 enum class NestedScopeType { IsNested, IsNotNested };
893 enum class TDZRequirement { UnderTDZ, NotUnderTDZ };
894 enum class ScopeType { CatchScope, LetConstScope, FunctionNameScope };
895 enum class ScopeRegisterType { Var, Block };
896 void pushLexicalScopeInternal(VariableEnvironment&, TDZCheckOptimization, NestedScopeType, RegisterID** constantSymbolTableResult, TDZRequirement, ScopeType, ScopeRegisterType);
897 void initializeBlockScopedFunctions(VariableEnvironment&, FunctionStack&, RegisterID* constantSymbolTable);
898 void popLexicalScopeInternal(VariableEnvironment&);
899 template<typename LookUpVarKindFunctor>
900 bool instantiateLexicalVariables(const VariableEnvironment&, SymbolTable*, ScopeRegisterType, LookUpVarKindFunctor);
901 void emitPrefillStackTDZVariables(const VariableEnvironment&, SymbolTable*);
902 void emitPopScope(RegisterID* dst, RegisterID* scope);
903 RegisterID* emitGetParentScope(RegisterID* dst, RegisterID* scope);
904 void emitPushFunctionNameScope(const Identifier& property, RegisterID* value, bool isCaptured);
905 void emitNewFunctionExpressionCommon(RegisterID*, FunctionMetadataNode*);
907 bool isNewTargetUsedInInnerArrowFunction();
908 bool isArgumentsUsedInInnerArrowFunction();
911 bool isSuperUsedInInnerArrowFunction();
912 bool isSuperCallUsedInInnerArrowFunction();
913 bool isThisUsedInInnerArrowFunction();
914 void pushLexicalScope(VariableEnvironmentNode*, TDZCheckOptimization, NestedScopeType = NestedScopeType::IsNotNested, RegisterID** constantSymbolTableResult = nullptr, bool shouldInitializeBlockScopedFunctions = true);
915 void popLexicalScope(VariableEnvironmentNode*);
916 void prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode*, RegisterID* loopSymbolTable);
917 int labelScopeDepth() const;
920 ParserError generate();
921 void reclaimFreeRegisters();
922 Variable variableForLocalEntry(const Identifier&, const SymbolTableEntry&, int symbolTableConstantIndex, bool isLexicallyScoped);
924 void emitOpcode(OpcodeID);
925 UnlinkedArrayAllocationProfile newArrayAllocationProfile();
926 UnlinkedObjectAllocationProfile newObjectAllocationProfile();
927 UnlinkedArrayProfile newArrayProfile();
928 UnlinkedValueProfile emitProfiledOpcode(OpcodeID);
929 int kill(RegisterID* dst)
931 int index = dst->index();
932 m_staticPropertyAnalyzer.kill(index);
936 void retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index);
937 void retrieveLastUnaryOp(int& dstIndex, int& srcIndex);
938 ALWAYS_INLINE void rewindBinaryOp();
939 ALWAYS_INLINE void rewindUnaryOp();
941 void allocateCalleeSaveSpace();
942 void allocateAndEmitScope();
944 typedef HashMap<double, JSValue> NumberMap;
945 typedef HashMap<UniquedStringImpl*, JSString*, IdentifierRepHash> IdentifierStringMap;
946 typedef HashMap<Ref<TemplateRegistryKey>, RegisterID*> TemplateRegistryKeyMap;
948 // Helper for emitCall() and emitConstruct(). This works because the set of
949 // expected functions have identical behavior for both call and construct
950 // (i.e. "Object()" is identical to "new Object()").
951 ExpectedFunction emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, Label& done);
953 RegisterID* emitCall(OpcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
955 RegisterID* newRegister();
957 // Adds an anonymous local var slot. To give this slot a name, add it to symbolTable().
960 ++m_codeBlock->m_numVars;
961 RegisterID* result = newRegister();
962 ASSERT(VirtualRegister(result->index()).toLocal() == m_codeBlock->m_numVars - 1);
963 result->ref(); // We should never free this slot.
967 // Initializes the stack form the parameter; does nothing for the symbol table.
968 RegisterID* initializeNextParameter();
969 UniquedStringImpl* visibleNameForParameter(DestructuringPatternNode*);
971 RegisterID& registerFor(VirtualRegister reg)
974 return m_calleeLocals[reg.toLocal()];
976 if (reg.offset() == CallFrameSlot::callee)
977 return m_calleeRegister;
979 ASSERT(m_parameters.size());
980 return m_parameters[reg.toArgument()];
983 bool hasConstant(const Identifier&) const;
984 unsigned addConstant(const Identifier&);
985 RegisterID* addConstantValue(JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
986 RegisterID* addConstantEmptyValue();
987 unsigned addRegExp(RegExp*);
989 unsigned addConstantBuffer(unsigned length);
991 UnlinkedFunctionExecutable* makeFunction(FunctionMetadataNode* metadata)
993 DerivedContextType newDerivedContextType = DerivedContextType::None;
995 if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(metadata->parseMode())) {
996 if (constructorKind() == ConstructorKind::Extends || isDerivedConstructorContext())
997 newDerivedContextType = DerivedContextType::DerivedConstructorContext;
998 else if (m_codeBlock->isClassContext() || isDerivedClassContext())
999 newDerivedContextType = DerivedContextType::DerivedMethodContext;
1002 VariableEnvironment variablesUnderTDZ;
1003 getVariablesUnderTDZ(variablesUnderTDZ);
1005 // FIXME: These flags, ParserModes and propagation to XXXCodeBlocks should be reorganized.
1006 // https://bugs.webkit.org/show_bug.cgi?id=151547
1007 SourceParseMode parseMode = metadata->parseMode();
1008 ConstructAbility constructAbility = constructAbilityForParseMode(parseMode);
1009 if (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() != ConstructorKind::None)
1010 constructAbility = ConstructAbility::CanConstruct;
1012 return UnlinkedFunctionExecutable::create(m_vm, m_scopeNode->source(), metadata, isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, constructAbility, scriptMode(), variablesUnderTDZ, newDerivedContextType);
1015 void getVariablesUnderTDZ(VariableEnvironment&);
1017 RegisterID* emitConstructVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1018 RegisterID* emitCallVarargs(OpcodeID, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1020 void emitLogShadowChickenPrologueIfNecessary();
1021 void emitLogShadowChickenTailIfNecessary();
1023 void initializeParameters(FunctionParameters&);
1024 void initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables);
1025 void initializeDefaultParameterValuesAndSetupFunctionScopeStack(FunctionParameters&, bool isSimpleParameterList, FunctionNode*, SymbolTable*, int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope);
1026 void initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable = nullptr, bool canReuseLexicalEnvironment = false);
1027 bool needsDerivedConstructorInArrowFunctionLexicalEnvironment();
1030 JSString* addStringConstant(const Identifier&);
1031 RegisterID* addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&&);
1033 Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>& instructions() { return m_instructions; }
1035 RegisterID* emitThrowExpressionTooDeepException();
1038 Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow> m_instructions;
1040 bool m_shouldEmitDebugHooks;
1042 struct LexicalScopeStackEntry {
1043 SymbolTable* m_symbolTable;
1044 RegisterID* m_scope;
1046 int m_symbolTableConstantIndex;
1048 Vector<LexicalScopeStackEntry> m_lexicalScopeStack;
1049 enum class TDZNecessityLevel {
1054 typedef HashMap<RefPtr<UniquedStringImpl>, TDZNecessityLevel, IdentifierRepHash> TDZMap;
1055 Vector<TDZMap> m_TDZStack;
1056 std::optional<size_t> m_varScopeLexicalScopeStackIndex;
1057 void pushTDZVariables(const VariableEnvironment&, TDZCheckOptimization, TDZRequirement);
1059 ScopeNode* const m_scopeNode;
1060 Strong<UnlinkedCodeBlock> m_codeBlock;
1062 // Some of these objects keep pointers to one another. They are arranged
1063 // to ensure a sane destruction order that avoids references to freed memory.
1064 HashSet<RefPtr<UniquedStringImpl>, IdentifierRepHash> m_functions;
1065 RegisterID m_ignoredResultRegister;
1066 RegisterID m_thisRegister;
1067 RegisterID m_calleeRegister;
1068 RegisterID* m_scopeRegister { nullptr };
1069 RegisterID* m_topMostScope { nullptr };
1070 RegisterID* m_argumentsRegister { nullptr };
1071 RegisterID* m_lexicalEnvironmentRegister { nullptr };
1072 RegisterID* m_generatorRegister { nullptr };
1073 RegisterID* m_emptyValueRegister { nullptr };
1074 RegisterID* m_globalObjectRegister { nullptr };
1075 RegisterID* m_newTargetRegister { nullptr };
1076 RegisterID* m_isDerivedConstuctor { nullptr };
1077 RegisterID* m_linkTimeConstantRegisters[LinkTimeConstantCount];
1078 RegisterID* m_arrowFunctionContextLexicalEnvironmentRegister { nullptr };
1079 RegisterID* m_promiseCapabilityRegister { nullptr };
1081 RefPtr<RegisterID> m_completionTypeRegister;
1082 RefPtr<RegisterID> m_completionValueRegister;
1084 FinallyContext* m_currentFinallyContext { nullptr };
1086 SegmentedVector<RegisterID*, 16> m_localRegistersForCalleeSaveRegisters;
1087 SegmentedVector<RegisterID, 32> m_constantPoolRegisters;
1088 SegmentedVector<RegisterID, 32> m_calleeLocals;
1089 SegmentedVector<RegisterID, 32> m_parameters;
1090 SegmentedVector<Label, 32> m_labels;
1091 LabelScopeStore m_labelScopes;
1092 unsigned m_finallyDepth { 0 };
1093 int m_localScopeDepth { 0 };
1094 const CodeType m_codeType;
1096 int localScopeDepth() const;
1097 void pushLocalControlFlowScope();
1098 void popLocalControlFlowScope();
1100 // FIXME: Restore overflow checking with UnsafeVectorOverflow once SegmentVector supports it.
1101 // https://bugs.webkit.org/show_bug.cgi?id=165980
1102 SegmentedVector<ControlFlowScope, 16> m_controlFlowScopeStack;
1103 Vector<SwitchInfo> m_switchContextStack;
1104 Vector<Ref<ForInContext>> m_forInContextStack;
1105 Vector<TryContext> m_tryContextStack;
1106 unsigned m_yieldPoints { 0 };
1108 Strong<SymbolTable> m_generatorFrameSymbolTable;
1109 int m_generatorFrameSymbolTableIndex { 0 };
1111 enum FunctionVariableType : uint8_t { NormalFunctionVariable, GlobalFunctionVariable };
1112 Vector<std::pair<FunctionMetadataNode*, FunctionVariableType>> m_functionsToInitialize;
1113 bool m_needToInitializeArguments { false };
1114 RestParameterNode* m_restParameter { nullptr };
1116 Vector<TryRange> m_tryRanges;
1117 SegmentedVector<TryData, 8> m_tryData;
1119 int m_nextConstantOffset { 0 };
1121 typedef HashMap<FunctionMetadataNode*, unsigned> FunctionOffsetMap;
1122 FunctionOffsetMap m_functionOffsets;
1125 IdentifierMap m_identifierMap;
1127 typedef HashMap<EncodedJSValueWithRepresentation, unsigned, EncodedJSValueWithRepresentationHash, EncodedJSValueWithRepresentationHashTraits> JSValueMap;
1128 JSValueMap m_jsValueMap;
1129 IdentifierStringMap m_stringMap;
1130 TemplateRegistryKeyMap m_templateRegistryKeyMap;
1132 StaticPropertyAnalyzer m_staticPropertyAnalyzer { &m_instructions };
1136 OpcodeID m_lastOpcodeID = op_end;
1138 size_t m_lastOpcodePosition { 0 };
1141 bool m_usesExceptions { false };
1142 bool m_expressionTooDeep { false };
1143 bool m_isBuiltinFunction { false };
1144 bool m_usesNonStrictEval { false };
1145 bool m_inTailPosition { false };
1146 bool m_needsToUpdateArrowFunctionContext;
1147 DerivedContextType m_derivedContextType { DerivedContextType::None };
1154 void printInternal(PrintStream&, JSC::Variable::VariableKind);