Speculatively change iteration protocall to use the same next function
[WebKit-https.git] / Source / JavaScriptCore / bytecompiler / BytecodeGenerator.h
1 /*
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.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
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.
18  *
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.
29  */
30
31 #pragma once
32
33 #include "CodeBlock.h"
34 #include "Instruction.h"
35 #include "Interpreter.h"
36 #include "JSAsyncGeneratorFunction.h"
37 #include "JSGeneratorFunction.h"
38 #include "Label.h"
39 #include "LabelScope.h"
40 #include "Nodes.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"
47 #include <functional>
48 #include <wtf/CheckedArithmetic.h>
49 #include <wtf/SegmentedVector.h>
50 #include <wtf/SetForScope.h>
51 #include <wtf/Vector.h>
52
53 namespace JSC {
54
55     class Identifier;
56     class JSTemplateRegistryKey;
57
58     enum ExpectedFunction {
59         NoExpectedFunction,
60         ExpectObjectConstructor,
61         ExpectArrayConstructor
62     };
63
64     enum class EmitAwait { Yes, No };
65
66     enum class DebuggableCall { Yes, No };
67     enum class ThisResolutionType { Local, Scoped };
68     
69     class CallArguments {
70     public:
71         CallArguments(BytecodeGenerator&, ArgumentsNode*, unsigned additionalArguments = 0);
72
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; }
78
79     private:
80         ArgumentsNode* m_argumentsNode;
81         Vector<RefPtr<RegisterID>, 8, UnsafeVectorOverflow> m_argv;
82         unsigned m_padding;
83     };
84
85     // https://tc39.github.io/ecma262/#sec-completion-record-specification-type
86     //
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 {
95         Normal,
96         Break,
97         Continue,
98         Return,
99         Throw,
100         
101         NumberOfTypes
102     };
103
104     inline CompletionType bytecodeOffsetToJumpID(unsigned offset)
105     {
106         int jumpIDAsInt = offset + static_cast<int>(CompletionType::NumberOfTypes);
107         ASSERT(jumpIDAsInt >= static_cast<int>(CompletionType::NumberOfTypes));
108         return static_cast<CompletionType>(jumpIDAsInt);
109     }
110
111     struct FinallyJump {
112         FinallyJump(CompletionType jumpID, int targetLexicalScopeIndex, Label& targetLabel)
113             : jumpID(jumpID)
114             , targetLexicalScopeIndex(targetLexicalScopeIndex)
115             , targetLabel(targetLabel)
116         { }
117
118         CompletionType jumpID;
119         int targetLexicalScopeIndex;
120         Ref<Label> targetLabel;
121     };
122
123     struct FinallyContext {
124         FinallyContext() { }
125         FinallyContext(FinallyContext* outerContext, Label& finallyLabel)
126             : m_outerContext(outerContext)
127             , m_finallyLabel(&finallyLabel)
128         {
129             ASSERT(m_jumps.isEmpty());
130         }
131
132         FinallyContext* outerContext() const { return m_outerContext; }
133         Label* finallyLabel() const { return m_finallyLabel; }
134
135         uint32_t numberOfBreaksOrContinues() const { return m_numberOfBreaksOrContinues.unsafeGet(); }
136         void incNumberOfBreaksOrContinues() { m_numberOfBreaksOrContinues++; }
137
138         bool handlesReturns() const { return m_handlesReturns; }
139         void setHandlesReturns() { m_handlesReturns = true; }
140
141         void registerJump(CompletionType jumpID, int lexicalScopeIndex, Label& targetLabel)
142         {
143             m_jumps.append(FinallyJump(jumpID, lexicalScopeIndex, targetLabel));
144         }
145
146         size_t numberOfJumps() const { return m_jumps.size(); }
147         FinallyJump& jumps(size_t i) { return m_jumps[i]; }
148
149     private:
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;
155     };
156
157     struct ControlFlowScope {
158         typedef uint8_t Type;
159         enum {
160             Label,
161             Finally
162         };
163         ControlFlowScope(Type type, int lexicalScopeIndex, FinallyContext&& finallyContext = FinallyContext())
164             : type(type)
165             , lexicalScopeIndex(lexicalScopeIndex)
166             , finallyContext(std::forward<FinallyContext>(finallyContext))
167         { }
168
169         bool isLabelScope() const { return type == Label; }
170         bool isFinallyScope() const { return type == Finally; }
171
172         Type type;
173         int lexicalScopeIndex;
174         FinallyContext finallyContext;
175     };
176
177     class ForInContext : public RefCounted<ForInContext> {
178         WTF_MAKE_FAST_ALLOCATED;
179         WTF_MAKE_NONCOPYABLE(ForInContext);
180     public:
181         ForInContext(RegisterID* localRegister)
182             : m_localRegister(localRegister)
183             , m_isValid(true)
184         {
185         }
186
187         virtual ~ForInContext()
188         {
189         }
190
191         bool isValid() const { return m_isValid; }
192         void invalidate() { m_isValid = false; }
193
194         enum ForInContextType {
195             StructureForInContextType,
196             IndexedForInContextType
197         };
198         virtual ForInContextType type() const = 0;
199
200         RegisterID* local() const { return m_localRegister.get(); }
201
202     private:
203         RefPtr<RegisterID> m_localRegister;
204         bool m_isValid;
205     };
206
207     class StructureForInContext : public ForInContext {
208     public:
209         using GetInst = std::tuple<unsigned, int, UnlinkedValueProfile>;
210
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)
216         {
217         }
218
219         ForInContextType type() const override
220         {
221             return StructureForInContextType;
222         }
223
224         RegisterID* index() const { return m_indexRegister.get(); }
225         RegisterID* property() const { return m_propertyRegister.get(); }
226         RegisterID* enumerator() const { return m_enumeratorRegister.get(); }
227
228         void addGetInst(unsigned instIndex, int propertyRegIndex, UnlinkedValueProfile valueProfile)
229         {
230             m_getInsts.append(GetInst { instIndex, propertyRegIndex, valueProfile });
231         }
232
233         void finalize(BytecodeGenerator&);
234
235     private:
236         RefPtr<RegisterID> m_indexRegister;
237         RefPtr<RegisterID> m_propertyRegister;
238         RefPtr<RegisterID> m_enumeratorRegister;
239         Vector<GetInst> m_getInsts;
240     };
241
242     class IndexedForInContext : public ForInContext {
243     public:
244         IndexedForInContext(RegisterID* localRegister, RegisterID* indexRegister)
245             : ForInContext(localRegister)
246             , m_indexRegister(indexRegister)
247         {
248         }
249
250         ForInContextType type() const override
251         {
252             return IndexedForInContextType;
253         }
254
255         RegisterID* index() const { return m_indexRegister.get(); }
256
257         void finalize(BytecodeGenerator&);
258         void addGetInst(unsigned instIndex, int propertyIndex) { m_getInsts.append({ instIndex, propertyIndex }); }
259
260     private:
261         RefPtr<RegisterID> m_indexRegister;
262         Vector<std::pair<unsigned, int>> m_getInsts;
263     };
264
265     struct TryData {
266         Ref<Label> target;
267         HandlerType handlerType;
268     };
269
270     struct TryContext {
271         Ref<Label> start;
272         TryData* tryData;
273     };
274
275     class Variable {
276     public:
277         enum VariableKind { NormalVariable, SpecialVariable };
278
279         Variable()
280             : m_offset()
281             , m_local(nullptr)
282             , m_attributes(0)
283             , m_kind(NormalVariable)
284             , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
285             , m_isLexicallyScoped(false)
286         {
287         }
288         
289         Variable(const Identifier& ident)
290             : m_ident(ident)
291             , m_local(nullptr)
292             , m_attributes(0)
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)
296         {
297         }
298
299         Variable(const Identifier& ident, VarOffset offset, RegisterID* local, unsigned attributes, VariableKind kind, int symbolTableConstantIndex, bool isLexicallyScoped)
300             : m_ident(ident)
301             , m_offset(offset)
302             , m_local(local)
303             , m_attributes(attributes)
304             , m_kind(kind)
305             , m_symbolTableConstantIndex(symbolTableConstantIndex)
306             , m_isLexicallyScoped(isLexicallyScoped)
307         {
308         }
309
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; }
315         
316         const Identifier& ident() const { return m_ident; }
317         
318         VarOffset offset() const { return m_offset; }
319         bool isLocal() const { return m_offset.isStack(); }
320         RegisterID* local() const { return m_local; }
321
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; }
326
327         void dump(PrintStream&) const;
328
329     private:
330         Identifier m_ident;
331         VarOffset m_offset;
332         RegisterID* m_local;
333         unsigned m_attributes;
334         VariableKind m_kind;
335         int m_symbolTableConstantIndex;
336         bool m_isLexicallyScoped;
337     };
338
339     struct TryRange {
340         Ref<Label> start;
341         Ref<Label> end;
342         TryData* tryData;
343     };
344
345     enum ProfileTypeBytecodeFlag {
346         ProfileTypeBytecodeClosureVar,
347         ProfileTypeBytecodeLocallyResolved,
348         ProfileTypeBytecodeDoesNotHaveGlobalID,
349         ProfileTypeBytecodeFunctionArgument,
350         ProfileTypeBytecodeFunctionReturnStatement
351     };
352
353     class BytecodeGenerator {
354         WTF_MAKE_FAST_ALLOCATED;
355         WTF_MAKE_NONCOPYABLE(BytecodeGenerator);
356     public:
357         typedef DeclarationStacks::FunctionStack FunctionStack;
358
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*);
363
364         ~BytecodeGenerator();
365         
366         VM* vm() const { return m_vm; }
367         ParserArena& parserArena() const { return m_scopeNode->parserArena(); }
368         const CommonIdentifiers& propertyNames() const { return *m_vm->propertyNames; }
369
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(); }
379
380         template<typename... Args>
381         static ParserError generate(VM& vm, Args&& ...args)
382         {
383             DeferGC deferGC(vm.heap);
384             auto bytecodeGenerator = std::make_unique<BytecodeGenerator>(vm, std::forward<Args>(args)...);
385             return bytecodeGenerator->generate(); 
386         }
387
388         bool isArgumentNumber(const Identifier&, int);
389
390         Variable variable(const Identifier&, ThisResolutionType = ThisResolutionType::Local);
391         
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.
394         
395         // Returns the register storing "this"
396         RegisterID* thisRegister() { return &m_thisRegister; }
397         RegisterID* argumentsRegister() { return m_argumentsRegister; }
398         RegisterID* newTarget()
399         {
400             return m_newTargetRegister;
401         }
402
403         RegisterID* scopeRegister() { return m_scopeRegister; }
404
405         RegisterID* generatorRegister() { return m_generatorRegister; }
406
407         RegisterID* promiseCapabilityRegister() { return m_promiseCapabilityRegister; }
408
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();
414
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(); }
420
421         // Functions for handling of dst register
422
423         RegisterID* ignoredResult() { return &m_ignoredResultRegister; }
424
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();
431
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)
435         {
436             return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary();
437         }
438
439         // Returns the place to write the final output of an operation.
440         RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0)
441         {
442             if (originalDst && originalDst != ignoredResult())
443                 return originalDst;
444             ASSERT(tempDst != ignoredResult());
445             if (tempDst && tempDst->isTemporary())
446                 return tempDst;
447             return newTemporary();
448         }
449
450         RegisterID* destinationForAssignResult(RegisterID* dst)
451         {
452             if (dst && dst != ignoredResult())
453                 return dst->isTemporary() ? dst : newTemporary();
454             return 0;
455         }
456
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)
459         {
460             return dst == ignoredResult() ? 0 : (dst && dst != src) ? emitMove(dst, src) : src;
461         }
462
463         Ref<LabelScope> newLabelScope(LabelScope::Type, const Identifier* = 0);
464         Ref<Label> newLabel();
465         Ref<Label> newEmittedLabel();
466
467         void emitNode(RegisterID* dst, StatementNode* n)
468         {
469             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
470             return emitNodeInTailPosition(dst, n);
471         }
472
473         void emitNodeInTailPosition(RegisterID* dst, StatementNode* n)
474         {
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();
479                 return;
480             }
481             if (UNLIKELY(n->needsDebugHook()))
482                 emitDebugHook(n);
483             n->emitBytecode(*this, dst);
484         }
485
486         void emitNode(StatementNode* n)
487         {
488             emitNode(nullptr, n);
489         }
490
491         void emitNodeInTailPosition(StatementNode* n)
492         {
493             emitNodeInTailPosition(nullptr, n);
494         }
495
496         RegisterID* emitNode(RegisterID* dst, ExpressionNode* n)
497         {
498             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
499             return emitNodeInTailPosition(dst, n);
500         }
501
502         RegisterID* emitNodeInTailPosition(RegisterID* dst, ExpressionNode* n)
503         {
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()))
509                 emitDebugHook(n);
510             return n->emitBytecode(*this, dst);
511         }
512
513         RegisterID* emitNode(ExpressionNode* n)
514         {
515             return emitNode(nullptr, n);
516         }
517
518         RegisterID* emitNodeInTailPosition(ExpressionNode* n)
519         {
520             return emitNodeInTailPosition(nullptr, n);
521         }
522
523         RegisterID* emitNodeForProperty(RegisterID* dst, ExpressionNode* node)
524         {
525             if (node->isString()) {
526                 if (std::optional<uint32_t> index = parseIndex(static_cast<StringNode*>(node)->value()))
527                     return emitLoad(dst, jsNumber(index.value()));
528             }
529             return emitNode(dst, node);
530         }
531
532         RegisterID* emitNodeForProperty(ExpressionNode* n)
533         {
534             return emitNodeForProperty(nullptr, n);
535         }
536
537         void emitNodeInConditionContext(ExpressionNode* n, Label& trueTarget, Label& falseTarget, FallThroughMode fallThroughMode)
538         {
539             if (UNLIKELY(!m_vm->isSafeToRecurse())) {
540                 emitThrowExpressionTooDeepException();
541                 return;
542             }
543             n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMode);
544         }
545
546         void emitExpressionInfo(const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
547         {            
548             ASSERT(divot.offset >= divotStart.offset);
549             ASSERT(divotEnd.offset >= divot.offset);
550
551             int sourceOffset = m_scopeNode->source().startOffset();
552             unsigned firstLine = m_scopeNode->source().firstLine().oneBasedInt();
553
554             int divotOffset = divot.offset - sourceOffset;
555             int startOffset = divot.offset - divotStart.offset;
556             int endOffset = divotEnd.offset - divot.offset;
557
558             unsigned line = divot.line;
559             ASSERT(line >= firstLine);
560             line -= firstLine;
561
562             int lineStart = divot.lineStartOffset;
563             if (lineStart > sourceOffset)
564                 lineStart -= sourceOffset;
565             else
566                 lineStart = 0;
567
568             if (divotOffset < lineStart)
569                 return;
570
571             unsigned column = divotOffset - lineStart;
572
573             unsigned instructionOffset = instructions().size();
574             if (!m_isBuiltinFunction)
575                 m_codeBlock->addExpressionInfo(instructionOffset, divotOffset, startOffset, endOffset, line, column);
576         }
577
578
579         ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure)
580         {
581             return (m_codeType != FunctionCode || rightHasAssignments) && !rightIsPure;
582         }
583
584         ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
585         {
586             if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
587                 RefPtr<RegisterID> dst = newTemporary();
588                 emitNode(dst.get(), n);
589                 return dst;
590             }
591
592             return emitNode(n);
593         }
594
595         ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSideForProperty(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
596         {
597             if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
598                 RefPtr<RegisterID> dst = newTemporary();
599                 emitNodeForProperty(dst.get(), n);
600                 return dst;
601             }
602
603             return emitNodeForProperty(n);
604         }
605
606         void hoistSloppyModeFunctionIfNecessary(const Identifier& functionName);
607
608     private:
609         void emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot);
610         RegisterID* emitCreateAsyncGeneratorQueue(const JSTextPosition&);
611     public:
612
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);
617
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);
621
622         void emitProfileControlFlow(int);
623         
624         RegisterID* emitLoadArrowFunctionLexicalEnvironment(const Identifier&);
625         RegisterID* ensureThis();
626         void emitLoadThisFromArrowFunctionLexicalEnvironment();
627         RegisterID* emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
628
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);
635
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);
642
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);
652
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*);
659
660         void emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name);
661
662         RegisterID* emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant);
663         RegisterID* emitMoveEmptyValue(RegisterID* dst);
664         RegisterID* emitMove(RegisterID* dst, RegisterID* src);
665
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);
670
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);
676
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);
691
692         RegisterID* emitAssert(RegisterID* condition, int line);
693         RegisterID* emitIdWithProfile(RegisterID* src, SpeculatedType profile);
694         void emitUnreachable();
695
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);
701
702         RegisterID* emitGetArgument(RegisterID* dst, int32_t index);
703
704         // Initialize object with generator fields (@generatorThis, @generatorNext, @generatorState, @generatorFrame)
705         void emitPutGeneratorFields(RegisterID* nextFunction);
706         
707         void emitPutAsyncGeneratorFields(RegisterID* nextFunction, const JSTextPosition&);
708
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);
716
717         enum PropertyDescriptorOption {
718             PropertyConfigurable = 1,
719             PropertyWritable     = 1 << 1,
720             PropertyEnumerable   = 1 << 2,
721         };
722         void emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
723             RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition&);
724
725         void emitEnumeration(ThrowableExpressionData* enumerationNode, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, ForOfNode* = nullptr, RegisterID* forLoopSymbolTable = nullptr);
726
727         RegisterID* emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode*);
728         RegisterID* emitGetGlobalPrivate(RegisterID* dst, const Identifier& property);
729
730         enum class ReturnFrom { Normal, Finally };
731         RegisterID* emitReturn(RegisterID* src, ReturnFrom = ReturnFrom::Normal);
732         RegisterID* emitEnd(RegisterID* src) { return emitUnaryNoDstOp(op_end, src); }
733
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);
737
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);
743
744         RegisterID* emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier&);
745
746         RegisterID* initializeVariable(const Variable&, RegisterID* value);
747
748         void emitLabel(Label&);
749         void emitLoopHint();
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);
755
756         void emitEnter();
757         void emitCheckTraps();
758
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);
769
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);
782
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);
786
787         RegisterID* emitRestParameter(RegisterID* result, unsigned numParametersToSkip);
788
789         bool emitReadOnlyExceptionIfNeeded(const Variable&);
790
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*);
796
797     private:
798         static const int CurrentLexicalScopeIndex = -2;
799         static const int OutermostLexicalScopeIndex = -1;
800
801         int currentLexicalScopeIndex() const
802         {
803             int size = static_cast<int>(m_lexicalScopeStack.size());
804             ASSERT(static_cast<size_t>(size) == m_lexicalScopeStack.size());
805             ASSERT(size >= 0);
806             if (!size)
807                 return OutermostLexicalScopeIndex;
808             return size - 1;
809         }
810
811     public:
812         void restoreScopeRegister();
813         void restoreScopeRegister(int lexicalScopeIndex);
814
815         int labelScopeDepthToLexicalScopeIndex(int labelScopeDepth);
816
817         void emitThrow(RegisterID* exc)
818         { 
819             m_usesExceptions = true;
820             emitUnaryNoDstOp(op_throw, exc);
821         }
822
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();
830
831         void emitPushCatchScope(VariableEnvironment&);
832         void emitPopCatchScope(VariableEnvironment&);
833
834         RegisterID* emitGetIterator(RegisterID*, ThrowableExpressionData*);
835         RegisterID* emitGetAsyncIterator(RegisterID*, ThrowableExpressionData*);
836
837         void emitAwait(RegisterID*);
838         void emitGetScope();
839         RegisterID* emitPushWithScope(RegisterID* objectScope);
840         void emitPopWithScope();
841         void emitPutThisToArrowFunctionContextScope();
842         void emitPutNewTargetToArrowFunctionContextScope();
843         void emitPutDerivedConstructorToArrowFunctionContextScope();
844         RegisterID* emitLoadDerivedConstructorFromArrowFunctionLexicalEnvironment();
845
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();
851
852         class CompletionRecordScope {
853         public:
854             CompletionRecordScope(BytecodeGenerator& generator, bool needCompletionRecordRegisters = true)
855                 : m_generator(generator)
856             {
857                 if (needCompletionRecordRegisters && m_generator.allocateCompletionRecordRegisters())
858                     m_needToReleaseOnDestruction = true;
859             }
860             ~CompletionRecordScope()
861             {
862                 if (m_needToReleaseOnDestruction)
863                     m_generator.releaseCompletionRecordRegisters();
864             }
865
866         private:
867             BytecodeGenerator& m_generator;
868             bool m_needToReleaseOnDestruction { false };
869         };
870
871         RegisterID* completionTypeRegister() const
872         {
873             ASSERT(m_completionTypeRegister);
874             return m_completionTypeRegister.get();
875         }
876         RegisterID* completionValueRegister() const
877         {
878             ASSERT(m_completionValueRegister);
879             return m_completionValueRegister.get();
880         }
881
882         void emitSetCompletionType(CompletionType type)
883         {
884             emitLoad(completionTypeRegister(), JSValue(static_cast<int>(type)));
885         }
886         void emitSetCompletionValue(RegisterID* reg)
887         {
888             emitMove(completionValueRegister(), reg);
889         }
890
891         void emitJumpIf(OpcodeID compareOpcode, RegisterID* completionTypeRegister, CompletionType, Label& jumpTarget);
892
893         bool emitJumpViaFinallyIfNeeded(int targetLabelScopeDepth, Label& jumpTarget);
894         bool emitReturnViaFinallyIfNeeded(RegisterID* returnRegister);
895         void emitFinallyCompletion(FinallyContext&, RegisterID* completionTypeRegister, Label& normalCompletionLabel);
896
897     private:
898         bool allocateCompletionRecordRegisters();
899         void releaseCompletionRecordRegisters();
900
901     public:
902         FinallyContext* pushFinallyControlFlowScope(Label& finallyLabel);
903         FinallyContext popFinallyControlFlowScope();
904
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);
910
911         LabelScope* breakTarget(const Identifier&);
912         LabelScope* continueTarget(const Identifier&);
913
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);
916
917         void emitYieldPoint(RegisterID*, JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason);
918
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)]; }
927
928         CodeType codeType() const { return m_codeType; }
929
930         bool shouldBeConcernedWithCompletionValue() const { return m_codeType != FunctionCode; }
931
932         bool shouldEmitDebugHooks() const { return m_shouldEmitDebugHooks; }
933         
934         bool isStrictMode() const { return m_codeBlock->isStrictMode(); }
935
936         SourceParseMode parseMode() const { return m_codeBlock->parseMode(); }
937         
938         bool isBuiltinFunction() const { return m_isBuiltinFunction; }
939
940         OpcodeID lastOpcodeID() const { return m_lastOpcodeID; }
941         
942         bool isDerivedConstructorContext() { return m_derivedContextType == DerivedContextType::DerivedConstructorContext; }
943         bool isDerivedClassContext() { return m_derivedContextType == DerivedContextType::DerivedMethodContext; }
944         bool isArrowFunction() { return m_codeBlock->isArrowFunction(); }
945
946         enum class TDZCheckOptimization { Optimize, DoNotOptimize };
947         enum class NestedScopeType { IsNested, IsNotNested };
948     private:
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*);
962         
963         bool isNewTargetUsedInInnerArrowFunction();
964         bool isArgumentsUsedInInnerArrowFunction();
965
966     public:
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();
975
976     private:
977         ParserError generate();
978         void reclaimFreeRegisters();
979         Variable variableForLocalEntry(const Identifier&, const SymbolTableEntry&, int symbolTableConstantIndex, bool isLexicallyScoped);
980
981         void emitOpcode(OpcodeID);
982         UnlinkedArrayAllocationProfile newArrayAllocationProfile();
983         UnlinkedObjectAllocationProfile newObjectAllocationProfile();
984         UnlinkedValueProfile emitProfiledOpcode(OpcodeID);
985         int kill(RegisterID* dst)
986         {
987             int index = dst->index();
988             m_staticPropertyAnalyzer.kill(index);
989             return index;
990         }
991
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();
996
997         void allocateCalleeSaveSpace();
998         void allocateAndEmitScope();
999
1000         typedef HashMap<double, JSValue> NumberMap;
1001         typedef HashMap<UniquedStringImpl*, JSString*, IdentifierRepHash> IdentifierStringMap;
1002         typedef HashMap<Ref<TemplateRegistryKey>, RegisterID*> TemplateRegistryKeyMap;
1003         
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);
1008         
1009         RegisterID* emitCall(OpcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1010
1011         RegisterID* emitCallIterator(RegisterID* iterator, RegisterID* argument, ThrowableExpressionData*);
1012         RegisterID* newRegister();
1013
1014         // Adds an anonymous local var slot. To give this slot a name, add it to symbolTable().
1015         RegisterID* addVar()
1016         {
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.
1021             return result;
1022         }
1023
1024         // Initializes the stack form the parameter; does nothing for the symbol table.
1025         RegisterID* initializeNextParameter();
1026         UniquedStringImpl* visibleNameForParameter(DestructuringPatternNode*);
1027         
1028         RegisterID& registerFor(VirtualRegister reg)
1029         {
1030             if (reg.isLocal())
1031                 return m_calleeLocals[reg.toLocal()];
1032
1033             if (reg.offset() == CallFrameSlot::callee)
1034                 return m_calleeRegister;
1035
1036             ASSERT(m_parameters.size());
1037             return m_parameters[reg.toArgument()];
1038         }
1039
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*);
1045
1046         unsigned addConstantBuffer(unsigned length);
1047         
1048         UnlinkedFunctionExecutable* makeFunction(FunctionMetadataNode* metadata)
1049         {
1050             DerivedContextType newDerivedContextType = DerivedContextType::None;
1051
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;
1057             }
1058
1059             VariableEnvironment variablesUnderTDZ;
1060             getVariablesUnderTDZ(variablesUnderTDZ);
1061
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;
1068
1069             return UnlinkedFunctionExecutable::create(m_vm, m_scopeNode->source(), metadata, isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, constructAbility, scriptMode(), variablesUnderTDZ, newDerivedContextType);
1070         }
1071
1072         void getVariablesUnderTDZ(VariableEnvironment&);
1073
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);
1076         
1077         void emitLogShadowChickenPrologueIfNecessary();
1078         void emitLogShadowChickenTailIfNecessary();
1079
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();
1085
1086     public:
1087         JSString* addStringConstant(const Identifier&);
1088         RegisterID* addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&&);
1089
1090         Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>& instructions() { return m_instructions; }
1091
1092         RegisterID* emitThrowExpressionTooDeepException();
1093
1094     private:
1095         Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow> m_instructions;
1096
1097         bool m_shouldEmitDebugHooks;
1098
1099         struct LexicalScopeStackEntry {
1100             SymbolTable* m_symbolTable;
1101             RegisterID* m_scope;
1102             bool m_isWithScope;
1103             int m_symbolTableConstantIndex;
1104         };
1105         Vector<LexicalScopeStackEntry> m_lexicalScopeStack;
1106         enum class TDZNecessityLevel {
1107             NotNeeded,
1108             Optimize,
1109             DoNotOptimize
1110         };
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);
1115
1116         ScopeNode* const m_scopeNode;
1117         Strong<UnlinkedCodeBlock> m_codeBlock;
1118
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 };
1137
1138         RefPtr<RegisterID> m_completionTypeRegister;
1139         RefPtr<RegisterID> m_completionValueRegister;
1140
1141         FinallyContext* m_currentFinallyContext { nullptr };
1142
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;
1152
1153         int localScopeDepth() const;
1154         void pushLocalControlFlowScope();
1155         void popLocalControlFlowScope();
1156
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 };
1164
1165         Strong<SymbolTable> m_generatorFrameSymbolTable;
1166         int m_generatorFrameSymbolTableIndex { 0 };
1167
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 };
1172         
1173         Vector<TryRange> m_tryRanges;
1174         SegmentedVector<TryData, 8> m_tryData;
1175
1176         int m_nextConstantOffset { 0 };
1177
1178         typedef HashMap<FunctionMetadataNode*, unsigned> FunctionOffsetMap;
1179         FunctionOffsetMap m_functionOffsets;
1180         
1181         // Constant pool
1182         IdentifierMap m_identifierMap;
1183
1184         typedef HashMap<EncodedJSValueWithRepresentation, unsigned, EncodedJSValueWithRepresentationHash, EncodedJSValueWithRepresentationHashTraits> JSValueMap;
1185         JSValueMap m_jsValueMap;
1186         IdentifierStringMap m_stringMap;
1187         TemplateRegistryKeyMap m_templateRegistryKeyMap;
1188
1189         StaticPropertyAnalyzer m_staticPropertyAnalyzer { &m_instructions };
1190
1191         VM* m_vm;
1192
1193         OpcodeID m_lastOpcodeID = op_end;
1194 #ifndef NDEBUG
1195         size_t m_lastOpcodePosition { 0 };
1196 #endif
1197
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 };
1205
1206         using CatchEntry = std::tuple<TryData*, int, int>;
1207         Vector<CatchEntry> m_catchesToEmit;
1208     };
1209
1210 } // namespace JSC
1211
1212 namespace WTF {
1213
1214 void printInternal(PrintStream&, JSC::Variable::VariableKind);
1215
1216 } // namespace WTF