94eeb1326106ff6ddcd74931dea0ab29194ddcc7
[WebKit-https.git] / Source / JavaScriptCore / bytecompiler / BytecodeGenerator.h
1 /*
2  * Copyright (C) 2008-2019 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  * Copyright (C) 2012 Igalia, S.L.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #pragma once
32
33 #include "CodeBlock.h"
34 #include "Instruction.h"
35 #include "Interpreter.h"
36 #include "JSAsyncGeneratorFunction.h"
37 #include "JSBigInt.h"
38 #include "JSGeneratorFunction.h"
39 #include "JSTemplateObjectDescriptor.h"
40 #include "Label.h"
41 #include "LabelScope.h"
42 #include "Nodes.h"
43 #include "ParserError.h"
44 #include "ProfileTypeBytecodeFlag.h"
45 #include "RegisterID.h"
46 #include "StaticPropertyAnalyzer.h"
47 #include "SymbolTable.h"
48 #include "UnlinkedCodeBlock.h"
49 #include <functional>
50 #include <wtf/CheckedArithmetic.h>
51 #include <wtf/HashFunctions.h>
52 #include <wtf/Optional.h>
53 #include <wtf/SegmentedVector.h>
54 #include <wtf/SetForScope.h>
55 #include <wtf/Vector.h>
56
57 namespace JSC {
58
59     class JSImmutableButterfly;
60     class Identifier;
61     class IndexedForInContext;
62     class StructureForInContext;
63
64     enum ExpectedFunction {
65         NoExpectedFunction,
66         ExpectObjectConstructor,
67         ExpectArrayConstructor
68     };
69
70     enum class EmitAwait { Yes, No };
71
72     enum class DebuggableCall { Yes, No };
73     enum class ThisResolutionType { Local, Scoped };
74     
75     class CallArguments {
76     public:
77         CallArguments(BytecodeGenerator&, ArgumentsNode*, unsigned additionalArguments = 0);
78
79         RegisterID* thisRegister() { return m_argv[0].get(); }
80         RegisterID* argumentRegister(unsigned i) { return m_argv[i + 1].get(); }
81         unsigned stackOffset() { return -m_argv[0]->index() + CallFrame::headerSizeInRegisters; }
82         unsigned argumentCountIncludingThis() { return m_argv.size() - m_padding; }
83         ArgumentsNode* argumentsNode() { return m_argumentsNode; }
84
85     private:
86         ArgumentsNode* m_argumentsNode;
87         Vector<RefPtr<RegisterID>, 8, UnsafeVectorOverflow> m_argv;
88         unsigned m_padding;
89     };
90
91     // https://tc39.github.io/ecma262/#sec-completion-record-specification-type
92     //
93     // For the Break and Continue cases, instead of using the Break and Continue enum values
94     // below, we use the unique jumpID of the break and continue statement as the encoding
95     // for the CompletionType value. emitFinallyCompletion() uses this jumpID value later
96     // to determine the appropriate jump target to jump to after executing the relevant finally
97     // blocks. The jumpID is computed as:
98     //     jumpID = bytecodeOffset (of the break/continue node) + CompletionType::NumberOfTypes.
99     // Hence, there won't be any collision between jumpIDs and CompletionType enums.
100     enum class CompletionType : int {
101         Normal,
102         Throw,
103         Return,
104         NumberOfTypes
105     };
106
107     inline CompletionType bytecodeOffsetToJumpID(unsigned offset)
108     {
109         int jumpIDAsInt = offset + static_cast<int>(CompletionType::NumberOfTypes);
110         ASSERT(jumpIDAsInt >= static_cast<int>(CompletionType::NumberOfTypes));
111         return static_cast<CompletionType>(jumpIDAsInt);
112     }
113
114     struct FinallyJump {
115         FinallyJump(CompletionType jumpID, int targetLexicalScopeIndex, Label& targetLabel)
116             : jumpID(jumpID)
117             , targetLexicalScopeIndex(targetLexicalScopeIndex)
118             , targetLabel(targetLabel)
119         { }
120
121         CompletionType jumpID;
122         int targetLexicalScopeIndex;
123         Ref<Label> targetLabel;
124     };
125
126     class FinallyContext {
127     public:
128         FinallyContext() { }
129         FinallyContext(BytecodeGenerator&, Label& finallyLabel);
130
131         FinallyContext* outerContext() const { return m_outerContext; }
132         Label* finallyLabel() const { return m_finallyLabel; }
133
134         RegisterID* completionTypeRegister() const { return m_completionRecord.typeRegister.get(); }
135         RegisterID* completionValueRegister() const { return m_completionRecord.valueRegister.get(); }
136
137         uint32_t numberOfBreaksOrContinues() const { return m_numberOfBreaksOrContinues.unsafeGet(); }
138         void incNumberOfBreaksOrContinues() { m_numberOfBreaksOrContinues++; }
139
140         bool handlesReturns() const { return m_handlesReturns; }
141         void setHandlesReturns() { m_handlesReturns = true; }
142
143         void registerJump(CompletionType jumpID, int lexicalScopeIndex, Label& targetLabel)
144         {
145             m_jumps.append(FinallyJump(jumpID, lexicalScopeIndex, targetLabel));
146         }
147
148         size_t numberOfJumps() const { return m_jumps.size(); }
149         FinallyJump& jumps(size_t i) { return m_jumps[i]; }
150
151     private:
152         FinallyContext* m_outerContext { nullptr };
153         Label* m_finallyLabel { nullptr };
154         Checked<uint32_t, WTF::CrashOnOverflow> m_numberOfBreaksOrContinues;
155         bool m_handlesReturns { false };
156         Vector<FinallyJump> m_jumps;
157         struct {
158             RefPtr<RegisterID> typeRegister;
159             RefPtr<RegisterID> valueRegister;
160         } m_completionRecord;
161     };
162
163     struct ControlFlowScope {
164         typedef uint8_t Type;
165         enum {
166             Label,
167             Finally
168         };
169         ControlFlowScope(Type type, int lexicalScopeIndex, FinallyContext* finallyContext = nullptr)
170             : type(type)
171             , lexicalScopeIndex(lexicalScopeIndex)
172             , finallyContext(finallyContext)
173         { }
174
175         bool isLabelScope() const { return type == Label; }
176         bool isFinallyScope() const { return type == Finally; }
177
178         Type type;
179         int lexicalScopeIndex;
180         FinallyContext* finallyContext;
181     };
182
183     class ForInContext : public RefCounted<ForInContext> {
184         WTF_MAKE_FAST_ALLOCATED;
185         WTF_MAKE_NONCOPYABLE(ForInContext);
186     public:
187         virtual ~ForInContext() = default;
188
189         bool isValid() const { return m_isValid; }
190         void invalidate() { m_isValid = false; }
191
192         enum class Type : uint8_t {
193             IndexedForIn,
194             StructureForIn
195         };
196
197         Type type() const { return m_type; }
198         bool isIndexedForInContext() const { return m_type == Type::IndexedForIn; }
199         bool isStructureForInContext() const { return m_type == Type::StructureForIn; }
200
201         IndexedForInContext& asIndexedForInContext()
202         {
203             ASSERT(isIndexedForInContext());
204             return *reinterpret_cast<IndexedForInContext*>(this);
205         }
206
207         StructureForInContext& asStructureForInContext()
208         {
209             ASSERT(isStructureForInContext());
210             return *reinterpret_cast<StructureForInContext*>(this);
211         }
212
213         RegisterID* local() const { return m_localRegister.get(); }
214
215     protected:
216         ForInContext(RegisterID* localRegister, Type type, unsigned bodyBytecodeStartOffset)
217             : m_localRegister(localRegister)
218             , m_type(type)
219             , m_bodyBytecodeStartOffset(bodyBytecodeStartOffset)
220         { }
221
222         unsigned bodyBytecodeStartOffset() const { return m_bodyBytecodeStartOffset; }
223
224         void finalize(BytecodeGenerator&, UnlinkedCodeBlock*, unsigned bodyBytecodeEndOffset);
225
226     private:
227         RefPtr<RegisterID> m_localRegister;
228         bool m_isValid { true };
229         Type m_type;
230         unsigned m_bodyBytecodeStartOffset;
231     };
232
233     class StructureForInContext : public ForInContext {
234         using Base = ForInContext;
235     public:
236         using GetInst = std::tuple<unsigned, int>;
237
238         StructureForInContext(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister, unsigned bodyBytecodeStartOffset)
239             : ForInContext(localRegister, Type::StructureForIn, bodyBytecodeStartOffset)
240             , m_indexRegister(indexRegister)
241             , m_propertyRegister(propertyRegister)
242             , m_enumeratorRegister(enumeratorRegister)
243         {
244         }
245
246         RegisterID* index() const { return m_indexRegister.get(); }
247         RegisterID* property() const { return m_propertyRegister.get(); }
248         RegisterID* enumerator() const { return m_enumeratorRegister.get(); }
249
250         void addGetInst(unsigned instIndex, int propertyRegIndex)
251         {
252             m_getInsts.append(GetInst { instIndex, propertyRegIndex });
253         }
254
255         void finalize(BytecodeGenerator&, UnlinkedCodeBlock*, unsigned bodyBytecodeEndOffset);
256
257     private:
258         RefPtr<RegisterID> m_indexRegister;
259         RefPtr<RegisterID> m_propertyRegister;
260         RefPtr<RegisterID> m_enumeratorRegister;
261         Vector<GetInst> m_getInsts;
262     };
263
264     class IndexedForInContext : public ForInContext {
265         using Base = ForInContext;
266     public:
267         IndexedForInContext(RegisterID* localRegister, RegisterID* indexRegister, unsigned bodyBytecodeStartOffset)
268             : ForInContext(localRegister, Type::IndexedForIn, bodyBytecodeStartOffset)
269             , m_indexRegister(indexRegister)
270         {
271         }
272
273         RegisterID* index() const { return m_indexRegister.get(); }
274
275         void finalize(BytecodeGenerator&, UnlinkedCodeBlock*, unsigned bodyBytecodeEndOffset);
276         void addGetInst(unsigned instIndex, int propertyIndex) { m_getInsts.append({ instIndex, propertyIndex }); }
277
278     private:
279         RefPtr<RegisterID> m_indexRegister;
280         Vector<std::pair<unsigned, int>> m_getInsts;
281     };
282
283     struct TryData {
284         Ref<Label> target;
285         HandlerType handlerType;
286     };
287
288     struct TryContext {
289         Ref<Label> start;
290         TryData* tryData;
291     };
292
293     class Variable {
294     public:
295         enum VariableKind { NormalVariable, SpecialVariable };
296
297         Variable()
298             : m_offset()
299             , m_local(nullptr)
300             , m_attributes(0)
301             , m_kind(NormalVariable)
302             , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
303             , m_isLexicallyScoped(false)
304         {
305         }
306         
307         Variable(const Identifier& ident)
308             : m_ident(ident)
309             , m_local(nullptr)
310             , m_attributes(0)
311             , m_kind(NormalVariable) // This is somewhat meaningless here for this kind of Variable.
312             , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
313             , m_isLexicallyScoped(false)
314         {
315         }
316
317         Variable(const Identifier& ident, VarOffset offset, RegisterID* local, unsigned attributes, VariableKind kind, int symbolTableConstantIndex, bool isLexicallyScoped)
318             : m_ident(ident)
319             , m_offset(offset)
320             , m_local(local)
321             , m_attributes(attributes)
322             , m_kind(kind)
323             , m_symbolTableConstantIndex(symbolTableConstantIndex)
324             , m_isLexicallyScoped(isLexicallyScoped)
325         {
326         }
327
328         // If it's unset, then it is a non-locally-scoped variable. If it is set, then it could be
329         // a stack variable, a scoped variable in a local scope, or a variable captured in the
330         // direct arguments object.
331         bool isResolved() const { return !!m_offset; }
332         int symbolTableConstantIndex() const { ASSERT(isResolved() && !isSpecial()); return m_symbolTableConstantIndex; }
333         
334         const Identifier& ident() const { return m_ident; }
335         
336         VarOffset offset() const { return m_offset; }
337         bool isLocal() const { return m_offset.isStack(); }
338         RegisterID* local() const { return m_local; }
339
340         bool isReadOnly() const { return m_attributes & PropertyAttribute::ReadOnly; }
341         bool isSpecial() const { return m_kind != NormalVariable; }
342         bool isConst() const { return isReadOnly() && m_isLexicallyScoped; }
343         void setIsReadOnly() { m_attributes |= PropertyAttribute::ReadOnly; }
344
345         void dump(PrintStream&) const;
346
347     private:
348         Identifier m_ident;
349         VarOffset m_offset;
350         RegisterID* m_local;
351         unsigned m_attributes;
352         VariableKind m_kind;
353         int m_symbolTableConstantIndex;
354         bool m_isLexicallyScoped;
355     };
356
357     struct TryRange {
358         Ref<Label> start;
359         Ref<Label> end;
360         TryData* tryData;
361     };
362
363     class BytecodeGenerator {
364         WTF_MAKE_FAST_ALLOCATED;
365         WTF_MAKE_NONCOPYABLE(BytecodeGenerator);
366
367         friend class BoundLabel;
368         friend class FinallyContext;
369         friend class Label;
370         friend class IndexedForInContext;
371         friend class StructureForInContext;
372     public:
373         typedef DeclarationStacks::FunctionStack FunctionStack;
374
375         BytecodeGenerator(VM&, ProgramNode*, UnlinkedProgramCodeBlock*, OptionSet<CodeGenerationMode>, const VariableEnvironment*);
376         BytecodeGenerator(VM&, FunctionNode*, UnlinkedFunctionCodeBlock*, OptionSet<CodeGenerationMode>, const VariableEnvironment*);
377         BytecodeGenerator(VM&, EvalNode*, UnlinkedEvalCodeBlock*, OptionSet<CodeGenerationMode>, const VariableEnvironment*);
378         BytecodeGenerator(VM&, ModuleProgramNode*, UnlinkedModuleProgramCodeBlock*, OptionSet<CodeGenerationMode>, const VariableEnvironment*);
379
380         ~BytecodeGenerator();
381         
382         VM& vm() const { return m_vm; }
383         ParserArena& parserArena() const { return m_scopeNode->parserArena(); }
384         const CommonIdentifiers& propertyNames() const { return *m_vm.propertyNames; }
385
386         bool isConstructor() const { return m_codeBlock->isConstructor(); }
387         DerivedContextType derivedContextType() const { return m_derivedContextType; }
388         bool usesArrowFunction() const { return m_scopeNode->usesArrowFunction(); }
389         bool needsToUpdateArrowFunctionContext() const { return m_needsToUpdateArrowFunctionContext; }
390         bool usesEval() const { return m_scopeNode->usesEval(); }
391         bool usesThis() const { return m_scopeNode->usesThis(); }
392         ConstructorKind constructorKind() const { return m_codeBlock->constructorKind(); }
393         SuperBinding superBinding() const { return m_codeBlock->superBinding(); }
394         JSParserScriptMode scriptMode() const { return m_codeBlock->scriptMode(); }
395
396         template<typename Node, typename UnlinkedCodeBlock>
397         static ParserError generate(VM& vm, Node* node, const SourceCode& sourceCode, UnlinkedCodeBlock* unlinkedCodeBlock, OptionSet<CodeGenerationMode> codeGenerationMode, const VariableEnvironment* environment)
398         {
399             MonotonicTime before;
400             if (UNLIKELY(Options::reportBytecodeCompileTimes()))
401                 before = MonotonicTime::now();
402
403             DeferGC deferGC(vm.heap);
404             auto bytecodeGenerator = makeUnique<BytecodeGenerator>(vm, node, unlinkedCodeBlock, codeGenerationMode, environment);
405             auto result = bytecodeGenerator->generate();
406
407             if (UNLIKELY(Options::reportBytecodeCompileTimes())) {
408                 MonotonicTime after = MonotonicTime::now();
409                 dataLogLn(result.isValid() ? "Failed to compile #" : "Compiled #", CodeBlockHash(sourceCode, unlinkedCodeBlock->isConstructor() ? CodeForConstruct : CodeForCall), " into bytecode ", bytecodeGenerator->instructions().size(), " instructions in ", (after - before).milliseconds(), " ms.");
410             }
411             return result;
412         }
413
414         bool isArgumentNumber(const Identifier&, int);
415
416         Variable variable(const Identifier&, ThisResolutionType = ThisResolutionType::Local);
417         
418         enum ExistingVariableMode { VerifyExisting, IgnoreExisting };
419         void createVariable(const Identifier&, VarKind, SymbolTable*, ExistingVariableMode = VerifyExisting); // Creates the variable, or asserts that the already-created variable is sufficiently compatible.
420         
421         // Returns the register storing "this"
422         RegisterID* thisRegister() { return &m_thisRegister; }
423         RegisterID* argumentsRegister() { return m_argumentsRegister; }
424         RegisterID* newTarget()
425         {
426             ASSERT(m_newTargetRegister);
427             return m_newTargetRegister;
428         }
429
430         RegisterID* scopeRegister() { return m_scopeRegister; }
431
432         RegisterID* generatorRegister() { return m_generatorRegister; }
433
434         RegisterID* promiseRegister() { return m_promiseRegister; }
435
436         // Returns the next available temporary register. Registers returned by
437         // newTemporary require a modified form of reference counting: any
438         // register with a refcount of 0 is considered "available", meaning that
439         // the next instruction may overwrite it.
440         RegisterID* newTemporary();
441
442         // The same as newTemporary(), but this function returns "suggestion" if
443         // "suggestion" is a temporary. This function is helpful in situations
444         // where you've put "suggestion" in a RefPtr, but you'd like to allow
445         // the next instruction to overwrite it anyway.
446         RegisterID* newTemporaryOr(RegisterID* suggestion) { return suggestion->isTemporary() ? suggestion : newTemporary(); }
447
448         // Functions for handling of dst register
449
450         RegisterID* ignoredResult() { return &m_ignoredResultRegister; }
451
452         // This will be allocated in the temporary region of registers, but it will
453         // not be marked as a temporary. This will ensure that finalDestination() does
454         // not overwrite a block scope variable that it mistakes as a temporary. These
455         // registers can be (and are) reclaimed when the lexical scope they belong to
456         // is no longer on the symbol table stack.
457         RegisterID* newBlockScopeVariable();
458
459         // Returns a place to write intermediate values of an operation
460         // which reuses dst if it is safe to do so.
461         RegisterID* tempDestination(RegisterID* dst)
462         {
463             return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary();
464         }
465
466         // Returns the place to write the final output of an operation.
467         RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0)
468         {
469             if (originalDst && originalDst != ignoredResult())
470                 return originalDst;
471             ASSERT(tempDst != ignoredResult());
472             if (tempDst && tempDst->isTemporary())
473                 return tempDst;
474             return newTemporary();
475         }
476
477         RegisterID* destinationForAssignResult(RegisterID* dst)
478         {
479             if (dst && dst != ignoredResult())
480                 return dst->isTemporary() ? dst : newTemporary();
481             return 0;
482         }
483
484         // Moves src to dst if dst is not null and is different from src, otherwise just returns src.
485         RegisterID* move(RegisterID* dst, RegisterID* src)
486         {
487             return dst == ignoredResult() ? nullptr : (dst && dst != src) ? emitMove(dst, src) : src;
488         }
489
490         Ref<LabelScope> newLabelScope(LabelScope::Type, const Identifier* = 0);
491         Ref<Label> newLabel();
492         Ref<Label> newEmittedLabel();
493
494         void emitNode(RegisterID* dst, StatementNode* n)
495         {
496             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
497             return emitNodeInTailPosition(dst, n);
498         }
499
500         void emitNodeInTailPosition(RegisterID* dst, StatementNode* 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                 emitThrowExpressionTooDeepException();
506                 return;
507             }
508             if (UNLIKELY(n->needsDebugHook()))
509                 emitDebugHook(n);
510             n->emitBytecode(*this, dst);
511         }
512
513         void recordOpcode(OpcodeID);
514
515         ALWAYS_INLINE unsigned addMetadataFor(OpcodeID opcodeID)
516         {
517             return m_codeBlock->metadata().addEntry(opcodeID);
518         }
519
520         void emitNode(StatementNode* n)
521         {
522             emitNode(nullptr, n);
523         }
524
525         void emitNodeInTailPosition(StatementNode* n)
526         {
527             emitNodeInTailPosition(nullptr, n);
528         }
529
530         RegisterID* emitNode(RegisterID* dst, ExpressionNode* n)
531         {
532             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
533             return emitNodeInTailPosition(dst, n);
534         }
535
536         RegisterID* emitNodeInTailPosition(RegisterID* dst, ExpressionNode* n)
537         {
538             // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
539             ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
540             if (UNLIKELY(!m_vm.isSafeToRecurse()))
541                 return emitThrowExpressionTooDeepException();
542             if (UNLIKELY(n->needsDebugHook()))
543                 emitDebugHook(n);
544             return n->emitBytecode(*this, dst);
545         }
546
547         RegisterID* emitNode(ExpressionNode* n)
548         {
549             return emitNode(nullptr, n);
550         }
551
552         RegisterID* emitNodeInTailPosition(ExpressionNode* n)
553         {
554             return emitNodeInTailPosition(nullptr, n);
555         }
556
557         RegisterID* emitDefineClassElements(PropertyListNode* n, RegisterID* constructor, RegisterID* prototype)
558         {
559             ASSERT(constructor->refCount() && prototype->refCount());
560             if (UNLIKELY(!m_vm.isSafeToRecurse()))
561                 return emitThrowExpressionTooDeepException();
562             if (UNLIKELY(n->needsDebugHook()))
563                 emitDebugHook(n);
564             return n->emitBytecode(*this, constructor, prototype);
565         }
566
567         RegisterID* emitNodeForProperty(RegisterID* dst, ExpressionNode* node)
568         {
569             if (node->isString()) {
570                 if (Optional<uint32_t> index = parseIndex(static_cast<StringNode*>(node)->value()))
571                     return emitLoad(dst, jsNumber(index.value()));
572             }
573             return emitNode(dst, node);
574         }
575
576         RegisterID* emitNodeForProperty(ExpressionNode* n)
577         {
578             return emitNodeForProperty(nullptr, n);
579         }
580
581         void emitNodeInConditionContext(ExpressionNode* n, Label& trueTarget, Label& falseTarget, FallThroughMode fallThroughMode)
582         {
583             if (UNLIKELY(!m_vm.isSafeToRecurse())) {
584                 emitThrowExpressionTooDeepException();
585                 return;
586             }
587             n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMode);
588         }
589
590         void emitExpressionInfo(const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
591         {            
592             ASSERT(divot.offset >= divotStart.offset);
593             ASSERT(divotEnd.offset >= divot.offset);
594
595             int sourceOffset = m_scopeNode->source().startOffset();
596             unsigned firstLine = m_scopeNode->source().firstLine().oneBasedInt();
597
598             int divotOffset = divot.offset - sourceOffset;
599             int startOffset = divot.offset - divotStart.offset;
600             int endOffset = divotEnd.offset - divot.offset;
601
602             unsigned line = divot.line;
603             ASSERT(line >= firstLine);
604             line -= firstLine;
605
606             int lineStart = divot.lineStartOffset;
607             if (lineStart > sourceOffset)
608                 lineStart -= sourceOffset;
609             else
610                 lineStart = 0;
611
612             if (divotOffset < lineStart)
613                 return;
614
615             unsigned column = divotOffset - lineStart;
616
617             unsigned instructionOffset = instructions().size();
618             if (!m_isBuiltinFunction)
619                 m_codeBlock->addExpressionInfo(instructionOffset, divotOffset, startOffset, endOffset, line, column);
620         }
621
622
623         ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure)
624         {
625             return (m_codeType != FunctionCode || rightHasAssignments) && !rightIsPure;
626         }
627
628         ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
629         {
630             if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
631                 RefPtr<RegisterID> dst = newTemporary();
632                 emitNode(dst.get(), n);
633                 return dst;
634             }
635
636             return emitNode(n);
637         }
638
639         ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSideForProperty(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
640         {
641             if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
642                 RefPtr<RegisterID> dst = newTemporary();
643                 emitNodeForProperty(dst.get(), n);
644                 return dst;
645             }
646
647             return emitNodeForProperty(n);
648         }
649
650         void hoistSloppyModeFunctionIfNecessary(const Identifier& functionName);
651
652     private:
653         void emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot);
654     public:
655
656         // This doesn't emit expression info. If using this, make sure you shouldn't be emitting text offset.
657         void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag); 
658         // These variables are associated with variables in a program. They could be Locals, LocalClosureVar, or ClosureVar.
659         void emitProfileType(RegisterID* registerToProfile, const Variable&, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
660
661         void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
662         // These are not associated with variables and don't have a global id.
663         void emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
664
665         void emitProfileControlFlow(int);
666         
667         RegisterID* emitLoadArrowFunctionLexicalEnvironment(const Identifier&);
668         RegisterID* ensureThis();
669         void emitLoadThisFromArrowFunctionLexicalEnvironment();
670         RegisterID* emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
671
672         unsigned addConstantIndex();
673         RegisterID* emitLoad(RegisterID* dst, bool);
674         RegisterID* emitLoad(RegisterID* dst, const Identifier&);
675         RegisterID* emitLoad(RegisterID* dst, JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
676         RegisterID* emitLoad(RegisterID* dst, IdentifierSet& excludedList);
677
678         template<typename UnaryOp, typename = std::enable_if_t<UnaryOp::opcodeID != op_negate>>
679         RegisterID* emitUnaryOp(RegisterID* dst, RegisterID* src)
680         {
681             UnaryOp::emit(this, dst, src);
682             return dst;
683         }
684
685         RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src, OperandTypes);
686
687         template<typename BinaryOp>
688         std::enable_if_t<
689             BinaryOp::opcodeID != op_add
690             && BinaryOp::opcodeID != op_mul
691             && BinaryOp::opcodeID != op_sub
692             && BinaryOp::opcodeID != op_div,
693             RegisterID*>
694         emitBinaryOp(RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes)
695         {
696             BinaryOp::emit(this, dst, src1, src2);
697             return dst;
698         }
699
700         template<typename BinaryOp>
701         std::enable_if_t<
702             BinaryOp::opcodeID == op_add
703             || BinaryOp::opcodeID == op_mul
704             || BinaryOp::opcodeID == op_sub
705             || BinaryOp::opcodeID == op_div,
706             RegisterID*>
707         emitBinaryOp(RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
708         {
709             BinaryOp::emit(this, dst, src1, src2, types);
710             return dst;
711         }
712
713         RegisterID* emitBinaryOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes);
714
715         template<typename EqOp>
716         RegisterID* emitEqualityOp(RegisterID* dst, RegisterID* src1, RegisterID* src2)
717         {
718             if (!emitEqualityOpImpl(dst, src1, src2))
719                 EqOp::emit(this, dst, src1, src2);
720             return dst;
721         }
722
723         bool emitEqualityOpImpl(RegisterID* dst, RegisterID* src1, RegisterID* src2);
724
725         RegisterID* emitCreateThis(RegisterID* dst);
726         RegisterID* emitCreatePromise(RegisterID* dst, RegisterID* newTarget, bool isInternalPromise);
727         void emitTDZCheck(RegisterID* target);
728         bool needsTDZCheck(const Variable&);
729         void emitTDZCheckIfNecessary(const Variable&, RegisterID* target, RegisterID* scope);
730         void liftTDZCheckIfPossible(const Variable&);
731         RegisterID* emitNewObject(RegisterID* dst);
732         RegisterID* emitNewPromise(RegisterID* dst, bool isInternalPromise);
733         RegisterID* emitNewArray(RegisterID* dst, ElementNode*, unsigned length, IndexingType recommendedIndexingType); // stops at first elision
734         RegisterID* emitNewArrayBuffer(RegisterID* dst, JSImmutableButterfly*, IndexingType recommendedIndexingType);
735         // FIXME: new_array_with_spread should use an array allocation profile and take a recommendedIndexingType
736         RegisterID* emitNewArrayWithSpread(RegisterID* dst, ElementNode*);
737         RegisterID* emitNewArrayWithSize(RegisterID* dst, RegisterID* length);
738
739         RegisterID* emitNewFunction(RegisterID* dst, FunctionMetadataNode*);
740         RegisterID* emitNewFunctionExpression(RegisterID* dst, FuncExprNode*);
741         RegisterID* emitNewDefaultConstructor(RegisterID* dst, ConstructorKind, const Identifier& name, const Identifier& ecmaName, const SourceCode& classSource);
742         RegisterID* emitNewArrowFunctionExpression(RegisterID*, ArrowFuncExprNode*);
743         RegisterID* emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode*);
744         RegisterID* emitNewRegExp(RegisterID* dst, RegExp*);
745
746         void emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name);
747
748         RegisterID* moveLinkTimeConstant(RegisterID* dst, LinkTimeConstant);
749         RegisterID* moveEmptyValue(RegisterID* dst);
750
751         RegisterID* emitToNumber(RegisterID* dst, RegisterID* src);
752         RegisterID* emitToString(RegisterID* dst, RegisterID* src);
753         RegisterID* emitToObject(RegisterID* dst, RegisterID* src, const Identifier& message);
754         RegisterID* emitInc(RegisterID* srcDst);
755         RegisterID* emitDec(RegisterID* srcDst);
756
757         RegisterID* emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue);
758         RegisterID* emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype);
759         RegisterID* emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue);
760         RegisterID* emitTypeOf(RegisterID* dst, RegisterID* src);
761         RegisterID* emitInByVal(RegisterID* dst, RegisterID* property, RegisterID* base);
762         RegisterID* emitInById(RegisterID* dst, RegisterID* base, const Identifier& property);
763
764         RegisterID* emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
765         RegisterID* emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
766         RegisterID* emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property);
767         RegisterID* emitDirectGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
768         RegisterID* emitPutById(RegisterID* base, const Identifier& property, RegisterID* value);
769         RegisterID* emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value);
770         RegisterID* emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType);
771         RegisterID* emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier&);
772         RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
773         RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property);
774         RegisterID* emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
775         RegisterID* emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value);
776         RegisterID* emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
777         RegisterID* emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
778
779         RegisterID* emitGetInternalField(RegisterID* dst, RegisterID* base, unsigned index);
780         RegisterID* emitPutInternalField(RegisterID* base, unsigned index, RegisterID* value);
781
782         void emitSuperSamplerBegin();
783         void emitSuperSamplerEnd();
784
785         RegisterID* emitIdWithProfile(RegisterID* src, SpeculatedType profile);
786         void emitUnreachable();
787
788         void emitPutGetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* getter);
789         void emitPutSetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* setter);
790         void emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter);
791         void emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* getter);
792         void emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* setter);
793
794         RegisterID* emitGetArgument(RegisterID* dst, int32_t index);
795
796         // Initialize object with generator fields (@generatorThis, @generatorNext, @generatorState, @generatorFrame)
797         void emitPutGeneratorFields(RegisterID* nextFunction);
798         
799         void emitPutAsyncGeneratorFields(RegisterID* nextFunction);
800
801         ExpectedFunction expectedFunctionForIdentifier(const Identifier&);
802         RegisterID* emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
803         RegisterID* emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
804         RegisterID* emitCallEval(RegisterID* dst, RegisterID* func, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
805         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);
806         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);
807         RegisterID* emitCallForwardArgumentsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
808
809         enum PropertyDescriptorOption {
810             PropertyConfigurable = 1,
811             PropertyWritable     = 1 << 1,
812             PropertyEnumerable   = 1 << 2,
813         };
814         void emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
815             RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition&);
816
817         void emitEnumeration(ThrowableExpressionData* enumerationNode, ExpressionNode* subjectNode, const ScopedLambda<void(BytecodeGenerator&, RegisterID*)>& callBack, ForOfNode* = nullptr, RegisterID* forLoopSymbolTable = nullptr);
818
819         RegisterID* emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode*);
820         RegisterID* emitGetGlobalPrivate(RegisterID* dst, const Identifier& property);
821
822         enum class ReturnFrom { Normal, Finally };
823         RegisterID* emitReturn(RegisterID* src, ReturnFrom = ReturnFrom::Normal);
824         RegisterID* emitEnd(RegisterID* src);
825
826         RegisterID* emitConstruct(RegisterID* dst, RegisterID* func, RegisterID* lazyThis, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd);
827         RegisterID* emitStrcat(RegisterID* dst, RegisterID* src, int count);
828         void emitToPrimitive(RegisterID* dst, RegisterID* src);
829
830         ResolveType resolveType();
831         RegisterID* emitResolveConstantLocal(RegisterID* dst, const Variable&);
832         RegisterID* emitResolveScope(RegisterID* dst, const Variable&);
833         RegisterID* emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable&, ResolveMode);
834         RegisterID* emitPutToScope(RegisterID* scope, const Variable&, RegisterID* value, ResolveMode, InitializationMode);
835
836         RegisterID* emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier&);
837
838         RegisterID* initializeVariable(const Variable&, RegisterID* value);
839
840         void emitLabel(Label&);
841         void emitLoopHint();
842         void emitJump(Label& target);
843         void emitJumpIfTrue(RegisterID* cond, Label& target);
844         void emitJumpIfFalse(RegisterID* cond, Label& target);
845         void emitJumpIfNotFunctionCall(RegisterID* cond, Label& target);
846         void emitJumpIfNotFunctionApply(RegisterID* cond, Label& target);
847
848         template<typename BinOp, typename JmpOp>
849         bool fuseCompareAndJump(RegisterID* cond, Label& target, bool swapOperands = false);
850
851         template<typename UnaryOp, typename JmpOp>
852         bool fuseTestAndJmp(RegisterID* cond, Label& target);
853
854         void emitEnter();
855         void emitCheckTraps();
856
857         RegisterID* emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
858         RegisterID* emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator);
859         RegisterID* emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
860         RegisterID* emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base);
861         RegisterID* emitGetEnumerableLength(RegisterID* dst, RegisterID* base);
862         RegisterID* emitGetStructurePropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length);
863         RegisterID* emitGetGenericPropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length, RegisterID* structureEnumerator);
864         RegisterID* emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
865         RegisterID* emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
866         RegisterID* emitToIndexString(RegisterID* dst, RegisterID* index);
867
868         RegisterID* emitIsCellWithType(RegisterID* dst, RegisterID* src, JSType);
869         RegisterID* emitIsJSArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ArrayType); }
870         RegisterID* emitIsPromise(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSPromiseType); }
871         RegisterID* emitIsProxyObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ProxyObjectType); }
872         RegisterID* emitIsRegExpObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, RegExpObjectType); }
873         RegisterID* emitIsMap(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSMapType); }
874         RegisterID* emitIsSet(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSSetType); }
875         RegisterID* emitIsObject(RegisterID* dst, RegisterID* src);
876         RegisterID* emitIsNumber(RegisterID* dst, RegisterID* src);
877         RegisterID* emitIsUndefined(RegisterID* dst, RegisterID* src);
878         RegisterID* emitIsUndefinedOrNull(RegisterID* dst, RegisterID* src);
879         RegisterID* emitIsEmpty(RegisterID* dst, RegisterID* src);
880         RegisterID* emitIsDerivedArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, DerivedArrayType); }
881         void emitRequireObjectCoercible(RegisterID* value, const String& error);
882
883         RegisterID* emitIteratorNext(RegisterID* dst, RegisterID* nextMethod, RegisterID* iterator, const ThrowableExpressionData* node, JSC::EmitAwait = JSC::EmitAwait::No);
884         RegisterID* emitIteratorNextWithValue(RegisterID* dst, RegisterID* nextMethod, RegisterID* iterator, RegisterID* value, const ThrowableExpressionData* node);
885         void emitIteratorClose(RegisterID* iterator, const ThrowableExpressionData* node, EmitAwait = EmitAwait::No);
886
887         RegisterID* emitRestParameter(RegisterID* result, unsigned numParametersToSkip);
888
889         bool emitReadOnlyExceptionIfNeeded(const Variable&);
890
891         // Start a try block. 'start' must have been emitted.
892         TryData* pushTry(Label& start, Label& handlerLabel, HandlerType);
893         // End a try block. 'end' must have been emitted.
894         void popTry(TryData*, Label& end);
895
896         void emitOutOfLineCatchHandler(RegisterID* thrownValueRegister, RegisterID* completionTypeRegister, TryData*);
897         void emitOutOfLineFinallyHandler(RegisterID* exceptionRegister, RegisterID* completionTypeRegister, TryData*);
898
899     private:
900         static const int CurrentLexicalScopeIndex = -2;
901         static const int OutermostLexicalScopeIndex = -1;
902
903         int currentLexicalScopeIndex() const
904         {
905             int size = static_cast<int>(m_lexicalScopeStack.size());
906             ASSERT(static_cast<size_t>(size) == m_lexicalScopeStack.size());
907             ASSERT(size >= 0);
908             if (!size)
909                 return OutermostLexicalScopeIndex;
910             return size - 1;
911         }
912
913         void emitOutOfLineExceptionHandler(RegisterID* exceptionRegister, RegisterID* thrownValueRegister, RegisterID* completionTypeRegister, TryData*);
914
915     public:
916         void restoreScopeRegister();
917         void restoreScopeRegister(int lexicalScopeIndex);
918
919         int labelScopeDepthToLexicalScopeIndex(int labelScopeDepth);
920
921         void emitThrow(RegisterID*);
922         RegisterID* emitArgumentCount(RegisterID*);
923
924         void emitThrowStaticError(ErrorType, RegisterID*);
925         void emitThrowStaticError(ErrorType, const Identifier& message);
926         void emitThrowReferenceError(const String& message);
927         void emitThrowTypeError(const String& message);
928         void emitThrowTypeError(const Identifier& message);
929         void emitThrowRangeError(const Identifier& message);
930         void emitThrowOutOfMemoryError();
931
932         void emitPushCatchScope(VariableEnvironment&);
933         void emitPopCatchScope(VariableEnvironment&);
934
935         RegisterID* emitGetIterator(RegisterID*, ThrowableExpressionData*);
936         RegisterID* emitGetAsyncIterator(RegisterID*, ThrowableExpressionData*);
937
938         void emitAwait(RegisterID*);
939         void emitGetScope();
940         RegisterID* emitPushWithScope(RegisterID* objectScope);
941         void emitPopWithScope();
942         void emitPutThisToArrowFunctionContextScope();
943         void emitPutNewTargetToArrowFunctionContextScope();
944         void emitPutDerivedConstructorToArrowFunctionContextScope();
945         RegisterID* emitLoadDerivedConstructorFromArrowFunctionLexicalEnvironment();
946
947         void emitDebugHook(DebugHookType, const JSTextPosition&);
948         void emitDebugHook(DebugHookType, unsigned line, unsigned charOffset, unsigned lineStart);
949         void emitDebugHook(StatementNode*);
950         void emitDebugHook(ExpressionNode*);
951         void emitWillLeaveCallFrameDebugHook();
952
953         void emitLoad(RegisterID* completionTypeRegister, CompletionType type)
954         {
955             emitLoad(completionTypeRegister, JSValue(static_cast<int>(type)));
956         }
957
958         template<typename CompareOp>
959         void emitJumpIf(RegisterID* completionTypeRegister, CompletionType, Label& jumpTarget);
960
961         bool emitJumpViaFinallyIfNeeded(int targetLabelScopeDepth, Label& jumpTarget);
962         bool emitReturnViaFinallyIfNeeded(RegisterID* returnRegister);
963         void emitFinallyCompletion(FinallyContext&, Label& normalCompletionLabel);
964
965     public:
966         void pushFinallyControlFlowScope(FinallyContext&);
967         void popFinallyControlFlowScope();
968
969         void pushOptionalChainTarget();
970         void popOptionalChainTarget();
971         void popOptionalChainTarget(RegisterID* dst, bool isDelete);
972         void emitOptionalCheck(RegisterID* src);
973
974         void pushIndexedForInScope(RegisterID* local, RegisterID* index);
975         void popIndexedForInScope(RegisterID* local);
976         void pushStructureForInScope(RegisterID* local, RegisterID* index, RegisterID* property, RegisterID* enumerator);
977         void popStructureForInScope(RegisterID* local);
978
979         LabelScope* breakTarget(const Identifier&);
980         LabelScope* continueTarget(const Identifier&);
981
982         void beginSwitch(RegisterID*, SwitchInfo::SwitchType);
983         void endSwitch(uint32_t clauseCount, const Vector<Ref<Label>, 8>&, ExpressionNode**, Label& defaultLabel, int32_t min, int32_t range);
984
985         void emitYieldPoint(RegisterID*, JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason);
986
987         void emitGeneratorStateLabel();
988         void emitGeneratorStateChange(int32_t state);
989         RegisterID* emitYield(RegisterID* argument, JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason = JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason::Yield);
990         RegisterID* emitDelegateYield(RegisterID* argument, ThrowableExpressionData*);
991         RegisterID* generatorStateRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::State)]; }
992         RegisterID* generatorValueRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Value)]; }
993         RegisterID* generatorResumeModeRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::ResumeMode)]; }
994         RegisterID* generatorFrameRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Frame)]; }
995
996         CodeType codeType() const { return m_codeType; }
997
998         bool shouldBeConcernedWithCompletionValue() const { return m_codeType != FunctionCode; }
999
1000         bool shouldEmitDebugHooks() const { return m_codeGenerationMode.contains(CodeGenerationMode::Debugger) && !m_isBuiltinFunction; }
1001         bool shouldEmitTypeProfilerHooks() const { return m_codeGenerationMode.contains(CodeGenerationMode::TypeProfiler); }
1002         bool shouldEmitControlFlowProfilerHooks() const { return m_codeGenerationMode.contains(CodeGenerationMode::ControlFlowProfiler); }
1003         
1004         bool isStrictMode() const { return m_codeBlock->isStrictMode(); }
1005
1006         SourceParseMode parseMode() const { return m_codeBlock->parseMode(); }
1007         
1008         bool isBuiltinFunction() const { return m_isBuiltinFunction; }
1009
1010         OpcodeID lastOpcodeID() const { return m_lastOpcodeID; }
1011         
1012         bool isDerivedConstructorContext() { return m_derivedContextType == DerivedContextType::DerivedConstructorContext; }
1013         bool isDerivedClassContext() { return m_derivedContextType == DerivedContextType::DerivedMethodContext; }
1014         bool isArrowFunction() { return m_codeBlock->isArrowFunction(); }
1015
1016         enum class TDZCheckOptimization { Optimize, DoNotOptimize };
1017         enum class NestedScopeType { IsNested, IsNotNested };
1018     private:
1019         enum class TDZRequirement { UnderTDZ, NotUnderTDZ };
1020         enum class ScopeType { CatchScope, LetConstScope, FunctionNameScope };
1021         enum class ScopeRegisterType { Var, Block };
1022         void pushLexicalScopeInternal(VariableEnvironment&, TDZCheckOptimization, NestedScopeType, RegisterID** constantSymbolTableResult, TDZRequirement, ScopeType, ScopeRegisterType);
1023         void initializeBlockScopedFunctions(VariableEnvironment&, FunctionStack&, RegisterID* constantSymbolTable);
1024         void popLexicalScopeInternal(VariableEnvironment&);
1025         template<typename LookUpVarKindFunctor>
1026         bool instantiateLexicalVariables(const VariableEnvironment&, SymbolTable*, ScopeRegisterType, LookUpVarKindFunctor);
1027         void emitPrefillStackTDZVariables(const VariableEnvironment&, SymbolTable*);
1028         RegisterID* emitGetParentScope(RegisterID* dst, RegisterID* scope);
1029         void emitPushFunctionNameScope(const Identifier& property, RegisterID* value, bool isCaptured);
1030         void emitNewFunctionExpressionCommon(RegisterID*, FunctionMetadataNode*);
1031         
1032         bool isNewTargetUsedInInnerArrowFunction();
1033         bool isArgumentsUsedInInnerArrowFunction();
1034
1035         void emitToThis();
1036
1037         RegisterID* emitMove(RegisterID* dst, RegisterID* src);
1038
1039         bool canDoPeepholeOptimization() const { return m_lastOpcodeID != op_end; }
1040
1041     public:
1042         bool isSuperUsedInInnerArrowFunction();
1043         bool isSuperCallUsedInInnerArrowFunction();
1044         bool isThisUsedInInnerArrowFunction();
1045         void pushLexicalScope(VariableEnvironmentNode*, TDZCheckOptimization, NestedScopeType = NestedScopeType::IsNotNested, RegisterID** constantSymbolTableResult = nullptr, bool shouldInitializeBlockScopedFunctions = true);
1046         void popLexicalScope(VariableEnvironmentNode*);
1047         void prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode*, RegisterID* loopSymbolTable);
1048         int labelScopeDepth() const;
1049         UnlinkedArrayProfile newArrayProfile();
1050
1051     private:
1052         ParserError generate();
1053         void reclaimFreeRegisters();
1054         Variable variableForLocalEntry(const Identifier&, const SymbolTableEntry&, int symbolTableConstantIndex, bool isLexicallyScoped);
1055
1056         RegisterID* kill(RegisterID* dst)
1057         {
1058             m_staticPropertyAnalyzer.kill(dst);
1059             return dst;
1060         }
1061
1062         void retrieveLastUnaryOp(int& dstIndex, int& srcIndex);
1063         ALWAYS_INLINE void rewind();
1064
1065         void allocateCalleeSaveSpace();
1066         void allocateAndEmitScope();
1067
1068         template<typename JumpOp>
1069         void setTargetForJumpInstruction(InstructionStream::MutableRef&, int target);
1070
1071         using BigIntMapEntry = std::tuple<UniquedStringImpl*, uint8_t, bool>;
1072
1073         using NumberMap = HashMap<double, JSValue>;
1074         using IdentifierStringMap = HashMap<UniquedStringImpl*, JSString*, IdentifierRepHash>;
1075         using IdentifierBigIntMap = HashMap<BigIntMapEntry, JSBigInt*>;
1076         using TemplateObjectDescriptorSet = HashSet<Ref<TemplateObjectDescriptor>>;
1077         using TemplateDescriptorMap = HashMap<uint64_t, JSTemplateObjectDescriptor*, WTF::IntHash<uint64_t>, WTF::UnsignedWithZeroKeyHashTraits<uint64_t>>;
1078
1079         // Helper for emitCall() and emitConstruct(). This works because the set of
1080         // expected functions have identical behavior for both call and construct
1081         // (i.e. "Object()" is identical to "new Object()").
1082         ExpectedFunction emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, Label& done);
1083         
1084         template<typename CallOp>
1085         RegisterID* emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1086
1087         RegisterID* emitCallIterator(RegisterID* iterator, RegisterID* argument, ThrowableExpressionData*);
1088         RegisterID* newRegister();
1089
1090         // Adds an anonymous local var slot. To give this slot a name, add it to symbolTable().
1091         RegisterID* addVar()
1092         {
1093             ++m_codeBlock->m_numVars;
1094             RegisterID* result = newRegister();
1095             ASSERT(VirtualRegister(result->index()).toLocal() == m_codeBlock->m_numVars - 1);
1096             result->ref(); // We should never free this slot.
1097             return result;
1098         }
1099
1100         // Initializes the stack form the parameter; does nothing for the symbol table.
1101         RegisterID* initializeNextParameter();
1102         UniquedStringImpl* visibleNameForParameter(DestructuringPatternNode*);
1103         
1104         RegisterID& registerFor(VirtualRegister reg)
1105         {
1106             if (reg.isLocal())
1107                 return m_calleeLocals[reg.toLocal()];
1108
1109             if (reg.offset() == CallFrameSlot::callee)
1110                 return m_calleeRegister;
1111
1112             ASSERT(m_parameters.size());
1113             return m_parameters[reg.toArgument()];
1114         }
1115
1116         bool hasConstant(const Identifier&) const;
1117         unsigned addConstant(const Identifier&);
1118         RegisterID* addConstantValue(JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
1119         RegisterID* addConstantEmptyValue();
1120
1121         UnlinkedFunctionExecutable* makeFunction(FunctionMetadataNode* metadata)
1122         {
1123             DerivedContextType newDerivedContextType = DerivedContextType::None;
1124
1125             if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode, SourceParseMode::AsyncArrowFunctionBodyMode).contains(metadata->parseMode())) {
1126                 if (constructorKind() == ConstructorKind::Extends || isDerivedConstructorContext())
1127                     newDerivedContextType = DerivedContextType::DerivedConstructorContext;
1128                 else if (m_codeBlock->isClassContext() || isDerivedClassContext())
1129                     newDerivedContextType = DerivedContextType::DerivedMethodContext;
1130             }
1131
1132             Optional<CompactVariableMap::Handle> optionalVariablesUnderTDZ = getVariablesUnderTDZ();
1133
1134             // FIXME: These flags, ParserModes and propagation to XXXCodeBlocks should be reorganized.
1135             // https://bugs.webkit.org/show_bug.cgi?id=151547
1136             SourceParseMode parseMode = metadata->parseMode();
1137             ConstructAbility constructAbility = constructAbilityForParseMode(parseMode);
1138             if (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() != ConstructorKind::None)
1139                 constructAbility = ConstructAbility::CanConstruct;
1140
1141             return UnlinkedFunctionExecutable::create(m_vm, m_scopeNode->source(), metadata, isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, constructAbility, scriptMode(), WTFMove(optionalVariablesUnderTDZ), newDerivedContextType);
1142         }
1143
1144         Optional<CompactVariableMap::Handle> getVariablesUnderTDZ();
1145
1146         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);
1147         template<typename CallOp>
1148         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);
1149         
1150         void emitLogShadowChickenPrologueIfNecessary();
1151         void emitLogShadowChickenTailIfNecessary();
1152
1153         void initializeParameters(FunctionParameters&);
1154         void initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables);
1155         void initializeDefaultParameterValuesAndSetupFunctionScopeStack(FunctionParameters&, bool isSimpleParameterList, FunctionNode*, SymbolTable*, int symbolTableConstantIndex, const ScopedLambda<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope);
1156         void initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable = nullptr, bool canReuseLexicalEnvironment = false);
1157         bool needsDerivedConstructorInArrowFunctionLexicalEnvironment();
1158
1159         enum class TDZNecessityLevel {
1160             NotNeeded,
1161             Optimize,
1162             DoNotOptimize
1163         };
1164         typedef HashMap<RefPtr<UniquedStringImpl>, TDZNecessityLevel, IdentifierRepHash> TDZMap;
1165
1166     public:
1167         JSString* addStringConstant(const Identifier&);
1168         JSValue addBigIntConstant(const Identifier&, uint8_t radix, bool sign);
1169         RegisterID* addTemplateObjectConstant(Ref<TemplateObjectDescriptor>&&, int);
1170
1171         const InstructionStream& instructions() const { return m_writer; }
1172
1173         RegisterID* emitThrowExpressionTooDeepException();
1174
1175         void write(uint8_t byte) { m_writer.write(byte); }
1176         void write(uint16_t h) { m_writer.write(h); }
1177         void write(uint32_t i) { m_writer.write(i); }
1178         void write(int8_t byte) { m_writer.write(static_cast<uint8_t>(byte)); }
1179         void write(int16_t h) { m_writer.write(static_cast<uint16_t>(h)); }
1180         void write(int32_t i) { m_writer.write(static_cast<uint32_t>(i)); }
1181         void alignWideOpcode16();
1182         void alignWideOpcode32();
1183
1184         class PreservedTDZStack {
1185         private:
1186             Vector<TDZMap> m_preservedTDZStack;
1187             friend class BytecodeGenerator;
1188         };
1189
1190         void preserveTDZStack(PreservedTDZStack&);
1191         void restoreTDZStack(const PreservedTDZStack&);
1192
1193         template<typename Func>
1194         void withWriter(InstructionStreamWriter& writer, const Func& fn)
1195         {
1196             auto prevLastOpcodeID = m_lastOpcodeID;
1197             auto prevLastInstruction = m_lastInstruction;
1198             m_writer.swap(writer);
1199             m_lastOpcodeID = op_end;
1200             m_lastInstruction = m_writer.ref();
1201             fn();
1202             m_writer.swap(writer);
1203             m_lastOpcodeID = prevLastOpcodeID;
1204             m_lastInstruction = prevLastInstruction;
1205         }
1206
1207     private:
1208         InstructionStreamWriter m_writer;
1209
1210         OptionSet<CodeGenerationMode> m_codeGenerationMode;
1211
1212         struct LexicalScopeStackEntry {
1213             SymbolTable* m_symbolTable;
1214             RegisterID* m_scope;
1215             bool m_isWithScope;
1216             int m_symbolTableConstantIndex;
1217         };
1218         Vector<LexicalScopeStackEntry> m_lexicalScopeStack;
1219
1220         Vector<TDZMap> m_TDZStack;
1221         Optional<size_t> m_varScopeLexicalScopeStackIndex;
1222         void pushTDZVariables(const VariableEnvironment&, TDZCheckOptimization, TDZRequirement);
1223
1224         ScopeNode* const m_scopeNode;
1225         Strong<UnlinkedCodeBlock> m_codeBlock;
1226
1227         // Some of these objects keep pointers to one another. They are arranged
1228         // to ensure a sane destruction order that avoids references to freed memory.
1229         HashSet<RefPtr<UniquedStringImpl>, IdentifierRepHash> m_functions;
1230         RegisterID m_ignoredResultRegister;
1231         RegisterID m_thisRegister;
1232         RegisterID m_calleeRegister;
1233         RegisterID* m_scopeRegister { nullptr };
1234         RegisterID* m_topMostScope { nullptr };
1235         RegisterID* m_argumentsRegister { nullptr };
1236         RegisterID* m_lexicalEnvironmentRegister { nullptr };
1237         RegisterID* m_generatorRegister { nullptr };
1238         RegisterID* m_emptyValueRegister { nullptr };
1239         RegisterID* m_newTargetRegister { nullptr };
1240         RegisterID* m_isDerivedConstuctor { nullptr };
1241         RegisterID* m_linkTimeConstantRegisters[LinkTimeConstantCount];
1242         RegisterID* m_arrowFunctionContextLexicalEnvironmentRegister { nullptr };
1243         RegisterID* m_promiseRegister { nullptr };
1244
1245         FinallyContext* m_currentFinallyContext { nullptr };
1246
1247         SegmentedVector<RegisterID*, 16> m_localRegistersForCalleeSaveRegisters;
1248         SegmentedVector<RegisterID, 32> m_constantPoolRegisters;
1249         SegmentedVector<RegisterID, 32> m_calleeLocals;
1250         SegmentedVector<RegisterID, 32> m_parameters;
1251         SegmentedVector<Label, 32> m_labels;
1252         SegmentedVector<LabelScope, 32> m_labelScopes;
1253         unsigned m_finallyDepth { 0 };
1254         unsigned m_localScopeDepth { 0 };
1255         const CodeType m_codeType;
1256
1257         unsigned localScopeDepth() const;
1258         void pushLocalControlFlowScope();
1259         void popLocalControlFlowScope();
1260
1261         // FIXME: Restore overflow checking with UnsafeVectorOverflow once SegmentVector supports it.
1262         // https://bugs.webkit.org/show_bug.cgi?id=165980
1263         SegmentedVector<ControlFlowScope, 16> m_controlFlowScopeStack;
1264         Vector<SwitchInfo> m_switchContextStack;
1265         Vector<Ref<ForInContext>> m_forInContextStack;
1266         Vector<TryContext> m_tryContextStack;
1267         unsigned m_yieldPoints { 0 };
1268
1269         Strong<SymbolTable> m_generatorFrameSymbolTable;
1270         int m_generatorFrameSymbolTableIndex { 0 };
1271
1272         enum FunctionVariableType : uint8_t { NormalFunctionVariable, TopLevelFunctionVariable };
1273         Vector<std::pair<FunctionMetadataNode*, FunctionVariableType>> m_functionsToInitialize;
1274         bool m_needToInitializeArguments { false };
1275         RestParameterNode* m_restParameter { nullptr };
1276         
1277         Vector<TryRange> m_tryRanges;
1278         SegmentedVector<TryData, 8> m_tryData;
1279
1280         Vector<Ref<Label>> m_optionalChainTargetStack;
1281
1282         int m_nextConstantOffset { 0 };
1283
1284         typedef HashMap<FunctionMetadataNode*, unsigned> FunctionOffsetMap;
1285         FunctionOffsetMap m_functionOffsets;
1286         
1287         // Constant pool
1288         IdentifierMap m_identifierMap;
1289
1290         typedef HashMap<EncodedJSValueWithRepresentation, unsigned, EncodedJSValueWithRepresentationHash, EncodedJSValueWithRepresentationHashTraits> JSValueMap;
1291         JSValueMap m_jsValueMap;
1292         IdentifierStringMap m_stringMap;
1293         IdentifierBigIntMap m_bigIntMap;
1294         TemplateObjectDescriptorSet m_templateObjectDescriptorSet;
1295         TemplateDescriptorMap m_templateDescriptorMap;
1296
1297         StaticPropertyAnalyzer m_staticPropertyAnalyzer;
1298
1299         VM& m_vm;
1300
1301         OpcodeID m_lastOpcodeID = op_end;
1302         InstructionStream::MutableRef m_lastInstruction { m_writer.ref() };
1303
1304         bool m_usesExceptions { false };
1305         bool m_expressionTooDeep { false };
1306         bool m_isBuiltinFunction { false };
1307         bool m_usesNonStrictEval { false };
1308         bool m_inTailPosition { false };
1309         bool m_needsToUpdateArrowFunctionContext;
1310         bool m_hasCachedVariablesUnderTDZ { false };
1311         DerivedContextType m_derivedContextType { DerivedContextType::None };
1312
1313         CompactVariableMap::Handle m_cachedVariablesUnderTDZ;
1314
1315         struct CatchEntry {
1316             TryData* tryData;
1317             VirtualRegister exceptionRegister;
1318             VirtualRegister thrownValueRegister;
1319             VirtualRegister completionTypeRegister;
1320         };
1321         Vector<CatchEntry> m_exceptionHandlersToEmit;
1322     };
1323
1324 } // namespace JSC
1325
1326 namespace WTF {
1327
1328 void printInternal(PrintStream&, JSC::Variable::VariableKind);
1329
1330 } // namespace WTF