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