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