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 "JSAsyncGeneratorFunction.h"
37 #include "JSGeneratorFunction.h"
39 #include "LabelScope.h"
41 #include "ParserError.h"
42 #include "RegisterID.h"
43 #include "StaticPropertyAnalyzer.h"
44 #include "SymbolTable.h"
45 #include "TemplateRegistryKey.h"
46 #include "UnlinkedCodeBlock.h"
48 #include <wtf/CheckedArithmetic.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 EmitAwait { Yes, No };
66 enum class DebuggableCall { Yes, No };
67 enum class ThisResolutionType { Local, Scoped };
71 CallArguments(BytecodeGenerator&, ArgumentsNode*, unsigned additionalArguments = 0);
73 RegisterID* thisRegister() { return m_argv[0].get(); }
74 RegisterID* argumentRegister(unsigned i) { return m_argv[i + 1].get(); }
75 unsigned stackOffset() { return -m_argv[0]->index() + CallFrame::headerSizeInRegisters; }
76 unsigned argumentCountIncludingThis() { return m_argv.size() - m_padding; }
77 ArgumentsNode* argumentsNode() { return m_argumentsNode; }
80 ArgumentsNode* m_argumentsNode;
81 Vector<RefPtr<RegisterID>, 8, UnsafeVectorOverflow> m_argv;
85 // https://tc39.github.io/ecma262/#sec-completion-record-specification-type
87 // For the Break and Continue cases, instead of using the Break and Continue enum values
88 // below, we use the unique jumpID of the break and continue statement as the encoding
89 // for the CompletionType value. emitFinallyCompletion() uses this jumpID value later
90 // to determine the appropriate jump target to jump to after executing the relevant finally
91 // blocks. The jumpID is computed as:
92 // jumpID = bytecodeOffset (of the break/continue node) + CompletionType::NumberOfTypes.
93 // Hence, there won't be any collision between jumpIDs and CompletionType enums.
94 enum class CompletionType : int {
104 inline CompletionType bytecodeOffsetToJumpID(unsigned offset)
106 int jumpIDAsInt = offset + static_cast<int>(CompletionType::NumberOfTypes);
107 ASSERT(jumpIDAsInt >= static_cast<int>(CompletionType::NumberOfTypes));
108 return static_cast<CompletionType>(jumpIDAsInt);
112 FinallyJump(CompletionType jumpID, int targetLexicalScopeIndex, Label& targetLabel)
114 , targetLexicalScopeIndex(targetLexicalScopeIndex)
115 , targetLabel(targetLabel)
118 CompletionType jumpID;
119 int targetLexicalScopeIndex;
120 Ref<Label> targetLabel;
123 struct FinallyContext {
125 FinallyContext(FinallyContext* outerContext, Label& finallyLabel)
126 : m_outerContext(outerContext)
127 , m_finallyLabel(&finallyLabel)
129 ASSERT(m_jumps.isEmpty());
132 FinallyContext* outerContext() const { return m_outerContext; }
133 Label* finallyLabel() const { return m_finallyLabel; }
135 uint32_t numberOfBreaksOrContinues() const { return m_numberOfBreaksOrContinues.unsafeGet(); }
136 void incNumberOfBreaksOrContinues() { m_numberOfBreaksOrContinues++; }
138 bool handlesReturns() const { return m_handlesReturns; }
139 void setHandlesReturns() { m_handlesReturns = true; }
141 void registerJump(CompletionType jumpID, int lexicalScopeIndex, Label& targetLabel)
143 m_jumps.append(FinallyJump(jumpID, lexicalScopeIndex, targetLabel));
146 size_t numberOfJumps() const { return m_jumps.size(); }
147 FinallyJump& jumps(size_t i) { return m_jumps[i]; }
150 FinallyContext* m_outerContext { nullptr };
151 Label* m_finallyLabel { nullptr };
152 Checked<uint32_t, WTF::CrashOnOverflow> m_numberOfBreaksOrContinues;
153 bool m_handlesReturns { false };
154 Vector<FinallyJump> m_jumps;
157 struct ControlFlowScope {
158 typedef uint8_t Type;
163 ControlFlowScope(Type type, int lexicalScopeIndex, FinallyContext&& finallyContext = FinallyContext())
165 , lexicalScopeIndex(lexicalScopeIndex)
166 , finallyContext(std::forward<FinallyContext>(finallyContext))
169 bool isLabelScope() const { return type == Label; }
170 bool isFinallyScope() const { return type == Finally; }
173 int lexicalScopeIndex;
174 FinallyContext finallyContext;
177 class ForInContext : public RefCounted<ForInContext> {
178 WTF_MAKE_FAST_ALLOCATED;
179 WTF_MAKE_NONCOPYABLE(ForInContext);
181 ForInContext(RegisterID* localRegister)
182 : m_localRegister(localRegister)
187 virtual ~ForInContext()
191 bool isValid() const { return m_isValid; }
192 void invalidate() { m_isValid = false; }
194 enum ForInContextType {
195 StructureForInContextType,
196 IndexedForInContextType
198 virtual ForInContextType type() const = 0;
200 RegisterID* local() const { return m_localRegister.get(); }
203 RefPtr<RegisterID> m_localRegister;
207 class StructureForInContext : public ForInContext {
209 using GetInst = std::tuple<unsigned, int, UnlinkedValueProfile>;
211 StructureForInContext(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister)
212 : ForInContext(localRegister)
213 , m_indexRegister(indexRegister)
214 , m_propertyRegister(propertyRegister)
215 , m_enumeratorRegister(enumeratorRegister)
219 ForInContextType type() const override
221 return StructureForInContextType;
224 RegisterID* index() const { return m_indexRegister.get(); }
225 RegisterID* property() const { return m_propertyRegister.get(); }
226 RegisterID* enumerator() const { return m_enumeratorRegister.get(); }
228 void addGetInst(unsigned instIndex, int propertyRegIndex, UnlinkedValueProfile valueProfile)
230 m_getInsts.append(GetInst { instIndex, propertyRegIndex, valueProfile });
233 void finalize(BytecodeGenerator&);
236 RefPtr<RegisterID> m_indexRegister;
237 RefPtr<RegisterID> m_propertyRegister;
238 RefPtr<RegisterID> m_enumeratorRegister;
239 Vector<GetInst> m_getInsts;
242 class IndexedForInContext : public ForInContext {
244 IndexedForInContext(RegisterID* localRegister, RegisterID* indexRegister)
245 : ForInContext(localRegister)
246 , m_indexRegister(indexRegister)
250 ForInContextType type() const override
252 return IndexedForInContextType;
255 RegisterID* index() const { return m_indexRegister.get(); }
257 void finalize(BytecodeGenerator&);
258 void addGetInst(unsigned instIndex, int propertyIndex) { m_getInsts.append({ instIndex, propertyIndex }); }
261 RefPtr<RegisterID> m_indexRegister;
262 Vector<std::pair<unsigned, int>> m_getInsts;
267 HandlerType handlerType;
277 enum VariableKind { NormalVariable, SpecialVariable };
283 , m_kind(NormalVariable)
284 , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
285 , m_isLexicallyScoped(false)
289 Variable(const Identifier& ident)
293 , m_kind(NormalVariable) // This is somewhat meaningless here for this kind of Variable.
294 , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
295 , m_isLexicallyScoped(false)
299 Variable(const Identifier& ident, VarOffset offset, RegisterID* local, unsigned attributes, VariableKind kind, int symbolTableConstantIndex, bool isLexicallyScoped)
303 , m_attributes(attributes)
305 , m_symbolTableConstantIndex(symbolTableConstantIndex)
306 , m_isLexicallyScoped(isLexicallyScoped)
310 // If it's unset, then it is a non-locally-scoped variable. If it is set, then it could be
311 // a stack variable, a scoped variable in a local scope, or a variable captured in the
312 // direct arguments object.
313 bool isResolved() const { return !!m_offset; }
314 int symbolTableConstantIndex() const { ASSERT(isResolved() && !isSpecial()); return m_symbolTableConstantIndex; }
316 const Identifier& ident() const { return m_ident; }
318 VarOffset offset() const { return m_offset; }
319 bool isLocal() const { return m_offset.isStack(); }
320 RegisterID* local() const { return m_local; }
322 bool isReadOnly() const { return m_attributes & ReadOnly; }
323 bool isSpecial() const { return m_kind != NormalVariable; }
324 bool isConst() const { return isReadOnly() && m_isLexicallyScoped; }
325 void setIsReadOnly() { m_attributes |= ReadOnly; }
327 void dump(PrintStream&) const;
333 unsigned m_attributes;
335 int m_symbolTableConstantIndex;
336 bool m_isLexicallyScoped;
345 enum ProfileTypeBytecodeFlag {
346 ProfileTypeBytecodeClosureVar,
347 ProfileTypeBytecodeLocallyResolved,
348 ProfileTypeBytecodeDoesNotHaveGlobalID,
349 ProfileTypeBytecodeFunctionArgument,
350 ProfileTypeBytecodeFunctionReturnStatement
353 class BytecodeGenerator {
354 WTF_MAKE_FAST_ALLOCATED;
355 WTF_MAKE_NONCOPYABLE(BytecodeGenerator);
357 typedef DeclarationStacks::FunctionStack FunctionStack;
359 BytecodeGenerator(VM&, ProgramNode*, UnlinkedProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
360 BytecodeGenerator(VM&, FunctionNode*, UnlinkedFunctionCodeBlock*, DebuggerMode, const VariableEnvironment*);
361 BytecodeGenerator(VM&, EvalNode*, UnlinkedEvalCodeBlock*, DebuggerMode, const VariableEnvironment*);
362 BytecodeGenerator(VM&, ModuleProgramNode*, UnlinkedModuleProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
364 ~BytecodeGenerator();
366 VM* vm() const { return m_vm; }
367 ParserArena& parserArena() const { return m_scopeNode->parserArena(); }
368 const CommonIdentifiers& propertyNames() const { return *m_vm->propertyNames; }
370 bool isConstructor() const { return m_codeBlock->isConstructor(); }
371 DerivedContextType derivedContextType() const { return m_derivedContextType; }
372 bool usesArrowFunction() const { return m_scopeNode->usesArrowFunction(); }
373 bool needsToUpdateArrowFunctionContext() const { return m_needsToUpdateArrowFunctionContext; }
374 bool usesEval() const { return m_scopeNode->usesEval(); }
375 bool usesThis() const { return m_scopeNode->usesThis(); }
376 ConstructorKind constructorKind() const { return m_codeBlock->constructorKind(); }
377 SuperBinding superBinding() const { return m_codeBlock->superBinding(); }
378 JSParserScriptMode scriptMode() const { return m_codeBlock->scriptMode(); }
380 template<typename... Args>
381 static ParserError generate(VM& vm, Args&& ...args)
383 DeferGC deferGC(vm.heap);
384 auto bytecodeGenerator = std::make_unique<BytecodeGenerator>(vm, std::forward<Args>(args)...);
385 return bytecodeGenerator->generate();
388 bool isArgumentNumber(const Identifier&, int);
390 Variable variable(const Identifier&, ThisResolutionType = ThisResolutionType::Local);
392 enum ExistingVariableMode { VerifyExisting, IgnoreExisting };
393 void createVariable(const Identifier&, VarKind, SymbolTable*, ExistingVariableMode = VerifyExisting); // Creates the variable, or asserts that the already-created variable is sufficiently compatible.
395 // Returns the register storing "this"
396 RegisterID* thisRegister() { return &m_thisRegister; }
397 RegisterID* argumentsRegister() { return m_argumentsRegister; }
398 RegisterID* newTarget()
400 return m_newTargetRegister;
403 RegisterID* scopeRegister() { return m_scopeRegister; }
405 RegisterID* generatorRegister() { return m_generatorRegister; }
407 RegisterID* promiseCapabilityRegister() { return m_promiseCapabilityRegister; }
409 // Returns the next available temporary register. Registers returned by
410 // newTemporary require a modified form of reference counting: any
411 // register with a refcount of 0 is considered "available", meaning that
412 // the next instruction may overwrite it.
413 RegisterID* newTemporary();
415 // The same as newTemporary(), but this function returns "suggestion" if
416 // "suggestion" is a temporary. This function is helpful in situations
417 // where you've put "suggestion" in a RefPtr, but you'd like to allow
418 // the next instruction to overwrite it anyway.
419 RegisterID* newTemporaryOr(RegisterID* suggestion) { return suggestion->isTemporary() ? suggestion : newTemporary(); }
421 // Functions for handling of dst register
423 RegisterID* ignoredResult() { return &m_ignoredResultRegister; }
425 // This will be allocated in the temporary region of registers, but it will
426 // not be marked as a temporary. This will ensure that finalDestination() does
427 // not overwrite a block scope variable that it mistakes as a temporary. These
428 // registers can be (and are) reclaimed when the lexical scope they belong to
429 // is no longer on the symbol table stack.
430 RegisterID* newBlockScopeVariable();
432 // Returns a place to write intermediate values of an operation
433 // which reuses dst if it is safe to do so.
434 RegisterID* tempDestination(RegisterID* dst)
436 return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary();
439 // Returns the place to write the final output of an operation.
440 RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0)
442 if (originalDst && originalDst != ignoredResult())
444 ASSERT(tempDst != ignoredResult());
445 if (tempDst && tempDst->isTemporary())
447 return newTemporary();
450 RegisterID* destinationForAssignResult(RegisterID* dst)
452 if (dst && dst != ignoredResult())
453 return dst->isTemporary() ? dst : newTemporary();
457 // Moves src to dst if dst is not null and is different from src, otherwise just returns src.
458 RegisterID* moveToDestinationIfNeeded(RegisterID* dst, RegisterID* src)
460 return dst == ignoredResult() ? 0 : (dst && dst != src) ? emitMove(dst, src) : src;
463 Ref<LabelScope> newLabelScope(LabelScope::Type, const Identifier* = 0);
464 Ref<Label> newLabel();
465 Ref<Label> newEmittedLabel();
467 void emitNode(RegisterID* dst, StatementNode* n)
469 SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
470 return emitNodeInTailPosition(dst, n);
473 void emitNodeInTailPosition(RegisterID* dst, StatementNode* n)
475 // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
476 ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
477 if (UNLIKELY(!m_vm->isSafeToRecurse())) {
478 emitThrowExpressionTooDeepException();
481 if (UNLIKELY(n->needsDebugHook()))
483 n->emitBytecode(*this, dst);
486 void emitNode(StatementNode* n)
488 emitNode(nullptr, n);
491 void emitNodeInTailPosition(StatementNode* n)
493 emitNodeInTailPosition(nullptr, n);
496 RegisterID* emitNode(RegisterID* dst, ExpressionNode* n)
498 SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
499 return emitNodeInTailPosition(dst, n);
502 RegisterID* emitNodeInTailPosition(RegisterID* dst, ExpressionNode* n)
504 // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
505 ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
506 if (UNLIKELY(!m_vm->isSafeToRecurse()))
507 return emitThrowExpressionTooDeepException();
508 if (UNLIKELY(n->needsDebugHook()))
510 return n->emitBytecode(*this, dst);
513 RegisterID* emitNode(ExpressionNode* n)
515 return emitNode(nullptr, n);
518 RegisterID* emitNodeInTailPosition(ExpressionNode* n)
520 return emitNodeInTailPosition(nullptr, n);
523 RegisterID* emitNodeForProperty(RegisterID* dst, ExpressionNode* node)
525 if (node->isString()) {
526 if (std::optional<uint32_t> index = parseIndex(static_cast<StringNode*>(node)->value()))
527 return emitLoad(dst, jsNumber(index.value()));
529 return emitNode(dst, node);
532 RegisterID* emitNodeForProperty(ExpressionNode* n)
534 return emitNodeForProperty(nullptr, n);
537 void emitNodeInConditionContext(ExpressionNode* n, Label& trueTarget, Label& falseTarget, FallThroughMode fallThroughMode)
539 if (UNLIKELY(!m_vm->isSafeToRecurse())) {
540 emitThrowExpressionTooDeepException();
543 n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMode);
546 void emitExpressionInfo(const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
548 ASSERT(divot.offset >= divotStart.offset);
549 ASSERT(divotEnd.offset >= divot.offset);
551 int sourceOffset = m_scopeNode->source().startOffset();
552 unsigned firstLine = m_scopeNode->source().firstLine().oneBasedInt();
554 int divotOffset = divot.offset - sourceOffset;
555 int startOffset = divot.offset - divotStart.offset;
556 int endOffset = divotEnd.offset - divot.offset;
558 unsigned line = divot.line;
559 ASSERT(line >= firstLine);
562 int lineStart = divot.lineStartOffset;
563 if (lineStart > sourceOffset)
564 lineStart -= sourceOffset;
568 if (divotOffset < lineStart)
571 unsigned column = divotOffset - lineStart;
573 unsigned instructionOffset = instructions().size();
574 if (!m_isBuiltinFunction)
575 m_codeBlock->addExpressionInfo(instructionOffset, divotOffset, startOffset, endOffset, line, column);
579 ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure)
581 return (m_codeType != FunctionCode || rightHasAssignments) && !rightIsPure;
584 ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
586 if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
587 RefPtr<RegisterID> dst = newTemporary();
588 emitNode(dst.get(), n);
595 ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSideForProperty(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
597 if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
598 RefPtr<RegisterID> dst = newTemporary();
599 emitNodeForProperty(dst.get(), n);
603 return emitNodeForProperty(n);
606 void hoistSloppyModeFunctionIfNecessary(const Identifier& functionName);
609 void emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot);
610 RegisterID* emitCreateAsyncGeneratorQueue(const JSTextPosition&);
613 // This doesn't emit expression info. If using this, make sure you shouldn't be emitting text offset.
614 void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag);
615 // These variables are associated with variables in a program. They could be Locals, LocalClosureVar, or ClosureVar.
616 void emitProfileType(RegisterID* registerToProfile, const Variable&, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
618 void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
619 // These are not associated with variables and don't have a global id.
620 void emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
622 void emitProfileControlFlow(int);
624 RegisterID* emitLoadArrowFunctionLexicalEnvironment(const Identifier&);
625 RegisterID* ensureThis();
626 void emitLoadThisFromArrowFunctionLexicalEnvironment();
627 RegisterID* emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
629 unsigned addConstantIndex();
630 RegisterID* emitLoad(RegisterID* dst, bool);
631 RegisterID* emitLoad(RegisterID* dst, const Identifier&);
632 RegisterID* emitLoad(RegisterID* dst, JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
633 RegisterID* emitLoad(RegisterID* dst, IdentifierSet& excludedList);
634 RegisterID* emitLoadGlobalObject(RegisterID* dst);
636 RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src);
637 RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src, OperandTypes);
638 RegisterID* emitUnaryOpProfiled(OpcodeID, RegisterID* dst, RegisterID* src);
639 RegisterID* emitBinaryOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes);
640 RegisterID* emitEqualityOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2);
641 RegisterID* emitUnaryNoDstOp(OpcodeID, RegisterID* src);
643 RegisterID* emitCreateThis(RegisterID* dst);
644 void emitTDZCheck(RegisterID* target);
645 bool needsTDZCheck(const Variable&);
646 void emitTDZCheckIfNecessary(const Variable&, RegisterID* target, RegisterID* scope);
647 void liftTDZCheckIfPossible(const Variable&);
648 RegisterID* emitNewObject(RegisterID* dst);
649 RegisterID* emitNewArray(RegisterID* dst, ElementNode*, unsigned length); // stops at first elision
650 RegisterID* emitNewArrayWithSpread(RegisterID* dst, ElementNode*);
651 RegisterID* emitNewArrayWithSize(RegisterID* dst, RegisterID* length);
653 RegisterID* emitNewFunction(RegisterID* dst, FunctionMetadataNode*);
654 RegisterID* emitNewFunctionExpression(RegisterID* dst, FuncExprNode*);
655 RegisterID* emitNewDefaultConstructor(RegisterID* dst, ConstructorKind, const Identifier& name, const Identifier& ecmaName, const SourceCode& classSource);
656 RegisterID* emitNewArrowFunctionExpression(RegisterID*, ArrowFuncExprNode*);
657 RegisterID* emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode*);
658 RegisterID* emitNewRegExp(RegisterID* dst, RegExp*);
660 void emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name);
662 RegisterID* emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant);
663 RegisterID* emitMoveEmptyValue(RegisterID* dst);
664 RegisterID* emitMove(RegisterID* dst, RegisterID* src);
666 RegisterID* emitToNumber(RegisterID* dst, RegisterID* src) { return emitUnaryOpProfiled(op_to_number, dst, src); }
667 RegisterID* emitToString(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_to_string, dst, src); }
668 RegisterID* emitInc(RegisterID* srcDst);
669 RegisterID* emitDec(RegisterID* srcDst);
671 RegisterID* emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue);
672 RegisterID* emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype);
673 RegisterID* emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue);
674 RegisterID* emitTypeOf(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_typeof, dst, src); }
675 RegisterID* emitIn(RegisterID* dst, RegisterID* property, RegisterID* base);
677 RegisterID* emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
678 RegisterID* emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
679 RegisterID* emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property);
680 RegisterID* emitPutById(RegisterID* base, const Identifier& property, RegisterID* value);
681 RegisterID* emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value);
682 RegisterID* emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType);
683 RegisterID* emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier&);
684 RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
685 RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property);
686 RegisterID* emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
687 RegisterID* emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value);
688 RegisterID* emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
689 RegisterID* emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
690 RegisterID* emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value);
692 RegisterID* emitAssert(RegisterID* condition, int line);
693 RegisterID* emitIdWithProfile(RegisterID* src, SpeculatedType profile);
694 void emitUnreachable();
696 void emitPutGetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* getter);
697 void emitPutSetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* setter);
698 void emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter);
699 void emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* getter);
700 void emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* setter);
702 RegisterID* emitGetArgument(RegisterID* dst, int32_t index);
704 // Initialize object with generator fields (@generatorThis, @generatorNext, @generatorState, @generatorFrame)
705 void emitPutGeneratorFields(RegisterID* nextFunction);
707 void emitPutAsyncGeneratorFields(RegisterID* nextFunction, const JSTextPosition&);
709 ExpectedFunction expectedFunctionForIdentifier(const Identifier&);
710 RegisterID* emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
711 RegisterID* emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
712 RegisterID* emitCallEval(RegisterID* dst, RegisterID* func, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
713 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);
714 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);
715 RegisterID* emitCallForwardArgumentsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
717 enum PropertyDescriptorOption {
718 PropertyConfigurable = 1,
719 PropertyWritable = 1 << 1,
720 PropertyEnumerable = 1 << 2,
722 void emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
723 RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition&);
725 void emitEnumeration(ThrowableExpressionData* enumerationNode, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, ForOfNode* = nullptr, RegisterID* forLoopSymbolTable = nullptr);
727 RegisterID* emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode*);
728 RegisterID* emitGetGlobalPrivate(RegisterID* dst, const Identifier& property);
730 enum class ReturnFrom { Normal, Finally };
731 RegisterID* emitReturn(RegisterID* src, ReturnFrom = ReturnFrom::Normal);
732 RegisterID* emitEnd(RegisterID* src) { return emitUnaryNoDstOp(op_end, src); }
734 RegisterID* emitConstruct(RegisterID* dst, RegisterID* func, RegisterID* lazyThis, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd);
735 RegisterID* emitStrcat(RegisterID* dst, RegisterID* src, int count);
736 void emitToPrimitive(RegisterID* dst, RegisterID* src);
738 ResolveType resolveType();
739 RegisterID* emitResolveConstantLocal(RegisterID* dst, const Variable&);
740 RegisterID* emitResolveScope(RegisterID* dst, const Variable&);
741 RegisterID* emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable&, ResolveMode);
742 RegisterID* emitPutToScope(RegisterID* scope, const Variable&, RegisterID* value, ResolveMode, InitializationMode);
744 RegisterID* emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier&);
746 RegisterID* initializeVariable(const Variable&, RegisterID* value);
748 void emitLabel(Label&);
750 void emitJump(Label& target);
751 void emitJumpIfTrue(RegisterID* cond, Label& target);
752 void emitJumpIfFalse(RegisterID* cond, Label& target);
753 void emitJumpIfNotFunctionCall(RegisterID* cond, Label& target);
754 void emitJumpIfNotFunctionApply(RegisterID* cond, Label& target);
757 void emitCheckTraps();
759 RegisterID* emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
760 RegisterID* emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator);
761 RegisterID* emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
762 RegisterID* emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base);
763 RegisterID* emitGetEnumerableLength(RegisterID* dst, RegisterID* base);
764 RegisterID* emitGetStructurePropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length);
765 RegisterID* emitGetGenericPropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length, RegisterID* structureEnumerator);
766 RegisterID* emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
767 RegisterID* emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
768 RegisterID* emitToIndexString(RegisterID* dst, RegisterID* index);
770 RegisterID* emitIsCellWithType(RegisterID* dst, RegisterID* src, JSType);
771 RegisterID* emitIsJSArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ArrayType); }
772 RegisterID* emitIsProxyObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ProxyObjectType); }
773 RegisterID* emitIsRegExpObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, RegExpObjectType); }
774 RegisterID* emitIsMap(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSMapType); }
775 RegisterID* emitIsSet(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSSetType); }
776 RegisterID* emitIsObject(RegisterID* dst, RegisterID* src);
777 RegisterID* emitIsNumber(RegisterID* dst, RegisterID* src);
778 RegisterID* emitIsUndefined(RegisterID* dst, RegisterID* src);
779 RegisterID* emitIsEmpty(RegisterID* dst, RegisterID* src);
780 RegisterID* emitIsDerivedArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, DerivedArrayType); }
781 void emitRequireObjectCoercible(RegisterID* value, const String& error);
783 RegisterID* emitIteratorNext(RegisterID* dst, RegisterID* nextMethod, RegisterID* iterator, const ThrowableExpressionData* node, JSC::EmitAwait = JSC::EmitAwait::No);
784 RegisterID* emitIteratorNextWithValue(RegisterID* dst, RegisterID* nextMethod, RegisterID* iterator, RegisterID* value, const ThrowableExpressionData* node);
785 void emitIteratorClose(RegisterID* iterator, const ThrowableExpressionData* node, EmitAwait = EmitAwait::No);
787 RegisterID* emitRestParameter(RegisterID* result, unsigned numParametersToSkip);
789 bool emitReadOnlyExceptionIfNeeded(const Variable&);
791 // Start a try block. 'start' must have been emitted.
792 TryData* pushTry(Label& start, Label& handlerLabel, HandlerType);
793 // End a try block. 'end' must have been emitted.
794 void popTry(TryData*, Label& end);
795 void emitCatch(RegisterID* exceptionRegister, RegisterID* thrownValueRegister, TryData*);
798 static const int CurrentLexicalScopeIndex = -2;
799 static const int OutermostLexicalScopeIndex = -1;
801 int currentLexicalScopeIndex() const
803 int size = static_cast<int>(m_lexicalScopeStack.size());
804 ASSERT(static_cast<size_t>(size) == m_lexicalScopeStack.size());
807 return OutermostLexicalScopeIndex;
812 void restoreScopeRegister();
813 void restoreScopeRegister(int lexicalScopeIndex);
815 int labelScopeDepthToLexicalScopeIndex(int labelScopeDepth);
817 void emitThrow(RegisterID* exc)
819 m_usesExceptions = true;
820 emitUnaryNoDstOp(op_throw, exc);
823 void emitThrowStaticError(ErrorType, RegisterID*);
824 void emitThrowStaticError(ErrorType, const Identifier& message);
825 void emitThrowReferenceError(const String& message);
826 void emitThrowTypeError(const String& message);
827 void emitThrowTypeError(const Identifier& message);
828 void emitThrowRangeError(const Identifier& message);
829 void emitThrowOutOfMemoryError();
831 void emitPushCatchScope(VariableEnvironment&);
832 void emitPopCatchScope(VariableEnvironment&);
834 RegisterID* emitGetIterator(RegisterID*, ThrowableExpressionData*);
835 RegisterID* emitGetAsyncIterator(RegisterID*, ThrowableExpressionData*);
837 void emitAwait(RegisterID*);
839 RegisterID* emitPushWithScope(RegisterID* objectScope);
840 void emitPopWithScope();
841 void emitPutThisToArrowFunctionContextScope();
842 void emitPutNewTargetToArrowFunctionContextScope();
843 void emitPutDerivedConstructorToArrowFunctionContextScope();
844 RegisterID* emitLoadDerivedConstructorFromArrowFunctionLexicalEnvironment();
846 void emitDebugHook(DebugHookType, const JSTextPosition&);
847 void emitDebugHook(DebugHookType, unsigned line, unsigned charOffset, unsigned lineStart);
848 void emitDebugHook(StatementNode*);
849 void emitDebugHook(ExpressionNode*);
850 void emitWillLeaveCallFrameDebugHook();
852 class CompletionRecordScope {
854 CompletionRecordScope(BytecodeGenerator& generator, bool needCompletionRecordRegisters = true)
855 : m_generator(generator)
857 if (needCompletionRecordRegisters && m_generator.allocateCompletionRecordRegisters())
858 m_needToReleaseOnDestruction = true;
860 ~CompletionRecordScope()
862 if (m_needToReleaseOnDestruction)
863 m_generator.releaseCompletionRecordRegisters();
867 BytecodeGenerator& m_generator;
868 bool m_needToReleaseOnDestruction { false };
871 RegisterID* completionTypeRegister() const
873 ASSERT(m_completionTypeRegister);
874 return m_completionTypeRegister.get();
876 RegisterID* completionValueRegister() const
878 ASSERT(m_completionValueRegister);
879 return m_completionValueRegister.get();
882 void emitSetCompletionType(CompletionType type)
884 emitLoad(completionTypeRegister(), JSValue(static_cast<int>(type)));
886 void emitSetCompletionValue(RegisterID* reg)
888 emitMove(completionValueRegister(), reg);
891 void emitJumpIf(OpcodeID compareOpcode, RegisterID* completionTypeRegister, CompletionType, Label& jumpTarget);
893 bool emitJumpViaFinallyIfNeeded(int targetLabelScopeDepth, Label& jumpTarget);
894 bool emitReturnViaFinallyIfNeeded(RegisterID* returnRegister);
895 void emitFinallyCompletion(FinallyContext&, RegisterID* completionTypeRegister, Label& normalCompletionLabel);
898 bool allocateCompletionRecordRegisters();
899 void releaseCompletionRecordRegisters();
902 FinallyContext* pushFinallyControlFlowScope(Label& finallyLabel);
903 FinallyContext popFinallyControlFlowScope();
905 void pushIndexedForInScope(RegisterID* local, RegisterID* index);
906 void popIndexedForInScope(RegisterID* local);
907 void pushStructureForInScope(RegisterID* local, RegisterID* index, RegisterID* property, RegisterID* enumerator);
908 void popStructureForInScope(RegisterID* local);
909 void invalidateForInContextForLocal(RegisterID* local);
911 LabelScope* breakTarget(const Identifier&);
912 LabelScope* continueTarget(const Identifier&);
914 void beginSwitch(RegisterID*, SwitchInfo::SwitchType);
915 void endSwitch(uint32_t clauseCount, const Vector<Ref<Label>, 8>&, ExpressionNode**, Label& defaultLabel, int32_t min, int32_t range);
917 void emitYieldPoint(RegisterID*, JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason);
919 void emitGeneratorStateLabel();
920 void emitGeneratorStateChange(int32_t state);
921 RegisterID* emitYield(RegisterID* argument, JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason = JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason::Yield);
922 RegisterID* emitDelegateYield(RegisterID* argument, ThrowableExpressionData*);
923 RegisterID* generatorStateRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::State)]; }
924 RegisterID* generatorValueRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Value)]; }
925 RegisterID* generatorResumeModeRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::ResumeMode)]; }
926 RegisterID* generatorFrameRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Frame)]; }
928 CodeType codeType() const { return m_codeType; }
930 bool shouldBeConcernedWithCompletionValue() const { return m_codeType != FunctionCode; }
932 bool shouldEmitDebugHooks() const { return m_shouldEmitDebugHooks; }
934 bool isStrictMode() const { return m_codeBlock->isStrictMode(); }
936 SourceParseMode parseMode() const { return m_codeBlock->parseMode(); }
938 bool isBuiltinFunction() const { return m_isBuiltinFunction; }
940 OpcodeID lastOpcodeID() const { return m_lastOpcodeID; }
942 bool isDerivedConstructorContext() { return m_derivedContextType == DerivedContextType::DerivedConstructorContext; }
943 bool isDerivedClassContext() { return m_derivedContextType == DerivedContextType::DerivedMethodContext; }
944 bool isArrowFunction() { return m_codeBlock->isArrowFunction(); }
946 enum class TDZCheckOptimization { Optimize, DoNotOptimize };
947 enum class NestedScopeType { IsNested, IsNotNested };
949 enum class TDZRequirement { UnderTDZ, NotUnderTDZ };
950 enum class ScopeType { CatchScope, LetConstScope, FunctionNameScope };
951 enum class ScopeRegisterType { Var, Block };
952 void pushLexicalScopeInternal(VariableEnvironment&, TDZCheckOptimization, NestedScopeType, RegisterID** constantSymbolTableResult, TDZRequirement, ScopeType, ScopeRegisterType);
953 void initializeBlockScopedFunctions(VariableEnvironment&, FunctionStack&, RegisterID* constantSymbolTable);
954 void popLexicalScopeInternal(VariableEnvironment&);
955 template<typename LookUpVarKindFunctor>
956 bool instantiateLexicalVariables(const VariableEnvironment&, SymbolTable*, ScopeRegisterType, LookUpVarKindFunctor);
957 void emitPrefillStackTDZVariables(const VariableEnvironment&, SymbolTable*);
958 void emitPopScope(RegisterID* dst, RegisterID* scope);
959 RegisterID* emitGetParentScope(RegisterID* dst, RegisterID* scope);
960 void emitPushFunctionNameScope(const Identifier& property, RegisterID* value, bool isCaptured);
961 void emitNewFunctionExpressionCommon(RegisterID*, FunctionMetadataNode*);
963 bool isNewTargetUsedInInnerArrowFunction();
964 bool isArgumentsUsedInInnerArrowFunction();
967 bool isSuperUsedInInnerArrowFunction();
968 bool isSuperCallUsedInInnerArrowFunction();
969 bool isThisUsedInInnerArrowFunction();
970 void pushLexicalScope(VariableEnvironmentNode*, TDZCheckOptimization, NestedScopeType = NestedScopeType::IsNotNested, RegisterID** constantSymbolTableResult = nullptr, bool shouldInitializeBlockScopedFunctions = true);
971 void popLexicalScope(VariableEnvironmentNode*);
972 void prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode*, RegisterID* loopSymbolTable);
973 int labelScopeDepth() const;
974 UnlinkedArrayProfile newArrayProfile();
977 ParserError generate();
978 void reclaimFreeRegisters();
979 Variable variableForLocalEntry(const Identifier&, const SymbolTableEntry&, int symbolTableConstantIndex, bool isLexicallyScoped);
981 void emitOpcode(OpcodeID);
982 UnlinkedArrayAllocationProfile newArrayAllocationProfile();
983 UnlinkedObjectAllocationProfile newObjectAllocationProfile();
984 UnlinkedValueProfile emitProfiledOpcode(OpcodeID);
985 int kill(RegisterID* dst)
987 int index = dst->index();
988 m_staticPropertyAnalyzer.kill(index);
992 void retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index);
993 void retrieveLastUnaryOp(int& dstIndex, int& srcIndex);
994 ALWAYS_INLINE void rewindBinaryOp();
995 ALWAYS_INLINE void rewindUnaryOp();
997 void allocateCalleeSaveSpace();
998 void allocateAndEmitScope();
1000 typedef HashMap<double, JSValue> NumberMap;
1001 typedef HashMap<UniquedStringImpl*, JSString*, IdentifierRepHash> IdentifierStringMap;
1002 typedef HashMap<Ref<TemplateRegistryKey>, RegisterID*> TemplateRegistryKeyMap;
1004 // Helper for emitCall() and emitConstruct(). This works because the set of
1005 // expected functions have identical behavior for both call and construct
1006 // (i.e. "Object()" is identical to "new Object()").
1007 ExpectedFunction emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, Label& done);
1009 RegisterID* emitCall(OpcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1011 RegisterID* emitCallIterator(RegisterID* iterator, RegisterID* argument, ThrowableExpressionData*);
1012 RegisterID* newRegister();
1014 // Adds an anonymous local var slot. To give this slot a name, add it to symbolTable().
1015 RegisterID* addVar()
1017 ++m_codeBlock->m_numVars;
1018 RegisterID* result = newRegister();
1019 ASSERT(VirtualRegister(result->index()).toLocal() == m_codeBlock->m_numVars - 1);
1020 result->ref(); // We should never free this slot.
1024 // Initializes the stack form the parameter; does nothing for the symbol table.
1025 RegisterID* initializeNextParameter();
1026 UniquedStringImpl* visibleNameForParameter(DestructuringPatternNode*);
1028 RegisterID& registerFor(VirtualRegister reg)
1031 return m_calleeLocals[reg.toLocal()];
1033 if (reg.offset() == CallFrameSlot::callee)
1034 return m_calleeRegister;
1036 ASSERT(m_parameters.size());
1037 return m_parameters[reg.toArgument()];
1040 bool hasConstant(const Identifier&) const;
1041 unsigned addConstant(const Identifier&);
1042 RegisterID* addConstantValue(JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
1043 RegisterID* addConstantEmptyValue();
1044 unsigned addRegExp(RegExp*);
1046 unsigned addConstantBuffer(unsigned length);
1048 UnlinkedFunctionExecutable* makeFunction(FunctionMetadataNode* metadata)
1050 DerivedContextType newDerivedContextType = DerivedContextType::None;
1052 if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode, SourceParseMode::AsyncArrowFunctionBodyMode).contains(metadata->parseMode())) {
1053 if (constructorKind() == ConstructorKind::Extends || isDerivedConstructorContext())
1054 newDerivedContextType = DerivedContextType::DerivedConstructorContext;
1055 else if (m_codeBlock->isClassContext() || isDerivedClassContext())
1056 newDerivedContextType = DerivedContextType::DerivedMethodContext;
1059 VariableEnvironment variablesUnderTDZ;
1060 getVariablesUnderTDZ(variablesUnderTDZ);
1062 // FIXME: These flags, ParserModes and propagation to XXXCodeBlocks should be reorganized.
1063 // https://bugs.webkit.org/show_bug.cgi?id=151547
1064 SourceParseMode parseMode = metadata->parseMode();
1065 ConstructAbility constructAbility = constructAbilityForParseMode(parseMode);
1066 if (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() != ConstructorKind::None)
1067 constructAbility = ConstructAbility::CanConstruct;
1069 return UnlinkedFunctionExecutable::create(m_vm, m_scopeNode->source(), metadata, isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, constructAbility, scriptMode(), variablesUnderTDZ, newDerivedContextType);
1072 void getVariablesUnderTDZ(VariableEnvironment&);
1074 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);
1075 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);
1077 void emitLogShadowChickenPrologueIfNecessary();
1078 void emitLogShadowChickenTailIfNecessary();
1080 void initializeParameters(FunctionParameters&);
1081 void initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables);
1082 void initializeDefaultParameterValuesAndSetupFunctionScopeStack(FunctionParameters&, bool isSimpleParameterList, FunctionNode*, SymbolTable*, int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope);
1083 void initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable = nullptr, bool canReuseLexicalEnvironment = false);
1084 bool needsDerivedConstructorInArrowFunctionLexicalEnvironment();
1087 JSString* addStringConstant(const Identifier&);
1088 RegisterID* addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&&);
1090 Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>& instructions() { return m_instructions; }
1092 RegisterID* emitThrowExpressionTooDeepException();
1095 Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow> m_instructions;
1097 bool m_shouldEmitDebugHooks;
1099 struct LexicalScopeStackEntry {
1100 SymbolTable* m_symbolTable;
1101 RegisterID* m_scope;
1103 int m_symbolTableConstantIndex;
1105 Vector<LexicalScopeStackEntry> m_lexicalScopeStack;
1106 enum class TDZNecessityLevel {
1111 typedef HashMap<RefPtr<UniquedStringImpl>, TDZNecessityLevel, IdentifierRepHash> TDZMap;
1112 Vector<TDZMap> m_TDZStack;
1113 std::optional<size_t> m_varScopeLexicalScopeStackIndex;
1114 void pushTDZVariables(const VariableEnvironment&, TDZCheckOptimization, TDZRequirement);
1116 ScopeNode* const m_scopeNode;
1117 Strong<UnlinkedCodeBlock> m_codeBlock;
1119 // Some of these objects keep pointers to one another. They are arranged
1120 // to ensure a sane destruction order that avoids references to freed memory.
1121 HashSet<RefPtr<UniquedStringImpl>, IdentifierRepHash> m_functions;
1122 RegisterID m_ignoredResultRegister;
1123 RegisterID m_thisRegister;
1124 RegisterID m_calleeRegister;
1125 RegisterID* m_scopeRegister { nullptr };
1126 RegisterID* m_topMostScope { nullptr };
1127 RegisterID* m_argumentsRegister { nullptr };
1128 RegisterID* m_lexicalEnvironmentRegister { nullptr };
1129 RegisterID* m_generatorRegister { nullptr };
1130 RegisterID* m_emptyValueRegister { nullptr };
1131 RegisterID* m_globalObjectRegister { nullptr };
1132 RegisterID* m_newTargetRegister { nullptr };
1133 RegisterID* m_isDerivedConstuctor { nullptr };
1134 RegisterID* m_linkTimeConstantRegisters[LinkTimeConstantCount];
1135 RegisterID* m_arrowFunctionContextLexicalEnvironmentRegister { nullptr };
1136 RegisterID* m_promiseCapabilityRegister { nullptr };
1138 RefPtr<RegisterID> m_completionTypeRegister;
1139 RefPtr<RegisterID> m_completionValueRegister;
1141 FinallyContext* m_currentFinallyContext { nullptr };
1143 SegmentedVector<RegisterID*, 16> m_localRegistersForCalleeSaveRegisters;
1144 SegmentedVector<RegisterID, 32> m_constantPoolRegisters;
1145 SegmentedVector<RegisterID, 32> m_calleeLocals;
1146 SegmentedVector<RegisterID, 32> m_parameters;
1147 SegmentedVector<Label, 32> m_labels;
1148 SegmentedVector<LabelScope, 32> m_labelScopes;
1149 unsigned m_finallyDepth { 0 };
1150 int m_localScopeDepth { 0 };
1151 const CodeType m_codeType;
1153 int localScopeDepth() const;
1154 void pushLocalControlFlowScope();
1155 void popLocalControlFlowScope();
1157 // FIXME: Restore overflow checking with UnsafeVectorOverflow once SegmentVector supports it.
1158 // https://bugs.webkit.org/show_bug.cgi?id=165980
1159 SegmentedVector<ControlFlowScope, 16> m_controlFlowScopeStack;
1160 Vector<SwitchInfo> m_switchContextStack;
1161 Vector<Ref<ForInContext>> m_forInContextStack;
1162 Vector<TryContext> m_tryContextStack;
1163 unsigned m_yieldPoints { 0 };
1165 Strong<SymbolTable> m_generatorFrameSymbolTable;
1166 int m_generatorFrameSymbolTableIndex { 0 };
1168 enum FunctionVariableType : uint8_t { NormalFunctionVariable, TopLevelFunctionVariable };
1169 Vector<std::pair<FunctionMetadataNode*, FunctionVariableType>> m_functionsToInitialize;
1170 bool m_needToInitializeArguments { false };
1171 RestParameterNode* m_restParameter { nullptr };
1173 Vector<TryRange> m_tryRanges;
1174 SegmentedVector<TryData, 8> m_tryData;
1176 int m_nextConstantOffset { 0 };
1178 typedef HashMap<FunctionMetadataNode*, unsigned> FunctionOffsetMap;
1179 FunctionOffsetMap m_functionOffsets;
1182 IdentifierMap m_identifierMap;
1184 typedef HashMap<EncodedJSValueWithRepresentation, unsigned, EncodedJSValueWithRepresentationHash, EncodedJSValueWithRepresentationHashTraits> JSValueMap;
1185 JSValueMap m_jsValueMap;
1186 IdentifierStringMap m_stringMap;
1187 TemplateRegistryKeyMap m_templateRegistryKeyMap;
1189 StaticPropertyAnalyzer m_staticPropertyAnalyzer { &m_instructions };
1193 OpcodeID m_lastOpcodeID = op_end;
1195 size_t m_lastOpcodePosition { 0 };
1198 bool m_usesExceptions { false };
1199 bool m_expressionTooDeep { false };
1200 bool m_isBuiltinFunction { false };
1201 bool m_usesNonStrictEval { false };
1202 bool m_inTailPosition { false };
1203 bool m_needsToUpdateArrowFunctionContext;
1204 DerivedContextType m_derivedContextType { DerivedContextType::None };
1206 using CatchEntry = std::tuple<TryData*, int, int>;
1207 Vector<CatchEntry> m_catchesToEmit;
1214 void printInternal(PrintStream&, JSC::Variable::VariableKind);