Unreviewed, rolling out r215476.
[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 "JSGeneratorFunction.h"
37 #include "Label.h"
38 #include "LabelScope.h"
39 #include "Nodes.h"
40 #include "ParserError.h"
41 #include "RegisterID.h"
42 #include "StaticPropertyAnalyzer.h"
43 #include "SymbolTable.h"
44 #include "TemplateRegistryKey.h"
45 #include "UnlinkedCodeBlock.h"
46 #include <functional>
47 #include <wtf/CheckedArithmetic.h>
48 #include <wtf/HashTraits.h>
49 #include <wtf/SegmentedVector.h>
50 #include <wtf/SetForScope.h>
51 #include <wtf/Vector.h>
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 DebuggableCall { Yes, No };
65     enum class ThisResolutionType { Local, Scoped };
66     
67     class CallArguments {
68     public:
69         CallArguments(BytecodeGenerator&, ArgumentsNode*, unsigned additionalArguments = 0);
70
71         RegisterID* thisRegister() { return m_argv[0].get(); }
72         RegisterID* argumentRegister(unsigned i) { return m_argv[i + 1].get(); }
73         unsigned stackOffset() { return -m_argv[0]->index() + CallFrame::headerSizeInRegisters; }
74         unsigned argumentCountIncludingThis() { return m_argv.size() - m_padding; }
75         ArgumentsNode* argumentsNode() { return m_argumentsNode; }
76
77     private:
78         ArgumentsNode* m_argumentsNode;
79         Vector<RefPtr<RegisterID>, 8, UnsafeVectorOverflow> m_argv;
80         unsigned m_padding;
81     };
82
83     // https://tc39.github.io/ecma262/#sec-completion-record-specification-type
84     //
85     // For the Break and Continue cases, instead of using the Break and Continue enum values
86     // below, we use the unique jumpID of the break and continue statement as the encoding
87     // for the CompletionType value. emitFinallyCompletion() uses this jumpID value later
88     // to determine the appropriate jump target to jump to after executing the relevant finally
89     // blocks. The jumpID is computed as:
90     //     jumpID = bytecodeOffset (of the break/continue node) + CompletionType::NumberOfTypes.
91     // Hence, there won't be any collision between jumpIDs and CompletionType enums.
92     enum class CompletionType : int {
93         Normal,
94         Break,
95         Continue,
96         Return,
97         Throw,
98         
99         NumberOfTypes
100     };
101
102     inline CompletionType bytecodeOffsetToJumpID(unsigned offset)
103     {
104         int jumpIDAsInt = offset + static_cast<int>(CompletionType::NumberOfTypes);
105         ASSERT(jumpIDAsInt >= static_cast<int>(CompletionType::NumberOfTypes));
106         return static_cast<CompletionType>(jumpIDAsInt);
107     }
108
109     struct FinallyJump {
110         FinallyJump(CompletionType jumpID, int targetLexicalScopeIndex, Label& targetLabel)
111             : jumpID(jumpID)
112             , targetLexicalScopeIndex(targetLexicalScopeIndex)
113             , targetLabel(targetLabel)
114         { }
115
116         CompletionType jumpID;
117         int targetLexicalScopeIndex;
118         Ref<Label> targetLabel;
119     };
120
121     struct FinallyContext {
122         FinallyContext() { }
123         FinallyContext(FinallyContext* outerContext, Label& finallyLabel)
124             : m_outerContext(outerContext)
125             , m_finallyLabel(&finallyLabel)
126         {
127             ASSERT(m_jumps.isEmpty());
128         }
129
130         FinallyContext* outerContext() const { return m_outerContext; }
131         Label* finallyLabel() const { return m_finallyLabel; }
132
133         uint32_t numberOfBreaksOrContinues() const { return m_numberOfBreaksOrContinues.unsafeGet(); }
134         void incNumberOfBreaksOrContinues() { m_numberOfBreaksOrContinues++; }
135
136         bool handlesReturns() const { return m_handlesReturns; }
137         void setHandlesReturns() { m_handlesReturns = true; }
138
139         void registerJump(CompletionType jumpID, int lexicalScopeIndex, Label& targetLabel)
140         {
141             m_jumps.append(FinallyJump(jumpID, lexicalScopeIndex, targetLabel));
142         }
143
144         size_t numberOfJumps() const { return m_jumps.size(); }
145         FinallyJump& jumps(size_t i) { return m_jumps[i]; }
146
147     private:
148         FinallyContext* m_outerContext { nullptr };
149         Label* m_finallyLabel { nullptr };
150         Checked<uint32_t, WTF::CrashOnOverflow> m_numberOfBreaksOrContinues;
151         bool m_handlesReturns { false };
152         Vector<FinallyJump> m_jumps;
153     };
154
155     struct ControlFlowScope {
156         typedef uint8_t Type;
157         enum {
158             Label,
159             Finally
160         };
161         ControlFlowScope(Type type, int lexicalScopeIndex, FinallyContext&& finallyContext = FinallyContext())
162             : type(type)
163             , lexicalScopeIndex(lexicalScopeIndex)
164             , finallyContext(std::forward<FinallyContext>(finallyContext))
165         { }
166
167         bool isLabelScope() const { return type == Label; }
168         bool isFinallyScope() const { return type == Finally; }
169
170         Type type;
171         int lexicalScopeIndex;
172         FinallyContext finallyContext;
173     };
174
175     class ForInContext : public RefCounted<ForInContext> {
176         WTF_MAKE_FAST_ALLOCATED;
177         WTF_MAKE_NONCOPYABLE(ForInContext);
178     public:
179         ForInContext(RegisterID* localRegister)
180             : m_localRegister(localRegister)
181             , m_isValid(true)
182         {
183         }
184
185         virtual ~ForInContext()
186         {
187         }
188
189         bool isValid() const { return m_isValid; }
190         void invalidate() { m_isValid = false; }
191
192         enum ForInContextType {
193             StructureForInContextType,
194             IndexedForInContextType
195         };
196         virtual ForInContextType type() const = 0;
197
198         RegisterID* local() const { return m_localRegister.get(); }
199
200     private:
201         RefPtr<RegisterID> m_localRegister;
202         bool m_isValid;
203     };
204
205     class StructureForInContext : public ForInContext {
206     public:
207         StructureForInContext(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister)
208             : ForInContext(localRegister)
209             , m_indexRegister(indexRegister)
210             , m_propertyRegister(propertyRegister)
211             , m_enumeratorRegister(enumeratorRegister)
212         {
213         }
214
215         ForInContextType type() const override
216         {
217             return StructureForInContextType;
218         }
219
220         RegisterID* index() const { return m_indexRegister.get(); }
221         RegisterID* property() const { return m_propertyRegister.get(); }
222         RegisterID* enumerator() const { return m_enumeratorRegister.get(); }
223
224     private:
225         RefPtr<RegisterID> m_indexRegister;
226         RefPtr<RegisterID> m_propertyRegister;
227         RefPtr<RegisterID> m_enumeratorRegister;
228     };
229
230     class IndexedForInContext : public ForInContext {
231     public:
232         IndexedForInContext(RegisterID* localRegister, RegisterID* indexRegister)
233             : ForInContext(localRegister)
234             , m_indexRegister(indexRegister)
235         {
236         }
237
238         ForInContextType type() const override
239         {
240             return IndexedForInContextType;
241         }
242
243         RegisterID* index() const { return m_indexRegister.get(); }
244
245     private:
246         RefPtr<RegisterID> m_indexRegister;
247     };
248
249     struct TryData {
250         Ref<Label> target;
251         HandlerType handlerType;
252     };
253
254     struct TryContext {
255         Ref<Label> start;
256         TryData* tryData;
257     };
258
259     class Variable {
260     public:
261         enum VariableKind { NormalVariable, SpecialVariable };
262
263         Variable()
264             : m_offset()
265             , m_local(nullptr)
266             , m_attributes(0)
267             , m_kind(NormalVariable)
268             , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
269             , m_isLexicallyScoped(false)
270         {
271         }
272         
273         Variable(const Identifier& ident)
274             : m_ident(ident)
275             , m_local(nullptr)
276             , m_attributes(0)
277             , m_kind(NormalVariable) // This is somewhat meaningless here for this kind of Variable.
278             , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
279             , m_isLexicallyScoped(false)
280         {
281         }
282
283         Variable(const Identifier& ident, VarOffset offset, RegisterID* local, unsigned attributes, VariableKind kind, int symbolTableConstantIndex, bool isLexicallyScoped)
284             : m_ident(ident)
285             , m_offset(offset)
286             , m_local(local)
287             , m_attributes(attributes)
288             , m_kind(kind)
289             , m_symbolTableConstantIndex(symbolTableConstantIndex)
290             , m_isLexicallyScoped(isLexicallyScoped)
291         {
292         }
293
294         // If it's unset, then it is a non-locally-scoped variable. If it is set, then it could be
295         // a stack variable, a scoped variable in a local scope, or a variable captured in the
296         // direct arguments object.
297         bool isResolved() const { return !!m_offset; }
298         int symbolTableConstantIndex() const { ASSERT(isResolved() && !isSpecial()); return m_symbolTableConstantIndex; }
299         
300         const Identifier& ident() const { return m_ident; }
301         
302         VarOffset offset() const { return m_offset; }
303         bool isLocal() const { return m_offset.isStack(); }
304         RegisterID* local() const { return m_local; }
305
306         bool isReadOnly() const { return m_attributes & ReadOnly; }
307         bool isSpecial() const { return m_kind != NormalVariable; }
308         bool isConst() const { return isReadOnly() && m_isLexicallyScoped; }
309         void setIsReadOnly() { m_attributes |= ReadOnly; }
310
311         void dump(PrintStream&) const;
312
313     private:
314         Identifier m_ident;
315         VarOffset m_offset;
316         RegisterID* m_local;
317         unsigned m_attributes;
318         VariableKind m_kind;
319         int m_symbolTableConstantIndex;
320         bool m_isLexicallyScoped;
321     };
322
323     struct TryRange {
324         Ref<Label> start;
325         Ref<Label> end;
326         TryData* tryData;
327     };
328
329     enum ProfileTypeBytecodeFlag {
330         ProfileTypeBytecodeClosureVar,
331         ProfileTypeBytecodeLocallyResolved,
332         ProfileTypeBytecodeDoesNotHaveGlobalID,
333         ProfileTypeBytecodeFunctionArgument,
334         ProfileTypeBytecodeFunctionReturnStatement
335     };
336
337     class BytecodeGenerator {
338         WTF_MAKE_FAST_ALLOCATED;
339         WTF_MAKE_NONCOPYABLE(BytecodeGenerator);
340     public:
341         typedef DeclarationStacks::FunctionStack FunctionStack;
342
343         BytecodeGenerator(VM&, ProgramNode*, UnlinkedProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
344         BytecodeGenerator(VM&, FunctionNode*, UnlinkedFunctionCodeBlock*, DebuggerMode, const VariableEnvironment*);
345         BytecodeGenerator(VM&, EvalNode*, UnlinkedEvalCodeBlock*, DebuggerMode, const VariableEnvironment*);
346         BytecodeGenerator(VM&, ModuleProgramNode*, UnlinkedModuleProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
347
348         ~BytecodeGenerator();
349         
350         VM* vm() const { return m_vm; }
351         ParserArena& parserArena() const { return m_scopeNode->parserArena(); }
352         const CommonIdentifiers& propertyNames() const { return *m_vm->propertyNames; }
353
354         bool isConstructor() const { return m_codeBlock->isConstructor(); }
355         DerivedContextType derivedContextType() const { return m_derivedContextType; }
356         bool usesArrowFunction() const { return m_scopeNode->usesArrowFunction(); }
357         bool needsToUpdateArrowFunctionContext() const { return m_needsToUpdateArrowFunctionContext; }
358         bool usesEval() const { return m_scopeNode->usesEval(); }
359         bool usesThis() const { return m_scopeNode->usesThis(); }
360         ConstructorKind constructorKind() const { return m_codeBlock->constructorKind(); }
361         SuperBinding superBinding() const { return m_codeBlock->superBinding(); }
362         JSParserScriptMode scriptMode() const { return m_codeBlock->scriptMode(); }
363
364         template<typename... Args>
365         static ParserError generate(VM& vm, Args&& ...args)
366         {
367             DeferGC deferGC(vm.heap);
368             auto bytecodeGenerator = std::make_unique<BytecodeGenerator>(vm, std::forward<Args>(args)...);
369             return bytecodeGenerator->generate(); 
370         }
371
372         bool isArgumentNumber(const Identifier&, int);
373
374         Variable variable(const Identifier&, ThisResolutionType = ThisResolutionType::Local);
375         
376         enum ExistingVariableMode { VerifyExisting, IgnoreExisting };
377         void createVariable(const Identifier&, VarKind, SymbolTable*, ExistingVariableMode = VerifyExisting); // Creates the variable, or asserts that the already-created variable is sufficiently compatible.
378         
379         // Returns the register storing "this"
380         RegisterID* thisRegister() { return &m_thisRegister; }
381         RegisterID* argumentsRegister() { return m_argumentsRegister; }
382         RegisterID* newTarget()
383         {
384             return m_newTargetRegister;
385         }
386
387         RegisterID* scopeRegister() { return m_scopeRegister; }
388
389         RegisterID* generatorRegister() { return m_generatorRegister; }
390
391         RegisterID* promiseCapabilityRegister() { return m_promiseCapabilityRegister; }
392
393         // Returns the next available temporary register. Registers returned by
394         // newTemporary require a modified form of reference counting: any
395         // register with a refcount of 0 is considered "available", meaning that
396         // the next instruction may overwrite it.
397         RegisterID* newTemporary();
398
399         // The same as newTemporary(), but this function returns "suggestion" if
400         // "suggestion" is a temporary. This function is helpful in situations
401         // where you've put "suggestion" in a RefPtr, but you'd like to allow
402         // the next instruction to overwrite it anyway.
403         RegisterID* newTemporaryOr(RegisterID* suggestion) { return suggestion->isTemporary() ? suggestion : newTemporary(); }
404
405         // Functions for handling of dst register
406
407         RegisterID* ignoredResult() { return &m_ignoredResultRegister; }
408
409         // This will be allocated in the temporary region of registers, but it will
410         // not be marked as a temporary. This will ensure that finalDestination() does
411         // not overwrite a block scope variable that it mistakes as a temporary. These
412         // registers can be (and are) reclaimed when the lexical scope they belong to
413         // is no longer on the symbol table stack.
414         RegisterID* newBlockScopeVariable();
415
416         // Returns a place to write intermediate values of an operation
417         // which reuses dst if it is safe to do so.
418         RegisterID* tempDestination(RegisterID* dst)
419         {
420             return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary();
421         }
422
423         // Returns the place to write the final output of an operation.
424         RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0)
425         {
426             if (originalDst && originalDst != ignoredResult())
427                 return originalDst;
428             ASSERT(tempDst != ignoredResult());
429             if (tempDst && tempDst->isTemporary())
430                 return tempDst;
431             return newTemporary();
432         }
433
434         RegisterID* destinationForAssignResult(RegisterID* dst)
435         {
436             if (dst && dst != ignoredResult())
437                 return dst->isTemporary() ? dst : newTemporary();
438             return 0;
439         }
440
441         // Moves src to dst if dst is not null and is different from src, otherwise just returns src.
442         RegisterID* moveToDestinationIfNeeded(RegisterID* dst, RegisterID* src)
443         {
444             return dst == ignoredResult() ? 0 : (dst && dst != src) ? emitMove(dst, src) : src;
445         }
446
447         LabelScopePtr newLabelScope(LabelScope::Type, const Identifier* = 0);
448         Ref<Label> newLabel();
449         Ref<Label> newEmittedLabel();
450
451         void emitNode(RegisterID* dst, StatementNode* n)
452         {
453             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
454             return emitNodeInTailPosition(dst, n);
455         }
456
457         void emitNodeInTailPosition(RegisterID* dst, StatementNode* n)
458         {
459             // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
460             ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
461             if (UNLIKELY(!m_vm->isSafeToRecurse())) {
462                 emitThrowExpressionTooDeepException();
463                 return;
464             }
465             if (UNLIKELY(n->needsDebugHook()))
466                 emitDebugHook(n);
467             n->emitBytecode(*this, dst);
468         }
469
470         void emitNode(StatementNode* n)
471         {
472             emitNode(nullptr, n);
473         }
474
475         void emitNodeInTailPosition(StatementNode* n)
476         {
477             emitNodeInTailPosition(nullptr, n);
478         }
479
480         RegisterID* emitNode(RegisterID* dst, ExpressionNode* n)
481         {
482             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
483             return emitNodeInTailPosition(dst, n);
484         }
485
486         RegisterID* emitNodeInTailPosition(RegisterID* dst, ExpressionNode* n)
487         {
488             // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
489             ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
490             if (UNLIKELY(!m_vm->isSafeToRecurse()))
491                 return emitThrowExpressionTooDeepException();
492             if (UNLIKELY(n->needsDebugHook()))
493                 emitDebugHook(n);
494             return n->emitBytecode(*this, dst);
495         }
496
497         RegisterID* emitNode(ExpressionNode* n)
498         {
499             return emitNode(nullptr, n);
500         }
501
502         RegisterID* emitNodeInTailPosition(ExpressionNode* n)
503         {
504             return emitNodeInTailPosition(nullptr, n);
505         }
506
507         void emitNodeInConditionContext(ExpressionNode* n, Label& trueTarget, Label& falseTarget, FallThroughMode fallThroughMode)
508         {
509             if (UNLIKELY(!m_vm->isSafeToRecurse())) {
510                 emitThrowExpressionTooDeepException();
511                 return;
512             }
513             n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMode);
514         }
515
516         void emitExpressionInfo(const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
517         {            
518             ASSERT(divot.offset >= divotStart.offset);
519             ASSERT(divotEnd.offset >= divot.offset);
520
521             int sourceOffset = m_scopeNode->source().startOffset();
522             unsigned firstLine = m_scopeNode->source().firstLine().oneBasedInt();
523
524             int divotOffset = divot.offset - sourceOffset;
525             int startOffset = divot.offset - divotStart.offset;
526             int endOffset = divotEnd.offset - divot.offset;
527
528             unsigned line = divot.line;
529             ASSERT(line >= firstLine);
530             line -= firstLine;
531
532             int lineStart = divot.lineStartOffset;
533             if (lineStart > sourceOffset)
534                 lineStart -= sourceOffset;
535             else
536                 lineStart = 0;
537
538             if (divotOffset < lineStart)
539                 return;
540
541             unsigned column = divotOffset - lineStart;
542
543             unsigned instructionOffset = instructions().size();
544             if (!m_isBuiltinFunction)
545                 m_codeBlock->addExpressionInfo(instructionOffset, divotOffset, startOffset, endOffset, line, column);
546         }
547
548
549         ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure)
550         {
551             return (m_codeType != FunctionCode || rightHasAssignments) && !rightIsPure;
552         }
553
554         ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
555         {
556             if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
557                 RefPtr<RegisterID> dst = newTemporary();
558                 emitNode(dst.get(), n);
559                 return dst;
560             }
561
562             return emitNode(n);
563         }
564
565         void hoistSloppyModeFunctionIfNecessary(const Identifier& functionName);
566
567     private:
568         void emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot);
569     public:
570
571         // This doesn't emit expression info. If using this, make sure you shouldn't be emitting text offset.
572         void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag); 
573         // These variables are associated with variables in a program. They could be Locals, LocalClosureVar, or ClosureVar.
574         void emitProfileType(RegisterID* registerToProfile, const Variable&, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
575
576         void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
577         // These are not associated with variables and don't have a global id.
578         void emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
579
580         void emitProfileControlFlow(int);
581         
582         RegisterID* emitLoadArrowFunctionLexicalEnvironment(const Identifier&);
583         RegisterID* ensureThis();
584         void emitLoadThisFromArrowFunctionLexicalEnvironment();
585         RegisterID* emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
586
587         RegisterID* emitLoad(RegisterID* dst, bool);
588         RegisterID* emitLoad(RegisterID* dst, const Identifier&);
589         RegisterID* emitLoad(RegisterID* dst, JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
590         RegisterID* emitLoad(RegisterID* dst, IdentifierSet& excludedList);
591         RegisterID* emitLoadGlobalObject(RegisterID* dst);
592
593         RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src);
594         RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src, OperandTypes);
595         RegisterID* emitUnaryOpProfiled(OpcodeID, RegisterID* dst, RegisterID* src);
596         RegisterID* emitBinaryOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes);
597         RegisterID* emitEqualityOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2);
598         RegisterID* emitUnaryNoDstOp(OpcodeID, RegisterID* src);
599
600         RegisterID* emitCreateThis(RegisterID* dst);
601         void emitTDZCheck(RegisterID* target);
602         bool needsTDZCheck(const Variable&);
603         void emitTDZCheckIfNecessary(const Variable&, RegisterID* target, RegisterID* scope);
604         void liftTDZCheckIfPossible(const Variable&);
605         RegisterID* emitNewObject(RegisterID* dst);
606         RegisterID* emitNewArray(RegisterID* dst, ElementNode*, unsigned length); // stops at first elision
607         RegisterID* emitNewArrayWithSpread(RegisterID* dst, ElementNode*);
608         RegisterID* emitNewArrayWithSize(RegisterID* dst, RegisterID* length);
609
610         RegisterID* emitNewFunction(RegisterID* dst, FunctionMetadataNode*);
611         RegisterID* emitNewFunctionExpression(RegisterID* dst, FuncExprNode*);
612         RegisterID* emitNewDefaultConstructor(RegisterID* dst, ConstructorKind, const Identifier& name, const Identifier& ecmaName, const SourceCode& classSource);
613         RegisterID* emitNewArrowFunctionExpression(RegisterID*, ArrowFuncExprNode*);
614         RegisterID* emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode*);
615         RegisterID* emitNewRegExp(RegisterID* dst, RegExp*);
616
617         void emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name);
618
619         RegisterID* emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant);
620         RegisterID* emitMoveEmptyValue(RegisterID* dst);
621         RegisterID* emitMove(RegisterID* dst, RegisterID* src);
622
623         RegisterID* emitToNumber(RegisterID* dst, RegisterID* src) { return emitUnaryOpProfiled(op_to_number, dst, src); }
624         RegisterID* emitToString(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_to_string, dst, src); }
625         RegisterID* emitInc(RegisterID* srcDst);
626         RegisterID* emitDec(RegisterID* srcDst);
627
628         RegisterID* emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue);
629         RegisterID* emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype);
630         RegisterID* emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue);
631         RegisterID* emitTypeOf(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_typeof, dst, src); }
632         RegisterID* emitIn(RegisterID* dst, RegisterID* property, RegisterID* base);
633
634         RegisterID* emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
635         RegisterID* emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
636         RegisterID* emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property);
637         RegisterID* emitPutById(RegisterID* base, const Identifier& property, RegisterID* value);
638         RegisterID* emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value);
639         RegisterID* emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType);
640         RegisterID* emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier&);
641         RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
642         RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property);
643         RegisterID* emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
644         RegisterID* emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value);
645         RegisterID* emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
646         RegisterID* emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
647         RegisterID* emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value);
648
649         RegisterID* emitAssert(RegisterID* condition, int line);
650
651         void emitPutGetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* getter);
652         void emitPutSetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* setter);
653         void emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter);
654         void emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* getter);
655         void emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* setter);
656
657         RegisterID* emitGetArgument(RegisterID* dst, int32_t index);
658
659         // Initialize object with generator fields (@generatorThis, @generatorNext, @generatorState, @generatorFrame)
660         void emitPutGeneratorFields(RegisterID* nextFunction);
661
662         ExpectedFunction expectedFunctionForIdentifier(const Identifier&);
663         RegisterID* emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
664         RegisterID* emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
665         RegisterID* emitCallEval(RegisterID* dst, RegisterID* func, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
666         RegisterID* emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
667         RegisterID* emitCallVarargsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
668         RegisterID* emitCallForwardArgumentsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
669
670         enum PropertyDescriptorOption {
671             PropertyConfigurable = 1,
672             PropertyWritable     = 1 << 1,
673             PropertyEnumerable   = 1 << 2,
674         };
675         void emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
676             RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition&);
677
678         void emitEnumeration(ThrowableExpressionData* enumerationNode, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, ForOfNode* = nullptr, RegisterID* forLoopSymbolTable = nullptr);
679
680         RegisterID* emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode*);
681         RegisterID* emitGetGlobalPrivate(RegisterID* dst, const Identifier& property);
682
683         enum class ReturnFrom { Normal, Finally };
684         RegisterID* emitReturn(RegisterID* src, ReturnFrom = ReturnFrom::Normal);
685         RegisterID* emitEnd(RegisterID* src) { return emitUnaryNoDstOp(op_end, src); }
686
687         RegisterID* emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd);
688         RegisterID* emitStrcat(RegisterID* dst, RegisterID* src, int count);
689         void emitToPrimitive(RegisterID* dst, RegisterID* src);
690
691         ResolveType resolveType();
692         RegisterID* emitResolveConstantLocal(RegisterID* dst, const Variable&);
693         RegisterID* emitResolveScope(RegisterID* dst, const Variable&);
694         RegisterID* emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable&, ResolveMode);
695         RegisterID* emitPutToScope(RegisterID* scope, const Variable&, RegisterID* value, ResolveMode, InitializationMode);
696         RegisterID* initializeVariable(const Variable&, RegisterID* value);
697
698         void emitLabel(Label&);
699         void emitLoopHint();
700         void emitJump(Label& target);
701         void emitJumpIfTrue(RegisterID* cond, Label& target);
702         void emitJumpIfFalse(RegisterID* cond, Label& target);
703         void emitJumpIfNotFunctionCall(RegisterID* cond, Label& target);
704         void emitJumpIfNotFunctionApply(RegisterID* cond, Label& target);
705
706         void emitEnter();
707         void emitCheckTraps();
708
709         RegisterID* emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
710         RegisterID* emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator);
711         RegisterID* emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
712         RegisterID* emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base);
713         RegisterID* emitGetEnumerableLength(RegisterID* dst, RegisterID* base);
714         RegisterID* emitGetStructurePropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length);
715         RegisterID* emitGetGenericPropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length, RegisterID* structureEnumerator);
716         RegisterID* emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
717         RegisterID* emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
718         RegisterID* emitToIndexString(RegisterID* dst, RegisterID* index);
719
720         RegisterID* emitIsCellWithType(RegisterID* dst, RegisterID* src, JSType);
721         RegisterID* emitIsJSArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ArrayType); }
722         RegisterID* emitIsProxyObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ProxyObjectType); }
723         RegisterID* emitIsRegExpObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, RegExpObjectType); }
724         RegisterID* emitIsMap(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSMapType); }
725         RegisterID* emitIsSet(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSSetType); }
726         RegisterID* emitIsObject(RegisterID* dst, RegisterID* src);
727         RegisterID* emitIsNumber(RegisterID* dst, RegisterID* src);
728         RegisterID* emitIsUndefined(RegisterID* dst, RegisterID* src);
729         RegisterID* emitIsEmpty(RegisterID* dst, RegisterID* src);
730         RegisterID* emitIsDerivedArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, DerivedArrayType); }
731         void emitRequireObjectCoercible(RegisterID* value, const String& error);
732
733         RegisterID* emitIteratorNext(RegisterID* dst, RegisterID* iterator, const ThrowableExpressionData* node);
734         RegisterID* emitIteratorNextWithValue(RegisterID* dst, RegisterID* iterator, RegisterID* value, const ThrowableExpressionData* node);
735         void emitIteratorClose(RegisterID* iterator, const ThrowableExpressionData* node);
736
737         RegisterID* emitRestParameter(RegisterID* result, unsigned numParametersToSkip);
738
739         bool emitReadOnlyExceptionIfNeeded(const Variable&);
740
741         // Start a try block. 'start' must have been emitted.
742         TryData* pushTry(Label& start, Label& handlerLabel, HandlerType);
743         // End a try block. 'end' must have been emitted.
744         void popTry(TryData*, Label& end);
745         void emitCatch(RegisterID* exceptionRegister, RegisterID* thrownValueRegister);
746
747     private:
748         static const int CurrentLexicalScopeIndex = -2;
749         static const int OutermostLexicalScopeIndex = -1;
750
751         int currentLexicalScopeIndex() const
752         {
753             int size = static_cast<int>(m_lexicalScopeStack.size());
754             ASSERT(static_cast<size_t>(size) == m_lexicalScopeStack.size());
755             ASSERT(size >= 0);
756             if (!size)
757                 return OutermostLexicalScopeIndex;
758             return size - 1;
759         }
760
761     public:
762         void restoreScopeRegister();
763         void restoreScopeRegister(int lexicalScopeIndex);
764
765         int labelScopeDepthToLexicalScopeIndex(int labelScopeDepth);
766
767         void emitThrow(RegisterID* exc)
768         { 
769             m_usesExceptions = true;
770             emitUnaryNoDstOp(op_throw, exc);
771         }
772
773         void emitThrowStaticError(ErrorType, RegisterID*);
774         void emitThrowStaticError(ErrorType, const Identifier& message);
775         void emitThrowReferenceError(const String& message);
776         void emitThrowTypeError(const String& message);
777         void emitThrowTypeError(const Identifier& message);
778         void emitThrowRangeError(const Identifier& message);
779         void emitThrowOutOfMemoryError();
780
781         void emitPushCatchScope(VariableEnvironment&);
782         void emitPopCatchScope(VariableEnvironment&);
783
784         void emitGetScope();
785         RegisterID* emitPushWithScope(RegisterID* objectScope);
786         void emitPopWithScope();
787         void emitPutThisToArrowFunctionContextScope();
788         void emitPutNewTargetToArrowFunctionContextScope();
789         void emitPutDerivedConstructorToArrowFunctionContextScope();
790         RegisterID* emitLoadDerivedConstructorFromArrowFunctionLexicalEnvironment();
791
792         void emitDebugHook(DebugHookType, const JSTextPosition&);
793         void emitDebugHook(DebugHookType, unsigned line, unsigned charOffset, unsigned lineStart);
794         void emitDebugHook(StatementNode*);
795         void emitDebugHook(ExpressionNode*);
796         void emitWillLeaveCallFrameDebugHook();
797
798         class CompletionRecordScope {
799         public:
800             CompletionRecordScope(BytecodeGenerator& generator, bool needCompletionRecordRegisters = true)
801                 : m_generator(generator)
802             {
803                 if (needCompletionRecordRegisters && m_generator.allocateCompletionRecordRegisters())
804                     m_needToReleaseOnDestruction = true;
805             }
806             ~CompletionRecordScope()
807             {
808                 if (m_needToReleaseOnDestruction)
809                     m_generator.releaseCompletionRecordRegisters();
810             }
811
812         private:
813             BytecodeGenerator& m_generator;
814             bool m_needToReleaseOnDestruction { false };
815         };
816
817         RegisterID* completionTypeRegister() const
818         {
819             ASSERT(m_completionTypeRegister);
820             return m_completionTypeRegister.get();
821         }
822         RegisterID* completionValueRegister() const
823         {
824             ASSERT(m_completionValueRegister);
825             return m_completionValueRegister.get();
826         }
827
828         void emitSetCompletionType(CompletionType type)
829         {
830             emitLoad(completionTypeRegister(), JSValue(static_cast<int>(type)));
831         }
832         void emitSetCompletionValue(RegisterID* reg)
833         {
834             emitMove(completionValueRegister(), reg);
835         }
836
837         void emitJumpIf(OpcodeID compareOpcode, RegisterID* completionTypeRegister, CompletionType, Label& jumpTarget);
838
839         bool emitJumpViaFinallyIfNeeded(int targetLabelScopeDepth, Label& jumpTarget);
840         bool emitReturnViaFinallyIfNeeded(RegisterID* returnRegister);
841         void emitFinallyCompletion(FinallyContext&, RegisterID* completionTypeRegister, Label& normalCompletionLabel);
842
843     private:
844         bool allocateCompletionRecordRegisters();
845         void releaseCompletionRecordRegisters();
846
847     public:
848         FinallyContext* pushFinallyControlFlowScope(Label& finallyLabel);
849         FinallyContext popFinallyControlFlowScope();
850
851         void pushIndexedForInScope(RegisterID* local, RegisterID* index);
852         void popIndexedForInScope(RegisterID* local);
853         void pushStructureForInScope(RegisterID* local, RegisterID* index, RegisterID* property, RegisterID* enumerator);
854         void popStructureForInScope(RegisterID* local);
855         void invalidateForInContextForLocal(RegisterID* local);
856
857         LabelScopePtr breakTarget(const Identifier&);
858         LabelScopePtr continueTarget(const Identifier&);
859
860         void beginSwitch(RegisterID*, SwitchInfo::SwitchType);
861         void endSwitch(uint32_t clauseCount, const Vector<Ref<Label>, 8>&, ExpressionNode**, Label& defaultLabel, int32_t min, int32_t range);
862
863         void emitYieldPoint(RegisterID*);
864
865         void emitGeneratorStateLabel();
866         void emitGeneratorStateChange(int32_t state);
867         RegisterID* emitYield(RegisterID* argument);
868         RegisterID* emitDelegateYield(RegisterID* argument, ThrowableExpressionData*);
869         RegisterID* generatorStateRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::State)]; }
870         RegisterID* generatorValueRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Value)]; }
871         RegisterID* generatorResumeModeRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::ResumeMode)]; }
872         RegisterID* generatorFrameRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Frame)]; }
873
874         CodeType codeType() const { return m_codeType; }
875
876         bool shouldEmitDebugHooks() { return m_shouldEmitDebugHooks; }
877         
878         bool isStrictMode() const { return m_codeBlock->isStrictMode(); }
879
880         SourceParseMode parseMode() const { return m_codeBlock->parseMode(); }
881         
882         bool isBuiltinFunction() const { return m_isBuiltinFunction; }
883
884         OpcodeID lastOpcodeID() const { return m_lastOpcodeID; }
885         
886         bool isDerivedConstructorContext() { return m_derivedContextType == DerivedContextType::DerivedConstructorContext; }
887         bool isDerivedClassContext() { return m_derivedContextType == DerivedContextType::DerivedMethodContext; }
888         bool isArrowFunction() { return m_codeBlock->isArrowFunction(); }
889
890         enum class TDZCheckOptimization { Optimize, DoNotOptimize };
891         enum class NestedScopeType { IsNested, IsNotNested };
892     private:
893         enum class TDZRequirement { UnderTDZ, NotUnderTDZ };
894         enum class ScopeType { CatchScope, LetConstScope, FunctionNameScope };
895         enum class ScopeRegisterType { Var, Block };
896         void pushLexicalScopeInternal(VariableEnvironment&, TDZCheckOptimization, NestedScopeType, RegisterID** constantSymbolTableResult, TDZRequirement, ScopeType, ScopeRegisterType);
897         void initializeBlockScopedFunctions(VariableEnvironment&, FunctionStack&, RegisterID* constantSymbolTable);
898         void popLexicalScopeInternal(VariableEnvironment&);
899         template<typename LookUpVarKindFunctor>
900         bool instantiateLexicalVariables(const VariableEnvironment&, SymbolTable*, ScopeRegisterType, LookUpVarKindFunctor);
901         void emitPrefillStackTDZVariables(const VariableEnvironment&, SymbolTable*);
902         void emitPopScope(RegisterID* dst, RegisterID* scope);
903         RegisterID* emitGetParentScope(RegisterID* dst, RegisterID* scope);
904         void emitPushFunctionNameScope(const Identifier& property, RegisterID* value, bool isCaptured);
905         void emitNewFunctionExpressionCommon(RegisterID*, FunctionMetadataNode*);
906         
907         bool isNewTargetUsedInInnerArrowFunction();
908         bool isArgumentsUsedInInnerArrowFunction();
909
910     public:
911         bool isSuperUsedInInnerArrowFunction();
912         bool isSuperCallUsedInInnerArrowFunction();
913         bool isThisUsedInInnerArrowFunction();
914         void pushLexicalScope(VariableEnvironmentNode*, TDZCheckOptimization, NestedScopeType = NestedScopeType::IsNotNested, RegisterID** constantSymbolTableResult = nullptr, bool shouldInitializeBlockScopedFunctions = true);
915         void popLexicalScope(VariableEnvironmentNode*);
916         void prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode*, RegisterID* loopSymbolTable);
917         int labelScopeDepth() const;
918
919     private:
920         ParserError generate();
921         void reclaimFreeRegisters();
922         Variable variableForLocalEntry(const Identifier&, const SymbolTableEntry&, int symbolTableConstantIndex, bool isLexicallyScoped);
923
924         void emitOpcode(OpcodeID);
925         UnlinkedArrayAllocationProfile newArrayAllocationProfile();
926         UnlinkedObjectAllocationProfile newObjectAllocationProfile();
927         UnlinkedArrayProfile newArrayProfile();
928         UnlinkedValueProfile emitProfiledOpcode(OpcodeID);
929         int kill(RegisterID* dst)
930         {
931             int index = dst->index();
932             m_staticPropertyAnalyzer.kill(index);
933             return index;
934         }
935
936         void retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index);
937         void retrieveLastUnaryOp(int& dstIndex, int& srcIndex);
938         ALWAYS_INLINE void rewindBinaryOp();
939         ALWAYS_INLINE void rewindUnaryOp();
940
941         void allocateCalleeSaveSpace();
942         void allocateAndEmitScope();
943
944         typedef HashMap<double, JSValue> NumberMap;
945         typedef HashMap<UniquedStringImpl*, JSString*, IdentifierRepHash> IdentifierStringMap;
946         typedef HashMap<Ref<TemplateRegistryKey>, RegisterID*> TemplateRegistryKeyMap;
947         
948         // Helper for emitCall() and emitConstruct(). This works because the set of
949         // expected functions have identical behavior for both call and construct
950         // (i.e. "Object()" is identical to "new Object()").
951         ExpectedFunction emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, Label& done);
952         
953         RegisterID* emitCall(OpcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
954
955         RegisterID* newRegister();
956
957         // Adds an anonymous local var slot. To give this slot a name, add it to symbolTable().
958         RegisterID* addVar()
959         {
960             ++m_codeBlock->m_numVars;
961             RegisterID* result = newRegister();
962             ASSERT(VirtualRegister(result->index()).toLocal() == m_codeBlock->m_numVars - 1);
963             result->ref(); // We should never free this slot.
964             return result;
965         }
966
967         // Initializes the stack form the parameter; does nothing for the symbol table.
968         RegisterID* initializeNextParameter();
969         UniquedStringImpl* visibleNameForParameter(DestructuringPatternNode*);
970         
971         RegisterID& registerFor(VirtualRegister reg)
972         {
973             if (reg.isLocal())
974                 return m_calleeLocals[reg.toLocal()];
975
976             if (reg.offset() == CallFrameSlot::callee)
977                 return m_calleeRegister;
978
979             ASSERT(m_parameters.size());
980             return m_parameters[reg.toArgument()];
981         }
982
983         bool hasConstant(const Identifier&) const;
984         unsigned addConstant(const Identifier&);
985         RegisterID* addConstantValue(JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
986         RegisterID* addConstantEmptyValue();
987         unsigned addRegExp(RegExp*);
988
989         unsigned addConstantBuffer(unsigned length);
990         
991         UnlinkedFunctionExecutable* makeFunction(FunctionMetadataNode* metadata)
992         {
993             DerivedContextType newDerivedContextType = DerivedContextType::None;
994
995             if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(metadata->parseMode())) {
996                 if (constructorKind() == ConstructorKind::Extends || isDerivedConstructorContext())
997                     newDerivedContextType = DerivedContextType::DerivedConstructorContext;
998                 else if (m_codeBlock->isClassContext() || isDerivedClassContext())
999                     newDerivedContextType = DerivedContextType::DerivedMethodContext;
1000             }
1001
1002             VariableEnvironment variablesUnderTDZ;
1003             getVariablesUnderTDZ(variablesUnderTDZ);
1004
1005             // FIXME: These flags, ParserModes and propagation to XXXCodeBlocks should be reorganized.
1006             // https://bugs.webkit.org/show_bug.cgi?id=151547
1007             SourceParseMode parseMode = metadata->parseMode();
1008             ConstructAbility constructAbility = constructAbilityForParseMode(parseMode);
1009             if (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() != ConstructorKind::None)
1010                 constructAbility = ConstructAbility::CanConstruct;
1011
1012             return UnlinkedFunctionExecutable::create(m_vm, m_scopeNode->source(), metadata, isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, constructAbility, scriptMode(), variablesUnderTDZ, newDerivedContextType);
1013         }
1014
1015         void getVariablesUnderTDZ(VariableEnvironment&);
1016
1017         RegisterID* emitConstructVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1018         RegisterID* emitCallVarargs(OpcodeID, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1019         
1020         void emitLogShadowChickenPrologueIfNecessary();
1021         void emitLogShadowChickenTailIfNecessary();
1022
1023         void initializeParameters(FunctionParameters&);
1024         void initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables);
1025         void initializeDefaultParameterValuesAndSetupFunctionScopeStack(FunctionParameters&, bool isSimpleParameterList, FunctionNode*, SymbolTable*, int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope);
1026         void initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable = nullptr, bool canReuseLexicalEnvironment = false);
1027         bool needsDerivedConstructorInArrowFunctionLexicalEnvironment();
1028
1029     public:
1030         JSString* addStringConstant(const Identifier&);
1031         RegisterID* addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&&);
1032
1033         Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>& instructions() { return m_instructions; }
1034
1035         RegisterID* emitThrowExpressionTooDeepException();
1036
1037     private:
1038         Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow> m_instructions;
1039
1040         bool m_shouldEmitDebugHooks;
1041
1042         struct LexicalScopeStackEntry {
1043             SymbolTable* m_symbolTable;
1044             RegisterID* m_scope;
1045             bool m_isWithScope;
1046             int m_symbolTableConstantIndex;
1047         };
1048         Vector<LexicalScopeStackEntry> m_lexicalScopeStack;
1049         enum class TDZNecessityLevel {
1050             NotNeeded,
1051             Optimize,
1052             DoNotOptimize
1053         };
1054         typedef HashMap<RefPtr<UniquedStringImpl>, TDZNecessityLevel, IdentifierRepHash> TDZMap;
1055         Vector<TDZMap> m_TDZStack;
1056         std::optional<size_t> m_varScopeLexicalScopeStackIndex;
1057         void pushTDZVariables(const VariableEnvironment&, TDZCheckOptimization, TDZRequirement);
1058
1059         ScopeNode* const m_scopeNode;
1060         Strong<UnlinkedCodeBlock> m_codeBlock;
1061
1062         // Some of these objects keep pointers to one another. They are arranged
1063         // to ensure a sane destruction order that avoids references to freed memory.
1064         HashSet<RefPtr<UniquedStringImpl>, IdentifierRepHash> m_functions;
1065         RegisterID m_ignoredResultRegister;
1066         RegisterID m_thisRegister;
1067         RegisterID m_calleeRegister;
1068         RegisterID* m_scopeRegister { nullptr };
1069         RegisterID* m_topMostScope { nullptr };
1070         RegisterID* m_argumentsRegister { nullptr };
1071         RegisterID* m_lexicalEnvironmentRegister { nullptr };
1072         RegisterID* m_generatorRegister { nullptr };
1073         RegisterID* m_emptyValueRegister { nullptr };
1074         RegisterID* m_globalObjectRegister { nullptr };
1075         RegisterID* m_newTargetRegister { nullptr };
1076         RegisterID* m_isDerivedConstuctor { nullptr };
1077         RegisterID* m_linkTimeConstantRegisters[LinkTimeConstantCount];
1078         RegisterID* m_arrowFunctionContextLexicalEnvironmentRegister { nullptr };
1079         RegisterID* m_promiseCapabilityRegister { nullptr };
1080
1081         RefPtr<RegisterID> m_completionTypeRegister;
1082         RefPtr<RegisterID> m_completionValueRegister;
1083
1084         FinallyContext* m_currentFinallyContext { nullptr };
1085
1086         SegmentedVector<RegisterID*, 16> m_localRegistersForCalleeSaveRegisters;
1087         SegmentedVector<RegisterID, 32> m_constantPoolRegisters;
1088         SegmentedVector<RegisterID, 32> m_calleeLocals;
1089         SegmentedVector<RegisterID, 32> m_parameters;
1090         SegmentedVector<Label, 32> m_labels;
1091         LabelScopeStore m_labelScopes;
1092         unsigned m_finallyDepth { 0 };
1093         int m_localScopeDepth { 0 };
1094         const CodeType m_codeType;
1095
1096         int localScopeDepth() const;
1097         void pushLocalControlFlowScope();
1098         void popLocalControlFlowScope();
1099
1100         // FIXME: Restore overflow checking with UnsafeVectorOverflow once SegmentVector supports it.
1101         // https://bugs.webkit.org/show_bug.cgi?id=165980
1102         SegmentedVector<ControlFlowScope, 16> m_controlFlowScopeStack;
1103         Vector<SwitchInfo> m_switchContextStack;
1104         Vector<Ref<ForInContext>> m_forInContextStack;
1105         Vector<TryContext> m_tryContextStack;
1106         unsigned m_yieldPoints { 0 };
1107
1108         Strong<SymbolTable> m_generatorFrameSymbolTable;
1109         int m_generatorFrameSymbolTableIndex { 0 };
1110
1111         enum FunctionVariableType : uint8_t { NormalFunctionVariable, GlobalFunctionVariable };
1112         Vector<std::pair<FunctionMetadataNode*, FunctionVariableType>> m_functionsToInitialize;
1113         bool m_needToInitializeArguments { false };
1114         RestParameterNode* m_restParameter { nullptr };
1115         
1116         Vector<TryRange> m_tryRanges;
1117         SegmentedVector<TryData, 8> m_tryData;
1118
1119         int m_nextConstantOffset { 0 };
1120
1121         typedef HashMap<FunctionMetadataNode*, unsigned> FunctionOffsetMap;
1122         FunctionOffsetMap m_functionOffsets;
1123         
1124         // Constant pool
1125         IdentifierMap m_identifierMap;
1126
1127         typedef HashMap<EncodedJSValueWithRepresentation, unsigned, EncodedJSValueWithRepresentationHash, EncodedJSValueWithRepresentationHashTraits> JSValueMap;
1128         JSValueMap m_jsValueMap;
1129         IdentifierStringMap m_stringMap;
1130         TemplateRegistryKeyMap m_templateRegistryKeyMap;
1131
1132         StaticPropertyAnalyzer m_staticPropertyAnalyzer { &m_instructions };
1133
1134         VM* m_vm;
1135
1136         OpcodeID m_lastOpcodeID = op_end;
1137 #ifndef NDEBUG
1138         size_t m_lastOpcodePosition { 0 };
1139 #endif
1140
1141         bool m_usesExceptions { false };
1142         bool m_expressionTooDeep { false };
1143         bool m_isBuiltinFunction { false };
1144         bool m_usesNonStrictEval { false };
1145         bool m_inTailPosition { false };
1146         bool m_needsToUpdateArrowFunctionContext;
1147         DerivedContextType m_derivedContextType { DerivedContextType::None };
1148     };
1149
1150 } // namespace JSC
1151
1152 namespace WTF {
1153
1154 void printInternal(PrintStream&, JSC::Variable::VariableKind);
1155
1156 } // namespace WTF