0219d89094af02ce1b2856ea4f43b7e7c7b0156b
[WebKit-https.git] / Source / JavaScriptCore / bytecompiler / BytecodeGenerator.cpp
1 /*
2  * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  * Copyright (C) 2012 Igalia, S.L.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "BytecodeGenerator.h"
33
34 #include "ArithProfile.h"
35 #include "BuiltinExecutables.h"
36 #include "BuiltinNames.h"
37 #include "BytecodeGeneratorification.h"
38 #include "BytecodeLivenessAnalysis.h"
39 #include "DefinePropertyAttributes.h"
40 #include "Interpreter.h"
41 #include "JSAsyncGeneratorFunction.h"
42 #include "JSCInlines.h"
43 #include "JSFunction.h"
44 #include "JSGeneratorFunction.h"
45 #include "JSLexicalEnvironment.h"
46 #include "JSTemplateRegistryKey.h"
47 #include "LowLevelInterpreter.h"
48 #include "Options.h"
49 #include "StackAlignment.h"
50 #include "StrongInlines.h"
51 #include "UnlinkedCodeBlock.h"
52 #include "UnlinkedEvalCodeBlock.h"
53 #include "UnlinkedFunctionCodeBlock.h"
54 #include "UnlinkedInstructionStream.h"
55 #include "UnlinkedModuleProgramCodeBlock.h"
56 #include "UnlinkedProgramCodeBlock.h"
57 #include <wtf/BitVector.h>
58 #include <wtf/CommaPrinter.h>
59 #include <wtf/SmallPtrSet.h>
60 #include <wtf/StdLibExtras.h>
61 #include <wtf/text/WTFString.h>
62
63 using namespace std;
64
65 namespace JSC {
66
67 template<typename T>
68 static inline void shrinkToFit(T& segmentedVector)
69 {
70     while (segmentedVector.size() && !segmentedVector.last().refCount())
71         segmentedVector.removeLast();
72 }
73
74 void Label::setLocation(BytecodeGenerator& generator, unsigned location)
75 {
76     m_location = location;
77     
78     unsigned size = m_unresolvedJumps.size();
79     for (unsigned i = 0; i < size; ++i)
80         generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
81 }
82
83 void Variable::dump(PrintStream& out) const
84 {
85     out.print(
86         "{ident = ", m_ident,
87         ", offset = ", m_offset,
88         ", local = ", RawPointer(m_local),
89         ", attributes = ", m_attributes,
90         ", kind = ", m_kind,
91         ", symbolTableConstantIndex = ", m_symbolTableConstantIndex,
92         ", isLexicallyScoped = ", m_isLexicallyScoped, "}");
93 }
94
95 ParserError BytecodeGenerator::generate()
96 {
97     m_codeBlock->setThisRegister(m_thisRegister.virtualRegister());
98
99     emitLogShadowChickenPrologueIfNecessary();
100     
101     // If we have declared a variable named "arguments" and we are using arguments then we should
102     // perform that assignment now.
103     if (m_needToInitializeArguments)
104         initializeVariable(variable(propertyNames().arguments), m_argumentsRegister);
105
106     if (m_restParameter)
107         m_restParameter->emit(*this);
108
109     {
110         RefPtr<RegisterID> temp = newTemporary();
111         RefPtr<RegisterID> tolLevelScope;
112         for (auto functionPair : m_functionsToInitialize) {
113             FunctionMetadataNode* metadata = functionPair.first;
114             FunctionVariableType functionType = functionPair.second;
115             emitNewFunction(temp.get(), metadata);
116             if (functionType == NormalFunctionVariable)
117                 initializeVariable(variable(metadata->ident()), temp.get());
118             else if (functionType == TopLevelFunctionVariable) {
119                 if (!tolLevelScope) {
120                     // We know this will resolve to the top level scope or global object because our parser/global initialization code 
121                     // doesn't allow let/const/class variables to have the same names as functions.
122                     // This is a top level function, and it's an error to ever create a top level function
123                     // name that would resolve to a lexical variable. E.g:
124                     // ```
125                     //     function f() {
126                     //         {
127                     //             let x;
128                     //             {
129                     //             //// error thrown here
130                     //                  eval("function x(){}");
131                     //             }
132                     //         }
133                     //     }
134                     // ```
135                     // Therefore, we're guaranteed to have this resolve to a top level variable.
136                     RefPtr<RegisterID> tolLevelObjectScope = emitResolveScope(nullptr, Variable(metadata->ident()));
137                     tolLevelScope = newBlockScopeVariable();
138                     emitMove(tolLevelScope.get(), tolLevelObjectScope.get());
139                 }
140                 emitPutToScope(tolLevelScope.get(), Variable(metadata->ident()), temp.get(), ThrowIfNotFound, InitializationMode::NotInitialization);
141             } else
142                 RELEASE_ASSERT_NOT_REACHED();
143         }
144     }
145     
146     bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor();
147     if (!callingClassConstructor)
148         m_scopeNode->emitBytecode(*this);
149     else {
150         // At this point we would have emitted an unconditional throw followed by some nonsense that's
151         // just an artifact of how this generator is structured. That code never runs, but it confuses
152         // bytecode analyses because it constitutes an unterminated basic block. So, we terminate the
153         // basic block the strongest way possible.
154         emitUnreachable();
155     }
156
157     for (auto& tuple : m_catchesToEmit) {
158         Ref<Label> realCatchTarget = newEmittedLabel();
159         emitOpcode(op_catch);
160         instructions().append(std::get<1>(tuple));
161         instructions().append(std::get<2>(tuple));
162         instructions().append(0);
163
164         TryData* tryData = std::get<0>(tuple);
165         emitJump(tryData->target.get());
166         tryData->target = WTFMove(realCatchTarget);
167     }
168
169     m_staticPropertyAnalyzer.kill();
170
171     for (auto& range : m_tryRanges) {
172         int start = range.start->bind();
173         int end = range.end->bind();
174         
175         // This will happen for empty try blocks and for some cases of finally blocks:
176         //
177         // try {
178         //    try {
179         //    } finally {
180         //        return 42;
181         //        // *HERE*
182         //    }
183         // } finally {
184         //    print("things");
185         // }
186         //
187         // The return will pop scopes to execute the outer finally block. But this includes
188         // popping the try context for the inner try. The try context is live in the fall-through
189         // part of the finally block not because we will emit a handler that overlaps the finally,
190         // but because we haven't yet had a chance to plant the catch target. Then when we finish
191         // emitting code for the outer finally block, we repush the try contex, this time with a
192         // new start index. But that means that the start index for the try range corresponding
193         // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
194         // than the end index of the try block. This is harmless since end < start handlers will
195         // never get matched in our logic, but we do the runtime a favor and choose to not emit
196         // such handlers at all.
197         if (end <= start)
198             continue;
199         
200         UnlinkedHandlerInfo info(static_cast<uint32_t>(start), static_cast<uint32_t>(end),
201             static_cast<uint32_t>(range.tryData->target->bind()), range.tryData->handlerType);
202         m_codeBlock->addExceptionHandler(info);
203     }
204     
205
206     if (isGeneratorOrAsyncFunctionBodyParseMode(m_codeBlock->parseMode()))
207         performGeneratorification(m_codeBlock.get(), m_instructions, m_generatorFrameSymbolTable.get(), m_generatorFrameSymbolTableIndex);
208
209     RELEASE_ASSERT(static_cast<unsigned>(m_codeBlock->numCalleeLocals()) < static_cast<unsigned>(FirstConstantRegisterIndex));
210     m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions));
211
212     m_codeBlock->shrinkToFit();
213
214     if (m_expressionTooDeep)
215         return ParserError(ParserError::OutOfMemory);
216     return ParserError(ParserError::ErrorNone);
217 }
218
219 BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
220     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
221     , m_scopeNode(programNode)
222     , m_codeBlock(vm, codeBlock)
223     , m_thisRegister(CallFrame::thisArgumentOffset())
224     , m_codeType(GlobalCode)
225     , m_vm(&vm)
226     , m_needsToUpdateArrowFunctionContext(programNode->usesArrowFunction() || programNode->usesEval())
227 {
228     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
229
230     for (auto& constantRegister : m_linkTimeConstantRegisters)
231         constantRegister = nullptr;
232
233     allocateCalleeSaveSpace();
234
235     m_codeBlock->setNumParameters(1); // Allocate space for "this"
236
237     emitEnter();
238
239     allocateAndEmitScope();
240
241     emitCheckTraps();
242
243     const FunctionStack& functionStack = programNode->functionStack();
244
245     for (auto* function : functionStack)
246         m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
247
248     if (Options::validateBytecode()) {
249         for (auto& entry : programNode->varDeclarations())
250             RELEASE_ASSERT(entry.value.isVar());
251     }
252     codeBlock->setVariableDeclarations(programNode->varDeclarations());
253     codeBlock->setLexicalDeclarations(programNode->lexicalVariables());
254     // Even though this program may have lexical variables that go under TDZ, when linking the get_from_scope/put_to_scope
255     // operations we emit we will have ResolveTypes that implictly do TDZ checks. Therefore, we don't need
256     // additional TDZ checks on top of those. This is why we can omit pushing programNode->lexicalVariables()
257     // to the TDZ stack.
258     
259     if (needsToUpdateArrowFunctionContext()) {
260         initializeArrowFunctionContextScopeIfNeeded();
261         emitPutThisToArrowFunctionContextScope();
262     }
263 }
264
265 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
266     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
267     , m_scopeNode(functionNode)
268     , m_codeBlock(vm, codeBlock)
269     , m_codeType(FunctionCode)
270     , m_vm(&vm)
271     , m_isBuiltinFunction(codeBlock->isBuiltinFunction())
272     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
273     // FIXME: We should be able to have tail call elimination with the profiler
274     // enabled. This is currently not possible because the profiler expects
275     // op_will_call / op_did_call pairs before and after a call, which are not
276     // compatible with tail calls (we have no way of emitting op_did_call).
277     // https://bugs.webkit.org/show_bug.cgi?id=148819
278     , m_inTailPosition(Options::useTailCalls() && !isConstructor() && constructorKind() == ConstructorKind::None && isStrictMode())
279     , m_needsToUpdateArrowFunctionContext(functionNode->usesArrowFunction() || functionNode->usesEval())
280     , m_derivedContextType(codeBlock->derivedContextType())
281 {
282     for (auto& constantRegister : m_linkTimeConstantRegisters)
283         constantRegister = nullptr;
284
285     if (m_isBuiltinFunction)
286         m_shouldEmitDebugHooks = false;
287
288     allocateCalleeSaveSpace();
289     
290     SymbolTable* functionSymbolTable = SymbolTable::create(*m_vm);
291     functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
292     int symbolTableConstantIndex = 0;
293
294     FunctionParameters& parameters = *functionNode->parameters(); 
295     // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
296     // This implements IsSimpleParameterList in the Ecma 2015 spec.
297     // If IsSimpleParameterList is false, we will create a strict-mode like arguments object.
298     // IsSimpleParameterList is false if the argument list contains any default parameter values,
299     // a rest parameter, or any destructuring patterns.
300     // If we do have default parameters, destructuring parameters, or a rest parameter, our parameters will be allocated in a different scope.
301     bool isSimpleParameterList = parameters.isSimpleParameterList();
302
303     SourceParseMode parseMode = codeBlock->parseMode();
304
305     bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || functionNode->usesEval()) && !m_codeBlock->isArrowFunction();
306     bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
307
308     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
309     bool needsArguments = ((functionNode->usesArguments() && !codeBlock->isArrowFunction()) || codeBlock->usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && isArgumentsUsedInInnerArrowFunction()));
310
311     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
312         // Generator and AsyncFunction never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
313         needsArguments = false;
314
315         // Generator and AsyncFunction uses the var scope to save and resume its variables. So the lexical scope is always instantiated.
316         shouldCaptureSomeOfTheThings = true;
317     }
318
319     if (isGeneratorOrAsyncFunctionWrapperParseMode(parseMode) && needsArguments) {
320         // Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
321         // This is because arguments of a generator should be evaluated before starting it.
322         // To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
323         //
324         //    function *gen(a, b = hello())
325         //    {
326         //        return {
327         //            @generatorNext: function (@generator, @generatorState, @generatorValue, @generatorResumeMode, @generatorFrame)
328         //            {
329         //                arguments;  // This `arguments` should reference to the gen's arguments.
330         //                ...
331         //            }
332         //        }
333         //    }
334         shouldCaptureSomeOfTheThings = true;
335     }
336
337     if (shouldCaptureAllOfTheThings)
338         functionNode->varDeclarations().markAllVariablesAsCaptured();
339     
340     auto captures = [&] (UniquedStringImpl* uid) -> bool {
341         if (!shouldCaptureSomeOfTheThings)
342             return false;
343         if (needsArguments && uid == propertyNames().arguments.impl()) {
344             // Actually, we only need to capture the arguments object when we "need full activation"
345             // because of name scopes. But historically we did it this way, so for now we just preserve
346             // the old behavior.
347             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
348             return true;
349         }
350         return functionNode->captures(uid);
351     };
352     auto varKind = [&] (UniquedStringImpl* uid) -> VarKind {
353         return captures(uid) ? VarKind::Scope : VarKind::Stack;
354     };
355
356     m_calleeRegister.setIndex(CallFrameSlot::callee);
357
358     initializeParameters(parameters);
359     ASSERT(!(isSimpleParameterList && m_restParameter));
360
361     emitEnter();
362
363     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode))
364         m_generatorRegister = &m_parameters[1];
365
366     allocateAndEmitScope();
367
368     emitCheckTraps();
369     
370     if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
371         ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
372         ASSERT(!isAsyncFunctionBodyParseMode(parseMode));
373         bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
374         bool isFunctionNameCaptured = captures(functionNode->ident().impl());
375         bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
376         emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister, markAsCaptured);
377     }
378
379     if (shouldCaptureSomeOfTheThings)
380         m_lexicalEnvironmentRegister = addVar();
381
382     if (shouldCaptureSomeOfTheThings || vm.typeProfiler())
383         symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index();
384
385     // We can allocate the "var" environment if we don't have default parameter expressions. If we have
386     // default parameter expressions, we have to hold off on allocating the "var" environment because
387     // the parent scope of the "var" environment is the parameter environment.
388     if (isSimpleParameterList)
389         initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, shouldCaptureSomeOfTheThings);
390
391     // Figure out some interesting facts about our arguments.
392     bool capturesAnyArgumentByName = false;
393     if (functionNode->hasCapturedVariables()) {
394         FunctionParameters& parameters = *functionNode->parameters();
395         for (size_t i = 0; i < parameters.size(); ++i) {
396             auto pattern = parameters.at(i).first;
397             if (!pattern->isBindingNode())
398                 continue;
399             const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
400             capturesAnyArgumentByName |= captures(ident.impl());
401         }
402     }
403     
404     if (capturesAnyArgumentByName)
405         ASSERT(m_lexicalEnvironmentRegister);
406
407     // Need to know what our functions are called. Parameters have some goofy behaviors when it
408     // comes to functions of the same name.
409     for (FunctionMetadataNode* function : functionNode->functionStack())
410         m_functions.add(function->ident().impl());
411     
412     if (needsArguments) {
413         // Create the arguments object now. We may put the arguments object into the activation if
414         // it is captured. Either way, we create two arguments object variables: one is our
415         // private variable that is immutable, and another that is the user-visible variable. The
416         // immutable one is only used here, or during formal parameter resolutions if we opt for
417         // DirectArguments.
418         
419         m_argumentsRegister = addVar();
420         m_argumentsRegister->ref();
421     }
422     
423     if (needsArguments && !codeBlock->isStrictMode() && isSimpleParameterList) {
424         // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
425         // use DirectArguments. With ScopedArguments, we lift all of our arguments into the
426         // activation.
427         
428         if (capturesAnyArgumentByName) {
429             functionSymbolTable->setArgumentsLength(vm, parameters.size());
430             
431             // For each parameter, we have two possibilities:
432             // Either it's a binding node with no function overlap, in which case it gets a name
433             // in the symbol table - or it just gets space reserved in the symbol table. Either
434             // way we lift the value into the scope.
435             for (unsigned i = 0; i < parameters.size(); ++i) {
436                 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
437                 functionSymbolTable->setArgumentOffset(vm, i, offset);
438                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) {
439                     VarOffset varOffset(offset);
440                     SymbolTableEntry entry(varOffset);
441                     // Stores to these variables via the ScopedArguments object will not do
442                     // notifyWrite(), since that would be cumbersome. Also, watching formal
443                     // parameters when "arguments" is in play is unlikely to be super profitable.
444                     // So, we just disable it.
445                     entry.disableWatching(*m_vm);
446                     functionSymbolTable->set(NoLockingNecessary, name, entry);
447                 }
448                 emitOpcode(op_put_to_scope);
449                 instructions().append(m_lexicalEnvironmentRegister->index());
450                 instructions().append(UINT_MAX);
451                 instructions().append(virtualRegisterForArgument(1 + i).offset());
452                 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
453                 instructions().append(symbolTableConstantIndex);
454                 instructions().append(offset.offset());
455             }
456             
457             // This creates a scoped arguments object and copies the overflow arguments into the
458             // scope. It's the equivalent of calling ScopedArguments::createByCopying().
459             emitOpcode(op_create_scoped_arguments);
460             instructions().append(m_argumentsRegister->index());
461             instructions().append(m_lexicalEnvironmentRegister->index());
462         } else {
463             // We're going to put all parameters into the DirectArguments object. First ensure
464             // that the symbol table knows that this is happening.
465             for (unsigned i = 0; i < parameters.size(); ++i) {
466                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first))
467                     functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
468             }
469             
470             emitOpcode(op_create_direct_arguments);
471             instructions().append(m_argumentsRegister->index());
472         }
473     } else if (isSimpleParameterList) {
474         // Create the formal parameters the normal way. Any of them could be captured, or not. If
475         // captured, lift them into the scope. We cannot do this if we have default parameter expressions
476         // because when default parameter expressions exist, they belong in their own lexical environment
477         // separate from the "var" lexical environment.
478         for (unsigned i = 0; i < parameters.size(); ++i) {
479             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
480             if (!name)
481                 continue;
482             
483             if (!captures(name)) {
484                 // This is the easy case - just tell the symbol table about the argument. It will
485                 // be accessed directly.
486                 functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i))));
487                 continue;
488             }
489             
490             ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
491             const Identifier& ident =
492                 static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty();
493             functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(offset)));
494             
495             emitOpcode(op_put_to_scope);
496             instructions().append(m_lexicalEnvironmentRegister->index());
497             instructions().append(addConstant(ident));
498             instructions().append(virtualRegisterForArgument(1 + i).offset());
499             instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
500             instructions().append(symbolTableConstantIndex);
501             instructions().append(offset.offset());
502         }
503     }
504     
505     if (needsArguments && (codeBlock->isStrictMode() || !isSimpleParameterList)) {
506         // Allocate a cloned arguments object.
507         emitOpcode(op_create_cloned_arguments);
508         instructions().append(m_argumentsRegister->index());
509     }
510     
511     // There are some variables that need to be preinitialized to something other than Undefined:
512     //
513     // - "arguments": unless it's used as a function or parameter, this should refer to the
514     //   arguments object.
515     //
516     // - functions: these always override everything else.
517     //
518     // The most logical way to do all of this is to initialize none of the variables until now,
519     // and then initialize them in BytecodeGenerator::generate() in such an order that the rules
520     // for how these things override each other end up holding. We would initialize "arguments" first, 
521     // then all arguments, then the functions.
522     //
523     // But some arguments are already initialized by default, since if they aren't captured and we
524     // don't have "arguments" then we just point the symbol table at the stack slot of those
525     // arguments. We end up initializing the rest of the arguments that have an uncomplicated
526     // binding (i.e. don't involve destructuring) above when figuring out how to lay them out,
527     // because that's just the simplest thing. This means that when we initialize them, we have to
528     // watch out for the things that override arguments (namely, functions).
529     
530     // This is our final act of weirdness. "arguments" is overridden by everything except the
531     // callee. We add it to the symbol table if it's not already there and it's not an argument.
532     bool shouldCreateArgumentsVariableInParameterScope = false;
533     if (needsArguments) {
534         // If "arguments" is overridden by a function or destructuring parameter name, then it's
535         // OK for us to call createVariable() because it won't change anything. It's also OK for
536         // us to them tell BytecodeGenerator::generate() to write to it because it will do so
537         // before it initializes functions and destructuring parameters. But if "arguments" is
538         // overridden by a "simple" function parameter, then we have to bail: createVariable()
539         // would assert and BytecodeGenerator::generate() would write the "arguments" after the
540         // argument value had already been properly initialized.
541         
542         bool haveParameterNamedArguments = false;
543         for (unsigned i = 0; i < parameters.size(); ++i) {
544             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
545             if (name == propertyNames().arguments.impl()) {
546                 haveParameterNamedArguments = true;
547                 break;
548             }
549         }
550
551         bool shouldCreateArgumensVariable = !haveParameterNamedArguments
552             && !SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(m_codeBlock->parseMode());
553         shouldCreateArgumentsVariableInParameterScope = shouldCreateArgumensVariable && !isSimpleParameterList;
554         // Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
555         if (shouldCreateArgumensVariable && !shouldCreateArgumentsVariableInParameterScope) {
556             createVariable(
557                 propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
558
559             m_needToInitializeArguments = true;
560         }
561     }
562
563     for (FunctionMetadataNode* function : functionNode->functionStack()) {
564         const Identifier& ident = function->ident();
565         createVariable(ident, varKind(ident.impl()), functionSymbolTable);
566         m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
567     }
568     for (auto& entry : functionNode->varDeclarations()) {
569         ASSERT(!entry.value.isLet() && !entry.value.isConst());
570         if (!entry.value.isVar()) // This is either a parameter or callee.
571             continue;
572         if (shouldCreateArgumentsVariableInParameterScope && entry.key.get() == propertyNames().arguments.impl())
573             continue;
574         createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting);
575     }
576
577
578     m_newTargetRegister = addVar();
579     switch (parseMode) {
580     case SourceParseMode::GeneratorWrapperFunctionMode:
581     case SourceParseMode::GeneratorWrapperMethodMode:
582     case SourceParseMode::AsyncGeneratorWrapperMethodMode:
583     case SourceParseMode::AsyncGeneratorWrapperFunctionMode: {
584         m_generatorRegister = addVar();
585
586         // FIXME: Emit to_this only when Generator uses it.
587         // https://bugs.webkit.org/show_bug.cgi?id=151586
588         m_codeBlock->addPropertyAccessInstruction(instructions().size());
589         emitOpcode(op_to_this);
590         instructions().append(kill(&m_thisRegister));
591         instructions().append(0);
592         instructions().append(0);
593
594         emitMove(m_generatorRegister, &m_calleeRegister);
595         emitCreateThis(m_generatorRegister);
596         break;
597     }
598
599     case SourceParseMode::AsyncArrowFunctionMode:
600     case SourceParseMode::AsyncMethodMode:
601     case SourceParseMode::AsyncFunctionMode: {
602         ASSERT(!isConstructor());
603         ASSERT(constructorKind() == ConstructorKind::None);
604         m_generatorRegister = addVar();
605         m_promiseCapabilityRegister = addVar();
606
607         if (parseMode != SourceParseMode::AsyncArrowFunctionMode) {
608             // FIXME: Emit to_this only when AsyncFunctionBody uses it.
609             // https://bugs.webkit.org/show_bug.cgi?id=151586
610             m_codeBlock->addPropertyAccessInstruction(instructions().size());
611             emitOpcode(op_to_this);
612             instructions().append(kill(&m_thisRegister));
613             instructions().append(0);
614             instructions().append(0);
615         }
616
617         emitNewObject(m_generatorRegister);
618
619         // let promiseCapability be @newPromiseCapability(@Promise)
620         auto varNewPromiseCapability = variable(propertyNames().builtinNames().newPromiseCapabilityPrivateName());
621         RefPtr<RegisterID> scope = newTemporary();
622         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varNewPromiseCapability));
623         RefPtr<RegisterID> newPromiseCapability = emitGetFromScope(newTemporary(), scope.get(), varNewPromiseCapability, ThrowIfNotFound);
624
625         CallArguments args(*this, nullptr, 1);
626         emitLoad(args.thisRegister(), jsUndefined());
627
628         auto varPromiseConstructor = variable(propertyNames().builtinNames().PromisePrivateName());
629         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varPromiseConstructor));
630         emitGetFromScope(args.argumentRegister(0), scope.get(), varPromiseConstructor, ThrowIfNotFound);
631
632         // JSTextPosition(int _line, int _offset, int _lineStartOffset)
633         JSTextPosition divot(m_scopeNode->firstLine(), m_scopeNode->startOffset(), m_scopeNode->lineStartOffset());
634         emitCall(promiseCapabilityRegister(), newPromiseCapability.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
635         break;
636     }
637
638     case SourceParseMode::AsyncGeneratorBodyMode:
639     case SourceParseMode::AsyncFunctionBodyMode:
640     case SourceParseMode::AsyncArrowFunctionBodyMode:
641     case SourceParseMode::GeneratorBodyMode: {
642         // |this| is already filled correctly before here.
643         emitLoad(m_newTargetRegister, jsUndefined());
644         break;
645     }
646
647     default: {
648         if (SourceParseMode::ArrowFunctionMode != parseMode) {
649             if (isConstructor()) {
650                 emitMove(m_newTargetRegister, &m_thisRegister);
651                 if (constructorKind() == ConstructorKind::Extends) {
652                     emitMoveEmptyValue(&m_thisRegister);
653                 } else
654                     emitCreateThis(&m_thisRegister);
655             } else if (constructorKind() != ConstructorKind::None)
656                 emitThrowTypeError("Cannot call a class constructor without |new|");
657             else {
658                 bool shouldEmitToThis = false;
659                 if (functionNode->usesThis() || codeBlock->usesEval() || m_scopeNode->doAnyInnerArrowFunctionsUseThis() || m_scopeNode->doAnyInnerArrowFunctionsUseEval())
660                     shouldEmitToThis = true;
661                 else if ((functionNode->usesSuperProperty() || m_scopeNode->doAnyInnerArrowFunctionsUseSuperProperty()) && !codeBlock->isStrictMode()) {
662                     // We must emit to_this when we're not in strict mode because we
663                     // will convert |this| to an object, and that object may be passed
664                     // to a strict function as |this|. This is observable because that
665                     // strict function's to_this will just return the object.
666                     //
667                     // We don't need to emit this for strict-mode code because
668                     // strict-mode code may call another strict function, which will
669                     // to_this if it directly uses this; this is OK, because we defer
670                     // to_this until |this| is used directly. Strict-mode code might
671                     // also call a sloppy mode function, and that will to_this, which
672                     // will defer the conversion, again, until necessary.
673                     shouldEmitToThis = true;
674                 }
675
676                 if (shouldEmitToThis) {
677                     m_codeBlock->addPropertyAccessInstruction(instructions().size());
678                     emitOpcode(op_to_this);
679                     instructions().append(kill(&m_thisRegister));
680                     instructions().append(0);
681                     instructions().append(0);
682                 }
683             }
684         }
685         break;
686     }
687     }
688
689     // We need load |super| & |this| for arrow function before initializeDefaultParameterValuesAndSetupFunctionScopeStack
690     // if we have default parameter expression. Because |super| & |this| values can be used there
691     if ((SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && !isSimpleParameterList) || parseMode == SourceParseMode::AsyncArrowFunctionBodyMode) {
692         if (functionNode->usesThis() || functionNode->usesSuperProperty())
693             emitLoadThisFromArrowFunctionLexicalEnvironment();
694
695         if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
696             emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
697     }
698
699     if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction()) {
700         bool canReuseLexicalEnvironment = isSimpleParameterList;
701         initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable, canReuseLexicalEnvironment);
702         emitPutThisToArrowFunctionContextScope();
703         emitPutNewTargetToArrowFunctionContextScope();
704         emitPutDerivedConstructorToArrowFunctionContextScope();
705     }
706
707     // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
708     // because a function's default parameter ExpressionNodes will use temporary registers.
709     pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
710
711     Ref<Label> catchLabel = newLabel();
712     TryData* tryFormalParametersData = nullptr;
713     bool needTryCatch = isAsyncFunctionWrapperParseMode(parseMode) && !isSimpleParameterList;
714     if (needTryCatch) {
715         Ref<Label> tryFormalParametersStart = newEmittedLabel();
716         tryFormalParametersData = pushTry(tryFormalParametersStart.get(), catchLabel.get(), HandlerType::SynthesizedCatch);
717     }
718
719     initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures, shouldCreateArgumentsVariableInParameterScope);
720
721     if (needTryCatch) {
722         Ref<Label> didNotThrow = newLabel();
723         emitJump(didNotThrow.get());
724         emitLabel(catchLabel.get());
725         popTry(tryFormalParametersData, catchLabel.get());
726
727         RefPtr<RegisterID> thrownValue = newTemporary();
728         RegisterID* unused = newTemporary();
729         emitCatch(unused, thrownValue.get(), tryFormalParametersData);
730
731         // return promiseCapability.@reject(thrownValue)
732         RefPtr<RegisterID> reject = emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().rejectPrivateName());
733
734         CallArguments args(*this, nullptr, 1);
735         emitLoad(args.thisRegister(), jsUndefined());
736         emitMove(args.argumentRegister(0), thrownValue.get());
737
738         JSTextPosition divot(functionNode->firstLine(), functionNode->startOffset(), functionNode->lineStartOffset());
739
740         RefPtr<RegisterID> result = emitCall(newTemporary(), reject.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
741         emitReturn(emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().promisePrivateName()));
742
743         emitLabel(didNotThrow.get());
744     }
745
746     // If we don't have  default parameter expression, then loading |this| inside an arrow function must be done
747     // after initializeDefaultParameterValuesAndSetupFunctionScopeStack() because that function sets up the
748     // SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment() consults the SymbolTable stack
749     if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && isSimpleParameterList) {
750         if (functionNode->usesThis() || functionNode->usesSuperProperty())
751             emitLoadThisFromArrowFunctionLexicalEnvironment();
752     
753         if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
754             emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
755     }
756     
757     // Set up the lexical environment scope as the generator frame. We store the saved and resumed generator registers into this scope with the symbol keys.
758     // Since they are symbol keyed, these variables cannot be reached from the usual code.
759     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
760         ASSERT(m_lexicalEnvironmentRegister);
761         m_generatorFrameSymbolTable.set(*m_vm, functionSymbolTable);
762         m_generatorFrameSymbolTableIndex = symbolTableConstantIndex;
763         emitMove(generatorFrameRegister(), m_lexicalEnvironmentRegister);
764         emitPutById(generatorRegister(), propertyNames().builtinNames().generatorFramePrivateName(), generatorFrameRegister());
765     }
766
767     bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
768     pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
769 }
770
771 BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
772     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
773     , m_scopeNode(evalNode)
774     , m_codeBlock(vm, codeBlock)
775     , m_thisRegister(CallFrame::thisArgumentOffset())
776     , m_codeType(EvalCode)
777     , m_vm(&vm)
778     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
779     , m_needsToUpdateArrowFunctionContext(evalNode->usesArrowFunction() || evalNode->usesEval())
780     , m_derivedContextType(codeBlock->derivedContextType())
781 {
782     for (auto& constantRegister : m_linkTimeConstantRegisters)
783         constantRegister = nullptr;
784
785     allocateCalleeSaveSpace();
786
787     m_codeBlock->setNumParameters(1);
788
789     pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
790
791     emitEnter();
792
793     allocateAndEmitScope();
794
795     emitCheckTraps();
796     
797     for (FunctionMetadataNode* function : evalNode->functionStack()) {
798         m_codeBlock->addFunctionDecl(makeFunction(function));
799         m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
800     }
801
802     const VariableEnvironment& varDeclarations = evalNode->varDeclarations();
803     Vector<Identifier, 0, UnsafeVectorOverflow> variables;
804     Vector<Identifier, 0, UnsafeVectorOverflow> hoistedFunctions;
805     for (auto& entry : varDeclarations) {
806         ASSERT(entry.value.isVar());
807         ASSERT(entry.key->isAtomic() || entry.key->isSymbol());
808         if (entry.value.isSloppyModeHoistingCandidate())
809             hoistedFunctions.append(Identifier::fromUid(m_vm, entry.key.get()));
810         else
811             variables.append(Identifier::fromUid(m_vm, entry.key.get()));
812     }
813     codeBlock->adoptVariables(variables);
814     codeBlock->adoptFunctionHoistingCandidates(WTFMove(hoistedFunctions));
815     
816     if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
817         m_newTargetRegister = addVar();
818
819     if (codeBlock->isArrowFunctionContext() && (evalNode->usesThis() || evalNode->usesSuperProperty()))
820         emitLoadThisFromArrowFunctionLexicalEnvironment();
821
822     if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
823         emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
824
825     if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunctionContext() && !isDerivedConstructorContext()) {
826         initializeArrowFunctionContextScopeIfNeeded();
827         emitPutThisToArrowFunctionContextScope();
828     }
829     
830     bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
831     pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
832 }
833
834 BytecodeGenerator::BytecodeGenerator(VM& vm, ModuleProgramNode* moduleProgramNode, UnlinkedModuleProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
835     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
836     , m_scopeNode(moduleProgramNode)
837     , m_codeBlock(vm, codeBlock)
838     , m_thisRegister(CallFrame::thisArgumentOffset())
839     , m_codeType(ModuleCode)
840     , m_vm(&vm)
841     , m_usesNonStrictEval(false)
842     , m_needsToUpdateArrowFunctionContext(moduleProgramNode->usesArrowFunction() || moduleProgramNode->usesEval())
843 {
844     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
845
846     for (auto& constantRegister : m_linkTimeConstantRegisters)
847         constantRegister = nullptr;
848
849     if (m_isBuiltinFunction)
850         m_shouldEmitDebugHooks = false;
851
852     allocateCalleeSaveSpace();
853
854     SymbolTable* moduleEnvironmentSymbolTable = SymbolTable::create(*m_vm);
855     moduleEnvironmentSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
856     moduleEnvironmentSymbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
857
858     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
859     if (shouldCaptureAllOfTheThings)
860         moduleProgramNode->varDeclarations().markAllVariablesAsCaptured();
861
862     auto captures = [&] (UniquedStringImpl* uid) -> bool {
863         return moduleProgramNode->captures(uid);
864     };
865     auto lookUpVarKind = [&] (UniquedStringImpl* uid, const VariableEnvironmentEntry& entry) -> VarKind {
866         // Allocate the exported variables in the module environment.
867         if (entry.isExported())
868             return VarKind::Scope;
869
870         // Allocate the namespace variables in the module environment to instantiate
871         // it from the outside of the module code.
872         if (entry.isImportedNamespace())
873             return VarKind::Scope;
874
875         if (entry.isCaptured())
876             return VarKind::Scope;
877         return captures(uid) ? VarKind::Scope : VarKind::Stack;
878     };
879
880     emitEnter();
881
882     allocateAndEmitScope();
883
884     emitCheckTraps();
885     
886     m_calleeRegister.setIndex(CallFrameSlot::callee);
887
888     m_codeBlock->setNumParameters(1); // Allocate space for "this"
889
890     // Now declare all variables.
891
892     createVariable(m_vm->propertyNames->builtinNames().metaPrivateName(), VarKind::Scope, moduleEnvironmentSymbolTable, VerifyExisting);
893
894     for (auto& entry : moduleProgramNode->varDeclarations()) {
895         ASSERT(!entry.value.isLet() && !entry.value.isConst());
896         if (!entry.value.isVar()) // This is either a parameter or callee.
897             continue;
898         // Imported bindings are not allocated in the module environment as usual variables' way.
899         // These references remain the "Dynamic" in the unlinked code block. Later, when linking
900         // the code block, we resolve the reference to the "ModuleVar".
901         if (entry.value.isImported() && !entry.value.isImportedNamespace())
902             continue;
903         createVariable(Identifier::fromUid(m_vm, entry.key.get()), lookUpVarKind(entry.key.get(), entry.value), moduleEnvironmentSymbolTable, IgnoreExisting);
904     }
905
906     VariableEnvironment& lexicalVariables = moduleProgramNode->lexicalVariables();
907     instantiateLexicalVariables(lexicalVariables, moduleEnvironmentSymbolTable, ScopeRegisterType::Block, lookUpVarKind);
908
909     // We keep the symbol table in the constant pool.
910     RegisterID* constantSymbolTable = nullptr;
911     if (vm.typeProfiler())
912         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable);
913     else
914         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable->cloneScopePart(*m_vm));
915
916     pushTDZVariables(lexicalVariables, TDZCheckOptimization::Optimize, TDZRequirement::UnderTDZ);
917     bool isWithScope = false;
918     m_lexicalScopeStack.append({ moduleEnvironmentSymbolTable, m_topMostScope, isWithScope, constantSymbolTable->index() });
919     emitPrefillStackTDZVariables(lexicalVariables, moduleEnvironmentSymbolTable);
920
921     // makeFunction assumes that there's correct TDZ stack entries.
922     // So it should be called after putting our lexical environment to the TDZ stack correctly.
923
924     for (FunctionMetadataNode* function : moduleProgramNode->functionStack()) {
925         const auto& iterator = moduleProgramNode->varDeclarations().find(function->ident().impl());
926         RELEASE_ASSERT(iterator != moduleProgramNode->varDeclarations().end());
927         RELEASE_ASSERT(!iterator->value.isImported());
928
929         VarKind varKind = lookUpVarKind(iterator->key.get(), iterator->value);
930         if (varKind == VarKind::Scope) {
931             // http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
932             // Section 15.2.1.16.4, step 16-a-iv-1.
933             // All heap allocated function declarations should be instantiated when the module environment
934             // is created. They include the exported function declarations and not-exported-but-heap-allocated
935             // function declarations. This is required because exported function should be instantiated before
936             // executing the any module in the dependency graph. This enables the modules to link the imported
937             // bindings before executing the any module code.
938             //
939             // And since function declarations are instantiated before executing the module body code, the spec
940             // allows the functions inside the module to be executed before its module body is executed under
941             // the circular dependencies. The following is the example.
942             //
943             // Module A (executed first):
944             //    import { b } from "B";
945             //    // Here, the module "B" is not executed yet, but the function declaration is already instantiated.
946             //    // So we can call the function exported from "B".
947             //    b();
948             //
949             //    export function a() {
950             //    }
951             //
952             // Module B (executed second):
953             //    import { a } from "A";
954             //
955             //    export function b() {
956             //        c();
957             //    }
958             //
959             //    // c is not exported, but since it is referenced from the b, we should instantiate it before
960             //    // executing the "B" module code.
961             //    function c() {
962             //        a();
963             //    }
964             //
965             // Module EntryPoint (executed last):
966             //    import "B";
967             //    import "A";
968             //
969             m_codeBlock->addFunctionDecl(makeFunction(function));
970         } else {
971             // Stack allocated functions can be allocated when executing the module's body.
972             m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
973         }
974     }
975
976     // Remember the constant register offset to the top-most symbol table. This symbol table will be
977     // cloned in the code block linking. After that, to create the module environment, we retrieve
978     // the cloned symbol table from the linked code block by using this offset.
979     codeBlock->setModuleEnvironmentSymbolTableConstantRegisterOffset(constantSymbolTable->index());
980 }
981
982 BytecodeGenerator::~BytecodeGenerator()
983 {
984 }
985
986 void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack(
987     FunctionParameters& parameters, bool isSimpleParameterList, FunctionNode* functionNode, SymbolTable* functionSymbolTable, 
988     int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope)
989 {
990     Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars;
991     ASSERT(!(isSimpleParameterList && shouldCreateArgumentsVariableInParameterScope));
992     if (!isSimpleParameterList) {
993         // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
994         // This implements step 21.
995         VariableEnvironment environment;
996         Vector<Identifier> allParameterNames; 
997         for (unsigned i = 0; i < parameters.size(); i++)
998             parameters.at(i).first->collectBoundIdentifiers(allParameterNames);
999         if (shouldCreateArgumentsVariableInParameterScope)
1000             allParameterNames.append(propertyNames().arguments);
1001         IdentifierSet parameterSet;
1002         for (auto& ident : allParameterNames) {
1003             parameterSet.add(ident.impl());
1004             auto addResult = environment.add(ident);
1005             addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables.
1006             if (captures(ident.impl()))
1007                 addResult.iterator->value.setIsCaptured();
1008         }
1009         // This implements step 25 of section 9.2.12.
1010         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1011
1012         if (shouldCreateArgumentsVariableInParameterScope) {
1013             Variable argumentsVariable = variable(propertyNames().arguments); 
1014             initializeVariable(argumentsVariable, m_argumentsRegister);
1015             liftTDZCheckIfPossible(argumentsVariable);
1016         }
1017
1018         RefPtr<RegisterID> temp = newTemporary();
1019         for (unsigned i = 0; i < parameters.size(); i++) {
1020             std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
1021             if (parameter.first->isRestParameter())
1022                 continue;
1023             if ((i + 1) < m_parameters.size())
1024                 emitMove(temp.get(), &m_parameters[i + 1]);
1025             else
1026                 emitGetArgument(temp.get(), i);
1027             if (parameter.second) {
1028                 RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), temp.get());
1029                 Ref<Label> skipDefaultParameterBecauseNotUndefined = newLabel();
1030                 emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get());
1031                 emitNode(temp.get(), parameter.second);
1032                 emitLabel(skipDefaultParameterBecauseNotUndefined.get());
1033             }
1034
1035             parameter.first->bindValue(*this, temp.get());
1036         }
1037
1038         // Final act of weirdness for default parameters. If a "var" also
1039         // has the same name as a parameter, it should start out as the
1040         // value of that parameter. Note, though, that they will be distinct
1041         // bindings.
1042         // This is step 28 of section 9.2.12. 
1043         for (auto& entry : functionNode->varDeclarations()) {
1044             if (!entry.value.isVar()) // This is either a parameter or callee.
1045                 continue;
1046
1047             if (parameterSet.contains(entry.key)) {
1048                 Identifier ident = Identifier::fromUid(m_vm, entry.key.get());
1049                 Variable var = variable(ident);
1050                 RegisterID* scope = emitResolveScope(nullptr, var);
1051                 RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound);
1052                 valuesToMoveIntoVars.append(std::make_pair(ident, value));
1053             }
1054         }
1055
1056         // Functions with default parameter expressions must have a separate environment
1057         // record for parameters and "var"s. The "var" environment record must have the
1058         // parameter environment record as its parent.
1059         // See step 28 of section 9.2.12.
1060         bool hasCapturedVariables = !!m_lexicalEnvironmentRegister; 
1061         initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, hasCapturedVariables);
1062     }
1063
1064     // This completes step 28 of section 9.2.12.
1065     for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) {
1066         ASSERT(!isSimpleParameterList);
1067         Variable var = variable(valuesToMoveIntoVars[i].first);
1068         RegisterID* scope = emitResolveScope(nullptr, var);
1069         emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
1070     }
1071 }
1072
1073 bool BytecodeGenerator::needsDerivedConstructorInArrowFunctionLexicalEnvironment()
1074 {
1075     ASSERT(m_codeBlock->isClassContext() || !(isConstructor() && constructorKind() == ConstructorKind::Extends));
1076     return m_codeBlock->isClassContext() && isSuperUsedInInnerArrowFunction();
1077 }
1078
1079 void BytecodeGenerator::initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable, bool canReuseLexicalEnvironment)
1080 {
1081     ASSERT(!m_arrowFunctionContextLexicalEnvironmentRegister);
1082
1083     if (canReuseLexicalEnvironment && m_lexicalEnvironmentRegister) {
1084         RELEASE_ASSERT(!m_codeBlock->isArrowFunction());
1085         RELEASE_ASSERT(functionSymbolTable);
1086
1087         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalEnvironmentRegister;
1088         
1089         ScopeOffset offset;
1090         
1091         if (isThisUsedInInnerArrowFunction()) {
1092             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1093             functionSymbolTable->set(NoLockingNecessary, propertyNames().thisIdentifier.impl(), SymbolTableEntry(VarOffset(offset)));
1094         }
1095
1096         if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1097             offset = functionSymbolTable->takeNextScopeOffset();
1098             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().newTargetLocalPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1099         }
1100         
1101         if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1102             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1103             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().derivedConstructorPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1104         }
1105
1106         return;
1107     }
1108
1109     VariableEnvironment environment;
1110
1111     if (isThisUsedInInnerArrowFunction()) {
1112         auto addResult = environment.add(propertyNames().thisIdentifier);
1113         addResult.iterator->value.setIsCaptured();
1114         addResult.iterator->value.setIsLet();
1115     }
1116     
1117     if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1118         auto addTarget = environment.add(propertyNames().builtinNames().newTargetLocalPrivateName());
1119         addTarget.iterator->value.setIsCaptured();
1120         addTarget.iterator->value.setIsLet();
1121     }
1122
1123     if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1124         auto derivedConstructor = environment.add(propertyNames().builtinNames().derivedConstructorPrivateName());
1125         derivedConstructor.iterator->value.setIsCaptured();
1126         derivedConstructor.iterator->value.setIsLet();
1127     }
1128
1129     if (environment.size() > 0) {
1130         size_t size = m_lexicalScopeStack.size();
1131         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1132
1133         ASSERT_UNUSED(size, m_lexicalScopeStack.size() == size + 1);
1134
1135         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalScopeStack.last().m_scope;
1136     }
1137 }
1138
1139 RegisterID* BytecodeGenerator::initializeNextParameter()
1140 {
1141     VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
1142     m_parameters.grow(m_parameters.size() + 1);
1143     auto& parameter = registerFor(reg);
1144     parameter.setIndex(reg.offset());
1145     m_codeBlock->addParameter();
1146     return &parameter;
1147 }
1148
1149 void BytecodeGenerator::initializeParameters(FunctionParameters& parameters)
1150 {
1151     // Make sure the code block knows about all of our parameters, and make sure that parameters
1152     // needing destructuring are noted.
1153     m_thisRegister.setIndex(initializeNextParameter()->index()); // this
1154
1155     bool nonSimpleArguments = false;
1156     for (unsigned i = 0; i < parameters.size(); ++i) {
1157         auto parameter = parameters.at(i);
1158         auto pattern = parameter.first;
1159         if (pattern->isRestParameter()) {
1160             RELEASE_ASSERT(!m_restParameter);
1161             m_restParameter = static_cast<RestParameterNode*>(pattern);
1162             nonSimpleArguments = true;
1163             continue;
1164         }
1165         if (parameter.second) {
1166             nonSimpleArguments = true;
1167             continue;
1168         }
1169         if (!nonSimpleArguments)
1170             initializeNextParameter();
1171     }
1172 }
1173
1174 void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables)
1175 {
1176     if (hasCapturedVariables) {
1177         RELEASE_ASSERT(m_lexicalEnvironmentRegister);
1178         emitOpcode(op_create_lexical_environment);
1179         instructions().append(m_lexicalEnvironmentRegister->index());
1180         instructions().append(scopeRegister()->index());
1181         instructions().append(symbolTableConstantIndex);
1182         instructions().append(addConstantValue(jsUndefined())->index());
1183
1184         emitOpcode(op_mov);
1185         instructions().append(scopeRegister()->index());
1186         instructions().append(m_lexicalEnvironmentRegister->index());
1187
1188         pushLocalControlFlowScope();
1189     }
1190     bool isWithScope = false;
1191     m_lexicalScopeStack.append({ functionSymbolTable, m_lexicalEnvironmentRegister, isWithScope, symbolTableConstantIndex });
1192     m_varScopeLexicalScopeStackIndex = m_lexicalScopeStack.size() - 1;
1193 }
1194
1195 UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern)
1196 {
1197     if (pattern->isBindingNode()) {
1198         const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
1199         if (!m_functions.contains(ident.impl()))
1200             return ident.impl();
1201     }
1202     return nullptr;
1203 }
1204
1205 RegisterID* BytecodeGenerator::newRegister()
1206 {
1207     m_calleeLocals.append(virtualRegisterForLocal(m_calleeLocals.size()));
1208     int numCalleeLocals = max<int>(m_codeBlock->m_numCalleeLocals, m_calleeLocals.size());
1209     numCalleeLocals = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeLocals);
1210     m_codeBlock->m_numCalleeLocals = numCalleeLocals;
1211     return &m_calleeLocals.last();
1212 }
1213
1214 void BytecodeGenerator::reclaimFreeRegisters()
1215 {
1216     shrinkToFit(m_calleeLocals);
1217 }
1218
1219 RegisterID* BytecodeGenerator::newBlockScopeVariable()
1220 {
1221     reclaimFreeRegisters();
1222
1223     return newRegister();
1224 }
1225
1226 RegisterID* BytecodeGenerator::newTemporary()
1227 {
1228     reclaimFreeRegisters();
1229
1230     RegisterID* result = newRegister();
1231     result->setTemporary();
1232     return result;
1233 }
1234
1235 Ref<LabelScope> BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
1236 {
1237     shrinkToFit(m_labelScopes);
1238
1239     // Allocate new label scope.
1240     m_labelScopes.append(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? RefPtr<Label>(newLabel()) : RefPtr<Label>()); // Only loops have continue targets.
1241     return m_labelScopes.last();
1242 }
1243
1244 Ref<Label> BytecodeGenerator::newLabel()
1245 {
1246     shrinkToFit(m_labels);
1247
1248     // Allocate new label ID.
1249     m_labels.append();
1250     return m_labels.last();
1251 }
1252
1253 Ref<Label> BytecodeGenerator::newEmittedLabel()
1254 {
1255     Ref<Label> label = newLabel();
1256     emitLabel(label.get());
1257     return label;
1258 }
1259
1260 void BytecodeGenerator::emitLabel(Label& l0)
1261 {
1262     unsigned newLabelIndex = instructions().size();
1263     l0.setLocation(*this, newLabelIndex);
1264
1265     if (m_codeBlock->numberOfJumpTargets()) {
1266         unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
1267         ASSERT(lastLabelIndex <= newLabelIndex);
1268         if (newLabelIndex == lastLabelIndex) {
1269             // Peephole optimizations have already been disabled by emitting the last label
1270             return;
1271         }
1272     }
1273
1274     m_codeBlock->addJumpTarget(newLabelIndex);
1275
1276     // This disables peephole optimizations when an instruction is a jump target
1277     m_lastOpcodeID = op_end;
1278 }
1279
1280 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
1281 {
1282 #ifndef NDEBUG
1283     size_t opcodePosition = instructions().size();
1284     ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
1285     m_lastOpcodePosition = opcodePosition;
1286 #endif
1287     instructions().append(opcodeID);
1288     m_lastOpcodeID = opcodeID;
1289 }
1290
1291 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
1292 {
1293     return m_codeBlock->addArrayProfile();
1294 }
1295
1296 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
1297 {
1298     return m_codeBlock->addArrayAllocationProfile();
1299 }
1300
1301 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
1302 {
1303     return m_codeBlock->addObjectAllocationProfile();
1304 }
1305
1306 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
1307 {
1308     UnlinkedValueProfile result = m_codeBlock->addValueProfile();
1309     emitOpcode(opcodeID);
1310     return result;
1311 }
1312
1313 void BytecodeGenerator::emitEnter()
1314 {
1315     emitOpcode(op_enter);
1316
1317     // We must add the end of op_enter as a potential jump target, because the bytecode parser may decide to split its basic block
1318     // to have somewhere to jump to if there is a recursive tail-call that points to this function.
1319     m_codeBlock->addJumpTarget(instructions().size());
1320     // This disables peephole optimizations when an instruction is a jump target
1321     m_lastOpcodeID = op_end;
1322 }
1323
1324 void BytecodeGenerator::emitLoopHint()
1325 {
1326     emitOpcode(op_loop_hint);
1327     emitCheckTraps();
1328 }
1329
1330 void BytecodeGenerator::emitCheckTraps()
1331 {
1332     emitOpcode(op_check_traps);
1333 }
1334
1335 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
1336 {
1337     ASSERT(instructions().size() >= 4);
1338     size_t size = instructions().size();
1339     dstIndex = instructions().at(size - 3).u.operand;
1340     src1Index = instructions().at(size - 2).u.operand;
1341     src2Index = instructions().at(size - 1).u.operand;
1342 }
1343
1344 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
1345 {
1346     ASSERT(instructions().size() >= 3);
1347     size_t size = instructions().size();
1348     dstIndex = instructions().at(size - 2).u.operand;
1349     srcIndex = instructions().at(size - 1).u.operand;
1350 }
1351
1352 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
1353 {
1354     ASSERT(instructions().size() >= 4);
1355     instructions().shrink(instructions().size() - 4);
1356     m_lastOpcodeID = op_end;
1357 }
1358
1359 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
1360 {
1361     ASSERT(instructions().size() >= 3);
1362     instructions().shrink(instructions().size() - 3);
1363     m_lastOpcodeID = op_end;
1364 }
1365
1366 void BytecodeGenerator::emitJump(Label& target)
1367 {
1368     size_t begin = instructions().size();
1369     emitOpcode(op_jmp);
1370     instructions().append(target.bind(begin, instructions().size()));
1371 }
1372
1373 void BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label& target)
1374 {
1375     auto fuseCompareAndJump = [&] (OpcodeID jumpID) {
1376         int dstIndex;
1377         int src1Index;
1378         int src2Index;
1379
1380         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1381
1382         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1383             rewindBinaryOp();
1384
1385             size_t begin = instructions().size();
1386             emitOpcode(jumpID);
1387             instructions().append(src1Index);
1388             instructions().append(src2Index);
1389             instructions().append(target.bind(begin, instructions().size()));
1390             return true;
1391         }
1392         return false;
1393     };
1394
1395     if (m_lastOpcodeID == op_less) {
1396         if (fuseCompareAndJump(op_jless))
1397             return;
1398     } else if (m_lastOpcodeID == op_lesseq) {
1399         if (fuseCompareAndJump(op_jlesseq))
1400             return;
1401     } else if (m_lastOpcodeID == op_greater) {
1402         if (fuseCompareAndJump(op_jgreater))
1403             return;
1404     } else if (m_lastOpcodeID == op_greatereq) {
1405         if (fuseCompareAndJump(op_jgreatereq))
1406             return;
1407     } else if (m_lastOpcodeID == op_below) {
1408         if (fuseCompareAndJump(op_jbelow))
1409             return;
1410     } else if (m_lastOpcodeID == op_beloweq) {
1411         if (fuseCompareAndJump(op_jbeloweq))
1412             return;
1413     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1414         int dstIndex;
1415         int srcIndex;
1416
1417         retrieveLastUnaryOp(dstIndex, srcIndex);
1418
1419         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1420             rewindUnaryOp();
1421
1422             size_t begin = instructions().size();
1423             emitOpcode(op_jeq_null);
1424             instructions().append(srcIndex);
1425             instructions().append(target.bind(begin, instructions().size()));
1426             return;
1427         }
1428     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1429         int dstIndex;
1430         int srcIndex;
1431
1432         retrieveLastUnaryOp(dstIndex, srcIndex);
1433
1434         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1435             rewindUnaryOp();
1436
1437             size_t begin = instructions().size();
1438             emitOpcode(op_jneq_null);
1439             instructions().append(srcIndex);
1440             instructions().append(target.bind(begin, instructions().size()));
1441             return;
1442         }
1443     }
1444
1445     size_t begin = instructions().size();
1446
1447     emitOpcode(op_jtrue);
1448     instructions().append(cond->index());
1449     instructions().append(target.bind(begin, instructions().size()));
1450 }
1451
1452 void BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label& target)
1453 {
1454     auto fuseCompareAndJump = [&] (OpcodeID jumpID, bool replaceOperands) {
1455         int dstIndex;
1456         int src1Index;
1457         int src2Index;
1458
1459         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1460
1461         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1462             rewindBinaryOp();
1463
1464             size_t begin = instructions().size();
1465             emitOpcode(jumpID);
1466             // Since op_below and op_beloweq only accepts Int32, replacing operands is not observable to users.
1467             if (replaceOperands)
1468                 std::swap(src1Index, src2Index);
1469             instructions().append(src1Index);
1470             instructions().append(src2Index);
1471             instructions().append(target.bind(begin, instructions().size()));
1472             return true;
1473         }
1474         return false;
1475     };
1476
1477     if (m_lastOpcodeID == op_less && target.isForward()) {
1478         if (fuseCompareAndJump(op_jnless, false))
1479             return;
1480     } else if (m_lastOpcodeID == op_lesseq && target.isForward()) {
1481         if (fuseCompareAndJump(op_jnlesseq, false))
1482             return;
1483     } else if (m_lastOpcodeID == op_greater && target.isForward()) {
1484         if (fuseCompareAndJump(op_jngreater, false))
1485             return;
1486     } else if (m_lastOpcodeID == op_greatereq && target.isForward()) {
1487         if (fuseCompareAndJump(op_jngreatereq, false))
1488             return;
1489     } else if (m_lastOpcodeID == op_below && target.isForward()) {
1490         if (fuseCompareAndJump(op_jbeloweq, true))
1491             return;
1492     } else if (m_lastOpcodeID == op_beloweq && target.isForward()) {
1493         if (fuseCompareAndJump(op_jbelow, true))
1494             return;
1495     } else if (m_lastOpcodeID == op_not) {
1496         int dstIndex;
1497         int srcIndex;
1498
1499         retrieveLastUnaryOp(dstIndex, srcIndex);
1500
1501         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1502             rewindUnaryOp();
1503
1504             size_t begin = instructions().size();
1505             emitOpcode(op_jtrue);
1506             instructions().append(srcIndex);
1507             instructions().append(target.bind(begin, instructions().size()));
1508             return;
1509         }
1510     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1511         int dstIndex;
1512         int srcIndex;
1513
1514         retrieveLastUnaryOp(dstIndex, srcIndex);
1515
1516         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1517             rewindUnaryOp();
1518
1519             size_t begin = instructions().size();
1520             emitOpcode(op_jneq_null);
1521             instructions().append(srcIndex);
1522             instructions().append(target.bind(begin, instructions().size()));
1523             return;
1524         }
1525     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1526         int dstIndex;
1527         int srcIndex;
1528
1529         retrieveLastUnaryOp(dstIndex, srcIndex);
1530
1531         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1532             rewindUnaryOp();
1533
1534             size_t begin = instructions().size();
1535             emitOpcode(op_jeq_null);
1536             instructions().append(srcIndex);
1537             instructions().append(target.bind(begin, instructions().size()));
1538             return;
1539         }
1540     }
1541
1542     size_t begin = instructions().size();
1543     emitOpcode(op_jfalse);
1544     instructions().append(cond->index());
1545     instructions().append(target.bind(begin, instructions().size()));
1546 }
1547
1548 void BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label& target)
1549 {
1550     size_t begin = instructions().size();
1551
1552     emitOpcode(op_jneq_ptr);
1553     instructions().append(cond->index());
1554     instructions().append(Special::CallFunction);
1555     instructions().append(target.bind(begin, instructions().size()));
1556     instructions().append(0);
1557 }
1558
1559 void BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label& target)
1560 {
1561     size_t begin = instructions().size();
1562
1563     emitOpcode(op_jneq_ptr);
1564     instructions().append(cond->index());
1565     instructions().append(Special::ApplyFunction);
1566     instructions().append(target.bind(begin, instructions().size()));
1567     instructions().append(0);
1568 }
1569
1570 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
1571 {
1572     UniquedStringImpl* rep = ident.impl();
1573     return m_identifierMap.contains(rep);
1574 }
1575
1576 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
1577 {
1578     UniquedStringImpl* rep = ident.impl();
1579     IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
1580     if (result.isNewEntry)
1581         m_codeBlock->addIdentifier(ident);
1582
1583     return result.iterator->value;
1584 }
1585
1586 // We can't hash JSValue(), so we use a dedicated data member to cache it.
1587 RegisterID* BytecodeGenerator::addConstantEmptyValue()
1588 {
1589     if (!m_emptyValueRegister) {
1590         int index = addConstantIndex();
1591         m_codeBlock->addConstant(JSValue());
1592         m_emptyValueRegister = &m_constantPoolRegisters[index];
1593     }
1594
1595     return m_emptyValueRegister;
1596 }
1597
1598 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1599 {
1600     if (!v)
1601         return addConstantEmptyValue();
1602
1603     int index = m_nextConstantOffset;
1604
1605     if (sourceCodeRepresentation == SourceCodeRepresentation::Double && v.isInt32())
1606         v = jsDoubleNumber(v.asNumber());
1607     EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
1608     JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
1609     if (result.isNewEntry) {
1610         addConstantIndex();
1611         m_codeBlock->addConstant(v, sourceCodeRepresentation);
1612     } else
1613         index = result.iterator->value;
1614     return &m_constantPoolRegisters[index];
1615 }
1616
1617 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1618 {
1619     unsigned constantIndex = static_cast<unsigned>(type);
1620     if (!m_linkTimeConstantRegisters[constantIndex]) {
1621         int index = addConstantIndex();
1622         m_codeBlock->addConstant(type);
1623         m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1624     }
1625
1626     if (!dst)
1627         return m_linkTimeConstantRegisters[constantIndex];
1628
1629     emitOpcode(op_mov);
1630     instructions().append(dst->index());
1631     instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1632
1633     return dst;
1634 }
1635
1636 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1637 {
1638     return m_codeBlock->addRegExp(r);
1639 }
1640
1641 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1642 {
1643     RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1644
1645     emitOpcode(op_mov);
1646     instructions().append(dst->index());
1647     instructions().append(emptyValue->index());
1648     return dst;
1649 }
1650
1651 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1652 {
1653     ASSERT(src != m_emptyValueRegister);
1654
1655     m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1656     emitOpcode(op_mov);
1657     instructions().append(dst->index());
1658     instructions().append(src->index());
1659
1660     return dst;
1661 }
1662
1663 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1664 {
1665     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1666     ASSERT_WITH_MESSAGE(op_negate != opcodeID, "op_negate has an Arith Profile.");
1667     emitOpcode(opcodeID);
1668     instructions().append(dst->index());
1669     instructions().append(src->index());
1670
1671     return dst;
1672 }
1673
1674 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src, OperandTypes types)
1675 {
1676     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1677     emitOpcode(opcodeID);
1678     instructions().append(dst->index());
1679     instructions().append(src->index());
1680
1681     if (opcodeID == op_negate)
1682         instructions().append(ArithProfile(types.first()).bits());
1683     return dst;
1684 }
1685
1686 RegisterID* BytecodeGenerator::emitUnaryOpProfiled(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1687 {
1688     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
1689     instructions().append(dst->index());
1690     instructions().append(src->index());
1691     instructions().append(profile);
1692     return dst;
1693 }
1694
1695 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1696 {
1697     emitOpcode(op_inc);
1698     instructions().append(srcDst->index());
1699     return srcDst;
1700 }
1701
1702 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1703 {
1704     emitOpcode(op_dec);
1705     instructions().append(srcDst->index());
1706     return srcDst;
1707 }
1708
1709 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1710 {
1711     emitOpcode(opcodeID);
1712     instructions().append(dst->index());
1713     instructions().append(src1->index());
1714     instructions().append(src2->index());
1715
1716     if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1717         opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1718         instructions().append(ArithProfile(types.first(), types.second()).bits());
1719
1720     return dst;
1721 }
1722
1723 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1724 {
1725     if (m_lastOpcodeID == op_typeof) {
1726         int dstIndex;
1727         int srcIndex;
1728
1729         retrieveLastUnaryOp(dstIndex, srcIndex);
1730
1731         if (src1->index() == dstIndex
1732             && src1->isTemporary()
1733             && m_codeBlock->isConstantRegisterIndex(src2->index())
1734             && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1735             const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1736             if (value == "undefined") {
1737                 rewindUnaryOp();
1738                 emitOpcode(op_is_undefined);
1739                 instructions().append(dst->index());
1740                 instructions().append(srcIndex);
1741                 return dst;
1742             }
1743             if (value == "boolean") {
1744                 rewindUnaryOp();
1745                 emitOpcode(op_is_boolean);
1746                 instructions().append(dst->index());
1747                 instructions().append(srcIndex);
1748                 return dst;
1749             }
1750             if (value == "number") {
1751                 rewindUnaryOp();
1752                 emitOpcode(op_is_number);
1753                 instructions().append(dst->index());
1754                 instructions().append(srcIndex);
1755                 return dst;
1756             }
1757             if (value == "string") {
1758                 rewindUnaryOp();
1759                 emitOpcode(op_is_cell_with_type);
1760                 instructions().append(dst->index());
1761                 instructions().append(srcIndex);
1762                 instructions().append(StringType);
1763                 return dst;
1764             }
1765             if (value == "symbol") {
1766                 rewindUnaryOp();
1767                 emitOpcode(op_is_cell_with_type);
1768                 instructions().append(dst->index());
1769                 instructions().append(srcIndex);
1770                 instructions().append(SymbolType);
1771                 return dst;
1772             }
1773             if (value == "object") {
1774                 rewindUnaryOp();
1775                 emitOpcode(op_is_object_or_null);
1776                 instructions().append(dst->index());
1777                 instructions().append(srcIndex);
1778                 return dst;
1779             }
1780             if (value == "function") {
1781                 rewindUnaryOp();
1782                 emitOpcode(op_is_function);
1783                 instructions().append(dst->index());
1784                 instructions().append(srcIndex);
1785                 return dst;
1786             }
1787         }
1788     }
1789
1790     emitOpcode(opcodeID);
1791     instructions().append(dst->index());
1792     instructions().append(src1->index());
1793     instructions().append(src2->index());
1794     return dst;
1795 }
1796
1797 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1798 {
1799     ASSERT(vm()->typeProfiler());
1800
1801     unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1802     unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1803     unsigned instructionOffset = instructions().size() - 1;
1804     m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1805 }
1806
1807 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag)
1808 {
1809     if (!vm()->typeProfiler())
1810         return;
1811
1812     if (!registerToProfile)
1813         return;
1814
1815     emitOpcode(op_profile_type);
1816     instructions().append(registerToProfile->index());
1817     instructions().append(0);
1818     instructions().append(flag);
1819     instructions().append(0);
1820     instructions().append(resolveType());
1821
1822     // Don't emit expression info for this version of profile type. This generally means
1823     // we're profiling information for something that isn't in the actual text of a JavaScript
1824     // program. For example, implicit return undefined from a function call.
1825 }
1826
1827 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1828 {
1829     emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot);
1830 }
1831
1832 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1833 {
1834     if (!vm()->typeProfiler())
1835         return;
1836
1837     if (!registerToProfile)
1838         return;
1839
1840     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1841     emitOpcode(op_profile_type);
1842     instructions().append(registerToProfile->index());
1843     instructions().append(0);
1844     instructions().append(flag);
1845     instructions().append(0);
1846     instructions().append(resolveType());
1847
1848     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1849 }
1850
1851 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1852 {
1853     if (!vm()->typeProfiler())
1854         return;
1855
1856     if (!registerToProfile)
1857         return;
1858
1859     ProfileTypeBytecodeFlag flag;
1860     int symbolTableOrScopeDepth;
1861     if (var.local() || var.offset().isScope()) {
1862         flag = ProfileTypeBytecodeLocallyResolved;
1863         ASSERT(var.symbolTableConstantIndex());
1864         symbolTableOrScopeDepth = var.symbolTableConstantIndex();
1865     } else {
1866         flag = ProfileTypeBytecodeClosureVar;
1867         symbolTableOrScopeDepth = localScopeDepth();
1868     }
1869
1870     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1871     emitOpcode(op_profile_type);
1872     instructions().append(registerToProfile->index());
1873     instructions().append(symbolTableOrScopeDepth);
1874     instructions().append(flag);
1875     instructions().append(addConstant(var.ident()));
1876     instructions().append(resolveType());
1877
1878     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1879 }
1880
1881 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1882 {
1883     if (vm()->controlFlowProfiler()) {
1884         RELEASE_ASSERT(textOffset >= 0);
1885         size_t bytecodeOffset = instructions().size();
1886         m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1887
1888         emitOpcode(op_profile_control_flow);
1889         instructions().append(textOffset);
1890     }
1891 }
1892
1893 unsigned BytecodeGenerator::addConstantIndex()
1894 {
1895     unsigned index = m_nextConstantOffset;
1896     m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1897     ++m_nextConstantOffset;
1898     return index;
1899 }
1900
1901 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1902 {
1903     return emitLoad(dst, jsBoolean(b));
1904 }
1905
1906 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1907 {
1908     ASSERT(!identifier.isSymbol());
1909     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1910     if (!stringInMap)
1911         stringInMap = jsOwnedString(vm(), identifier.string());
1912
1913     return emitLoad(dst, JSValue(stringInMap));
1914 }
1915
1916 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1917 {
1918     RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1919     if (dst)
1920         return emitMove(dst, constantID);
1921     return constantID;
1922 }
1923
1924 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, IdentifierSet& set)
1925 {
1926     for (const auto& entry : m_codeBlock->constantIdentifierSets()) {
1927         if (entry.first != set)
1928             continue;
1929         
1930         return &m_constantPoolRegisters[entry.second];
1931     }
1932     
1933     unsigned index = addConstantIndex();
1934     m_codeBlock->addSetConstant(set);
1935     RegisterID* m_setRegister = &m_constantPoolRegisters[index];
1936     
1937     if (dst)
1938         return emitMove(dst, m_setRegister);
1939     
1940     return m_setRegister;
1941 }
1942
1943 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1944 {
1945     if (!m_globalObjectRegister) {
1946         int index = addConstantIndex();
1947         m_codeBlock->addConstant(JSValue());
1948         m_globalObjectRegister = &m_constantPoolRegisters[index];
1949         m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1950     }
1951     if (dst)
1952         emitMove(dst, m_globalObjectRegister);
1953     return m_globalObjectRegister;
1954 }
1955
1956 template<typename LookUpVarKindFunctor>
1957 bool BytecodeGenerator::instantiateLexicalVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable, ScopeRegisterType scopeRegisterType, LookUpVarKindFunctor lookUpVarKind)
1958 {
1959     bool hasCapturedVariables = false;
1960     {
1961         for (auto& entry : lexicalVariables) {
1962             ASSERT(entry.value.isLet() || entry.value.isConst() || entry.value.isFunction());
1963             ASSERT(!entry.value.isVar());
1964             SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
1965             ASSERT(symbolTableEntry.isNull());
1966
1967             // Imported bindings which are not the namespace bindings are not allocated
1968             // in the module environment as usual variables' way.
1969             // And since these types of the variables only seen in the module environment,
1970             // other lexical environment need not to take care this.
1971             if (entry.value.isImported() && !entry.value.isImportedNamespace())
1972                 continue;
1973
1974             VarKind varKind = lookUpVarKind(entry.key.get(), entry.value);
1975             VarOffset varOffset;
1976             if (varKind == VarKind::Scope) {
1977                 varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
1978                 hasCapturedVariables = true;
1979             } else {
1980                 ASSERT(varKind == VarKind::Stack);
1981                 RegisterID* local;
1982                 if (scopeRegisterType == ScopeRegisterType::Block) {
1983                     local = newBlockScopeVariable();
1984                     local->ref();
1985                 } else
1986                     local = addVar();
1987                 varOffset = VarOffset(local->virtualRegister());
1988             }
1989
1990             SymbolTableEntry newEntry(varOffset, static_cast<unsigned>(entry.value.isConst() ? PropertyAttribute::ReadOnly : PropertyAttribute::None));
1991             symbolTable->add(NoLockingNecessary, entry.key.get(), newEntry);
1992         }
1993     }
1994     return hasCapturedVariables;
1995 }
1996
1997 void BytecodeGenerator::emitPrefillStackTDZVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable)
1998 {
1999     // Prefill stack variables with the TDZ empty value.
2000     // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated.
2001     for (auto& entry : lexicalVariables) {
2002         // Imported bindings which are not the namespace bindings are not allocated
2003         // in the module environment as usual variables' way.
2004         // And since these types of the variables only seen in the module environment,
2005         // other lexical environment need not to take care this.
2006         if (entry.value.isImported() && !entry.value.isImportedNamespace())
2007             continue;
2008
2009         if (entry.value.isFunction())
2010             continue;
2011
2012         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2013         ASSERT(!symbolTableEntry.isNull());
2014         VarOffset offset = symbolTableEntry.varOffset();
2015         if (offset.isScope())
2016             continue;
2017
2018         ASSERT(offset.isStack());
2019         emitMoveEmptyValue(&registerFor(offset.stackOffset()));
2020     }
2021 }
2022
2023 void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType, RegisterID** constantSymbolTableResult, bool shouldInitializeBlockScopedFunctions)
2024 {
2025     VariableEnvironment& environment = node->lexicalVariables();
2026     RegisterID* constantSymbolTableResultTemp = nullptr;
2027     pushLexicalScopeInternal(environment, tdzCheckOptimization, nestedScopeType, &constantSymbolTableResultTemp, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
2028
2029     if (shouldInitializeBlockScopedFunctions)
2030         initializeBlockScopedFunctions(environment, node->functionStack(), constantSymbolTableResultTemp);
2031
2032     if (constantSymbolTableResult && constantSymbolTableResultTemp)
2033         *constantSymbolTableResult = constantSymbolTableResultTemp;
2034 }
2035
2036 void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType,
2037     RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType)
2038 {
2039     if (!environment.size())
2040         return;
2041
2042     if (m_shouldEmitDebugHooks)
2043         environment.markAllVariablesAsCaptured();
2044
2045     SymbolTable* symbolTable = SymbolTable::create(*m_vm);
2046     switch (scopeType) {
2047     case ScopeType::CatchScope:
2048         symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope);
2049         break;
2050     case ScopeType::LetConstScope:
2051         symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
2052         break;
2053     case ScopeType::FunctionNameScope:
2054         symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope);
2055         break;
2056     }
2057
2058     if (nestedScopeType == NestedScopeType::IsNested)
2059         symbolTable->markIsNestedLexicalScope();
2060
2061     auto lookUpVarKind = [] (UniquedStringImpl*, const VariableEnvironmentEntry& entry) -> VarKind {
2062         return entry.isCaptured() ? VarKind::Scope : VarKind::Stack;
2063     };
2064
2065     bool hasCapturedVariables = instantiateLexicalVariables(environment, symbolTable, scopeRegisterType, lookUpVarKind);
2066
2067     RegisterID* newScope = nullptr;
2068     RegisterID* constantSymbolTable = nullptr;
2069     int symbolTableConstantIndex = 0;
2070     if (vm()->typeProfiler()) {
2071         constantSymbolTable = addConstantValue(symbolTable);
2072         symbolTableConstantIndex = constantSymbolTable->index();
2073     }
2074     if (hasCapturedVariables) {
2075         if (scopeRegisterType == ScopeRegisterType::Block) {
2076             newScope = newBlockScopeVariable();
2077             newScope->ref();
2078         } else
2079             newScope = addVar();
2080         if (!constantSymbolTable) {
2081             ASSERT(!vm()->typeProfiler());
2082             constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm));
2083             symbolTableConstantIndex = constantSymbolTable->index();
2084         }
2085         if (constantSymbolTableResult)
2086             *constantSymbolTableResult = constantSymbolTable;
2087
2088         emitOpcode(op_create_lexical_environment);
2089         instructions().append(newScope->index());
2090         instructions().append(scopeRegister()->index());
2091         instructions().append(constantSymbolTable->index());
2092         instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index());
2093
2094         emitMove(scopeRegister(), newScope);
2095
2096         pushLocalControlFlowScope();
2097     }
2098
2099     bool isWithScope = false;
2100     m_lexicalScopeStack.append({ symbolTable, newScope, isWithScope, symbolTableConstantIndex });
2101     pushTDZVariables(environment, tdzCheckOptimization, tdzRequirement);
2102
2103     if (tdzRequirement == TDZRequirement::UnderTDZ)
2104         emitPrefillStackTDZVariables(environment, symbolTable);
2105 }
2106
2107 void BytecodeGenerator::initializeBlockScopedFunctions(VariableEnvironment& environment, FunctionStack& functionStack, RegisterID* constantSymbolTable)
2108 {
2109     /*
2110      * We must transform block scoped function declarations in strict mode like so:
2111      *
2112      * function foo() {
2113      *     if (c) {
2114      *           function foo() { ... }
2115      *           if (bar) { ... }
2116      *           else { ... }
2117      *           function baz() { ... }
2118      *     }
2119      * }
2120      *
2121      * to:
2122      *
2123      * function foo() {
2124      *     if (c) {
2125      *         let foo = function foo() { ... }
2126      *         let baz = function baz() { ... }
2127      *         if (bar) { ... }
2128      *         else { ... }
2129      *     }
2130      * }
2131      * 
2132      * But without the TDZ checks.
2133     */
2134
2135     if (!environment.size()) {
2136         RELEASE_ASSERT(!functionStack.size());
2137         return;
2138     }
2139
2140     if (!functionStack.size())
2141         return;
2142
2143     SymbolTable* symbolTable = m_lexicalScopeStack.last().m_symbolTable;
2144     RegisterID* scope = m_lexicalScopeStack.last().m_scope;
2145     RefPtr<RegisterID> temp = newTemporary();
2146     int symbolTableIndex = constantSymbolTable ? constantSymbolTable->index() : 0;
2147     for (FunctionMetadataNode* function : functionStack) {
2148         const Identifier& name = function->ident();
2149         auto iter = environment.find(name.impl());
2150         RELEASE_ASSERT(iter != environment.end());
2151         RELEASE_ASSERT(iter->value.isFunction());
2152         // We purposefully don't hold the symbol table lock around this loop because emitNewFunctionExpressionCommon may GC.
2153         SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, name.impl()); 
2154         RELEASE_ASSERT(!entry.isNull());
2155         emitNewFunctionExpressionCommon(temp.get(), function);
2156         bool isLexicallyScoped = true;
2157         emitPutToScope(scope, variableForLocalEntry(name, entry, symbolTableIndex, isLexicallyScoped), temp.get(), DoNotThrowIfNotFound, InitializationMode::Initialization);
2158     }
2159 }
2160
2161 void BytecodeGenerator::hoistSloppyModeFunctionIfNecessary(const Identifier& functionName)
2162 {
2163     if (m_scopeNode->hasSloppyModeHoistedFunction(functionName.impl())) {
2164         if (codeType() != EvalCode) {
2165             Variable currentFunctionVariable = variable(functionName);
2166             RefPtr<RegisterID> currentValue;
2167             if (RegisterID* local = currentFunctionVariable.local())
2168                 currentValue = local;
2169             else {
2170                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2171                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2172             }
2173
2174             ASSERT(m_varScopeLexicalScopeStackIndex);
2175             ASSERT(*m_varScopeLexicalScopeStackIndex < m_lexicalScopeStack.size());
2176             LexicalScopeStackEntry varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex];
2177             SymbolTable* varSymbolTable = varScope.m_symbolTable;
2178             ASSERT(varSymbolTable->scopeType() == SymbolTable::ScopeType::VarScope);
2179             SymbolTableEntry entry = varSymbolTable->get(NoLockingNecessary, functionName.impl());
2180             if (functionName == propertyNames().arguments && entry.isNull()) {
2181                 // "arguments" might be put in the parameter scope when we have a non-simple
2182                 // parameter list since "arguments" is visible to expressions inside the
2183                 // parameter evaluation list.
2184                 // e.g:
2185                 // function foo(x = arguments) { { function arguments() { } } }
2186                 RELEASE_ASSERT(*m_varScopeLexicalScopeStackIndex > 0);
2187                 varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex - 1];
2188                 SymbolTable* parameterSymbolTable = varScope.m_symbolTable;
2189                 entry = parameterSymbolTable->get(NoLockingNecessary, functionName.impl());
2190             }
2191             RELEASE_ASSERT(!entry.isNull());
2192             bool isLexicallyScoped = false;
2193             emitPutToScope(varScope.m_scope, variableForLocalEntry(functionName, entry, varScope.m_symbolTableConstantIndex, isLexicallyScoped), currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2194         } else {
2195             Variable currentFunctionVariable = variable(functionName);
2196             RefPtr<RegisterID> currentValue;
2197             if (RegisterID* local = currentFunctionVariable.local())
2198                 currentValue = local;
2199             else {
2200                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2201                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2202             }
2203
2204             RefPtr<RegisterID> scopeId = emitResolveScopeForHoistingFuncDeclInEval(nullptr, functionName);
2205             RefPtr<RegisterID> checkResult = emitIsUndefined(newTemporary(), scopeId.get());
2206             
2207             Ref<Label> isNotVarScopeLabel = newLabel();
2208             emitJumpIfTrue(checkResult.get(), isNotVarScopeLabel.get());
2209
2210             // Put to outer scope
2211             emitPutToScope(scopeId.get(), functionName, currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2212             emitLabel(isNotVarScopeLabel.get());
2213
2214         }
2215     }
2216 }
2217
2218 RegisterID* BytecodeGenerator::emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier& property)
2219 {
2220     ASSERT(m_codeType == EvalCode);
2221
2222     dst = finalDestination(dst);
2223     emitOpcode(op_resolve_scope_for_hoisting_func_decl_in_eval);
2224     instructions().append(kill(dst));
2225     instructions().append(m_topMostScope->index());
2226     instructions().append(addConstant(property));
2227     return dst;
2228 }
2229
2230 void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node)
2231 {
2232     VariableEnvironment& environment = node->lexicalVariables();
2233     popLexicalScopeInternal(environment);
2234 }
2235
2236 void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment)
2237 {
2238     // NOTE: This function only makes sense for scopes that aren't ScopeRegisterType::Var (only function name scope right now is ScopeRegisterType::Var).
2239     // This doesn't make sense for ScopeRegisterType::Var because we deref RegisterIDs here.
2240     if (!environment.size())
2241         return;
2242
2243     if (m_shouldEmitDebugHooks)
2244         environment.markAllVariablesAsCaptured();
2245
2246     auto stackEntry = m_lexicalScopeStack.takeLast();
2247     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2248     bool hasCapturedVariables = false;
2249     for (auto& entry : environment) {
2250         if (entry.value.isCaptured()) {
2251             hasCapturedVariables = true;
2252             continue;
2253         }
2254         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2255         ASSERT(!symbolTableEntry.isNull());
2256         VarOffset offset = symbolTableEntry.varOffset();
2257         ASSERT(offset.isStack());
2258         RegisterID* local = &registerFor(offset.stackOffset());
2259         local->deref();
2260     }
2261
2262     if (hasCapturedVariables) {
2263         RELEASE_ASSERT(stackEntry.m_scope);
2264         emitPopScope(scopeRegister(), stackEntry.m_scope);
2265         popLocalControlFlowScope();
2266         stackEntry.m_scope->deref();
2267     }
2268
2269     m_TDZStack.removeLast();
2270 }
2271
2272 void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable)
2273 {
2274     VariableEnvironment& environment = node->lexicalVariables();
2275     if (!environment.size())
2276         return;
2277     if (m_shouldEmitDebugHooks)
2278         environment.markAllVariablesAsCaptured();
2279     if (!environment.hasCapturedVariables())
2280         return;
2281
2282     RELEASE_ASSERT(loopSymbolTable);
2283
2284     // This function needs to do setup for a for loop's activation if any of
2285     // the for loop's lexically declared variables are captured (that is, variables
2286     // declared in the loop header, not the loop body). This function needs to
2287     // make a copy of the current activation and copy the values from the previous
2288     // activation into the new activation because each iteration of a for loop
2289     // gets a new activation.
2290
2291     auto stackEntry = m_lexicalScopeStack.last();
2292     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2293     RegisterID* loopScope = stackEntry.m_scope;
2294     ASSERT(symbolTable->scopeSize());
2295     ASSERT(loopScope);
2296     Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver;
2297
2298     {
2299         activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize());
2300
2301         for (auto end = symbolTable->end(NoLockingNecessary), ptr = symbolTable->begin(NoLockingNecessary); ptr != end; ++ptr) {
2302             if (!ptr->value.varOffset().isScope())
2303                 continue;
2304
2305             RefPtr<UniquedStringImpl> ident = ptr->key;
2306             Identifier identifier = Identifier::fromUid(m_vm, ident.get());
2307
2308             RegisterID* transitionValue = newBlockScopeVariable();
2309             transitionValue->ref();
2310             emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound);
2311             activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier));
2312         }
2313     }
2314
2315     // We need this dynamic behavior of the executing code to ensure
2316     // each loop iteration has a new activation object. (It's pretty ugly).
2317     // Also, this new activation needs to be assigned to the same register
2318     // as the previous scope because the loop body is compiled under
2319     // the assumption that the scope's register index is constant even
2320     // though the value in that register will change on each loop iteration.
2321     RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope);
2322     emitMove(scopeRegister(), parentScope.get());
2323
2324     emitOpcode(op_create_lexical_environment);
2325     instructions().append(loopScope->index());
2326     instructions().append(scopeRegister()->index());
2327     instructions().append(loopSymbolTable->index());
2328     instructions().append(addConstantValue(jsTDZValue())->index());
2329
2330     emitMove(scopeRegister(), loopScope);
2331
2332     {
2333         for (auto pair : activationValuesToCopyOver) {
2334             const Identifier& identifier = pair.second;
2335             SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, identifier.impl());
2336             RELEASE_ASSERT(!entry.isNull());
2337             RegisterID* transitionValue = pair.first;
2338             emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2339             transitionValue->deref();
2340         }
2341     }
2342 }
2343
2344 Variable BytecodeGenerator::variable(const Identifier& property, ThisResolutionType thisResolutionType)
2345 {
2346     if (property == propertyNames().thisIdentifier && thisResolutionType == ThisResolutionType::Local)
2347         return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(), static_cast<unsigned>(PropertyAttribute::ReadOnly), Variable::SpecialVariable, 0, false);
2348     
2349     // We can optimize lookups if the lexical variable is found before a "with" or "catch"
2350     // scope because we're guaranteed static resolution. If we have to pass through
2351     // a "with" or "catch" scope we loose this guarantee.
2352     // We can't optimize cases like this:
2353     // {
2354     //     let x = ...;
2355     //     with (o) {
2356     //         doSomethingWith(x);
2357     //     }
2358     // }
2359     // Because we can't gaurantee static resolution on x.
2360     // But, in this case, we are guaranteed static resolution:
2361     // {
2362     //     let x = ...;
2363     //     with (o) {
2364     //         let x = ...;
2365     //         doSomethingWith(x);
2366     //     }
2367     // }
2368     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2369         auto& stackEntry = m_lexicalScopeStack[i];
2370         if (stackEntry.m_isWithScope)
2371             return Variable(property);
2372         SymbolTable* symbolTable = stackEntry.m_symbolTable;
2373         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, property.impl());
2374         if (symbolTableEntry.isNull())
2375             continue;
2376         bool resultIsCallee = false;
2377         if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2378             if (m_usesNonStrictEval) {
2379                 // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name.
2380                 // We resort to dynamic lookup to answer this question.
2381                 Variable result = Variable(property);
2382                 return result;
2383             }
2384             resultIsCallee = true;
2385         }
2386         Variable result = variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope);
2387         if (resultIsCallee)
2388             result.setIsReadOnly();
2389         return result;
2390     }
2391     
2392     return Variable(property);
2393 }
2394
2395 Variable BytecodeGenerator::variableForLocalEntry(
2396     const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped)
2397 {
2398     VarOffset offset = entry.varOffset();
2399     
2400     RegisterID* local;
2401     if (offset.isStack())
2402         local = &registerFor(offset.stackOffset());
2403     else
2404         local = nullptr;
2405     
2406     return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped);
2407 }
2408
2409 void BytecodeGenerator::createVariable(
2410     const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode)
2411 {
2412     ASSERT(property != propertyNames().thisIdentifier);
2413     SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, property.impl());
2414     
2415     if (!entry.isNull()) {
2416         if (existingVariableMode == IgnoreExisting)
2417             return;
2418         
2419         // Do some checks to ensure that the variable we're being asked to create is sufficiently
2420         // compatible with the one we have already created.
2421
2422         VarOffset offset = entry.varOffset();
2423         
2424         // We can't change our minds about whether it's captured.
2425         if (offset.kind() != varKind) {
2426             dataLog(
2427                 "Trying to add variable called ", property, " as ", varKind,
2428                 " but it was already added as ", offset, ".\n");
2429             RELEASE_ASSERT_NOT_REACHED();
2430         }
2431
2432         return;
2433     }
2434     
2435     VarOffset varOffset;
2436     if (varKind == VarKind::Scope)
2437         varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
2438     else {
2439         ASSERT(varKind == VarKind::Stack);
2440         varOffset = VarOffset(virtualRegisterForLocal(m_calleeLocals.size()));
2441     }
2442     SymbolTableEntry newEntry(varOffset, 0);
2443     symbolTable->add(NoLockingNecessary, property.impl(), newEntry);
2444     
2445     if (varKind == VarKind::Stack) {
2446         RegisterID* local = addVar();
2447         RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
2448     }
2449 }
2450
2451 RegisterID* BytecodeGenerator::emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue)
2452 {
2453     emitOpcode(op_overrides_has_instance);
2454     instructions().append(dst->index());
2455     instructions().append(constructor->index());
2456     instructions().append(hasInstanceValue->index());
2457     return dst;
2458 }
2459
2460 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
2461 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
2462 ResolveType BytecodeGenerator::resolveType()
2463 {
2464     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2465         if (m_lexicalScopeStack[i].m_isWithScope)
2466             return Dynamic;
2467         if (m_usesNonStrictEval && m_lexicalScopeStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2468             // We never want to assign to a FunctionNameScope. Returning Dynamic here achieves this goal.
2469             // If we aren't in non-strict eval mode, then NodesCodeGen needs to take care not to emit
2470             // a put_to_scope with the destination being the function name scope variable.
2471             return Dynamic;
2472         }
2473     }
2474
2475     if (m_usesNonStrictEval)
2476         return GlobalPropertyWithVarInjectionChecks;
2477     return GlobalProperty;
2478 }
2479
2480 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
2481 {
2482     switch (variable.offset().kind()) {
2483     case VarKind::Stack:
2484         return nullptr;
2485         
2486     case VarKind::DirectArgument:
2487         return argumentsRegister();
2488         
2489     case VarKind::Scope: {
2490         // This always refers to the activation that *we* allocated, and not the current scope that code
2491         // lives in. Note that this will change once we have proper support for block scoping. Once that
2492         // changes, it will be correct for this code to return scopeRegister(). The only reason why we
2493         // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
2494         // requires weird things because it is a shameful pile of nonsense, but block scoping would make
2495         // that code sensible and obviate the need for us to do bad things.
2496         for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2497             auto& stackEntry = m_lexicalScopeStack[i];
2498             // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current
2499             // scope and the resolved scope.
2500             RELEASE_ASSERT(!stackEntry.m_isWithScope);
2501
2502             if (stackEntry.m_symbolTable->get(NoLockingNecessary, variable.ident().impl()).isNull())
2503                 continue;
2504             
2505             RegisterID* scope = stackEntry.m_scope;
2506             RELEASE_ASSERT(scope);
2507             return scope;
2508         }
2509
2510         RELEASE_ASSERT_NOT_REACHED();
2511         return nullptr;
2512         
2513     }
2514     case VarKind::Invalid:
2515         // Indicates non-local resolution.
2516         
2517         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2518         
2519         // resolve_scope dst, id, ResolveType, depth
2520         dst = tempDestination(dst);
2521         emitOpcode(op_resolve_scope);
2522         instructions().append(kill(dst));
2523         instructions().append(scopeRegister()->index());
2524         instructions().append(addConstant(variable.ident()));
2525         instructions().append(resolveType());
2526         instructions().append(localScopeDepth());
2527         instructions().append(0);
2528         return dst;
2529     }
2530     
2531     RELEASE_ASSERT_NOT_REACHED();
2532     return nullptr;
2533 }
2534
2535 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
2536 {
2537     switch (variable.offset().kind()) {
2538     case VarKind::Stack:
2539         return emitMove(dst, variable.local());
2540         
2541     case VarKind::DirectArgument: {
2542         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
2543         instructions().append(kill(dst));
2544         instructions().append(scope->index());
2545         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2546         instructions().append(profile);
2547         return dst;
2548     }
2549         
2550     case VarKind::Scope:
2551     case VarKind::Invalid: {
2552         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2553         
2554         // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2555         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
2556         instructions().append(kill(dst));
2557         instructions().append(scope->index());
2558         instructions().append(addConstant(variable.ident()));
2559         instructions().append(GetPutInfo(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType(), InitializationMode::NotInitialization).operand());
2560         instructions().append(localScopeDepth());
2561         instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
2562         instructions().append(profile);
2563         return dst;
2564     } }
2565     
2566     RELEASE_ASSERT_NOT_REACHED();
2567 }
2568
2569 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode, InitializationMode initializationMode)
2570 {
2571     switch (variable.offset().kind()) {
2572     case VarKind::Stack:
2573         emitMove(variable.local(), value);
2574         return value;
2575         
2576     case VarKind::DirectArgument:
2577         emitOpcode(op_put_to_arguments);
2578         instructions().append(scope->index());
2579         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2580         instructions().append(value->index());
2581         return value;
2582         
2583     case VarKind::Scope:
2584     case VarKind::Invalid: {
2585         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2586         
2587         // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2588         emitOpcode(op_put_to_scope);
2589         instructions().append(scope->index());
2590         instructions().append(addConstant(variable.ident()));
2591         instructions().append(value->index());
2592         ScopeOffset offset;
2593         if (variable.offset().isScope()) {
2594             offset = variable.offset().scopeOffset();
2595             instructions().append(GetPutInfo(resolveMode, LocalClosureVar, initializationMode).operand());
2596             instructions().append(variable.symbolTableConstantIndex());
2597         } else {
2598             ASSERT(resolveType() != LocalClosureVar);
2599             instructions().append(GetPutInfo(resolveMode, resolveType(), initializationMode).operand());
2600             instructions().append(localScopeDepth());
2601         }
2602         instructions().append(!!offset ? offset.offset() : 0);
2603         return value;
2604     } }
2605     
2606     RELEASE_ASSERT_NOT_REACHED();
2607 }
2608
2609 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
2610 {
2611     RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid);
2612     RegisterID* scope = emitResolveScope(nullptr, variable);
2613     return emitPutToScope(scope, variable, value, ThrowIfNotFound, InitializationMode::NotInitialization);
2614 }
2615
2616 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
2617 {
2618     emitOpcode(op_instanceof);
2619     instructions().append(dst->index());
2620     instructions().append(value->index());
2621     instructions().append(basePrototype->index());
2622     return dst;
2623 }
2624
2625 RegisterID* BytecodeGenerator::emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue)
2626 {
2627     emitOpcode(op_instanceof_custom);
2628     instructions().append(dst->index());
2629     instructions().append(value->index());
2630     instructions().append(constructor->index());
2631     instructions().append(hasInstanceValue->index());
2632     return dst;
2633 }
2634
2635 RegisterID* BytecodeGenerator::emitIn(RegisterID* dst, RegisterID* property, RegisterID* base)
2636 {
2637     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2638     emitOpcode(op_in);
2639     instructions().append(dst->index());
2640     instructions().append(base->index());
2641     instructions().append(property->index());
2642     instructions().append(arrayProfile);
2643     return dst;
2644 }
2645
2646 RegisterID* BytecodeGenerator::emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2647 {
2648     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties are not supported with tryGetById.");
2649
2650     UnlinkedValueProfile profile = emitProfiledOpcode(op_try_get_by_id);
2651     instructions().append(kill(dst));
2652     instructions().append(base->index());
2653     instructions().append(addConstant(property));
2654     instructions().append(profile);
2655     return dst;
2656 }
2657
2658 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2659 {
2660     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2661
2662     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2663
2664     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
2665     instructions().append(kill(dst));
2666     instructions().append(base->index());
2667     instructions().append(addConstant(property));
2668     instructions().append(0);
2669     instructions().append(0);
2670     instructions().append(0);
2671     instructions().append(Options::prototypeHitCountForLLIntCaching());
2672     instructions().append(profile);
2673     return dst;
2674 }
2675
2676 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property)
2677 {
2678     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2679
2680     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id_with_this);
2681     instructions().append(kill(dst));
2682     instructions().append(base->index());
2683     instructions().append(thisVal->index());
2684     instructions().append(addConstant(property));
2685     instructions().append(profile);
2686     return dst;
2687 }
2688
2689 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
2690 {
2691     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2692
2693     unsigned propertyIndex = addConstant(property);
2694
2695     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2696
2697     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2698
2699     emitOpcode(op_put_by_id);
2700     instructions().append(base->index());
2701     instructions().append(propertyIndex);
2702     instructions().append(value->index());
2703     instructions().append(0); // old structure
2704     instructions().append(0); // offset
2705     instructions().append(0); // new structure
2706     instructions().append(0); // structure chain
2707     instructions().append(static_cast<int>(PutByIdNone)); // is not direct
2708
2709     return value;
2710 }
2711
2712 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value)
2713 {
2714     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2715
2716     unsigned propertyIndex = addConstant(property);
2717
2718     emitOpcode(op_put_by_id_with_this);
2719     instructions().append(base->index());
2720     instructions().append(thisValue->index());
2721     instructions().append(propertyIndex);
2722     instructions().append(value->index());
2723
2724     return value;
2725 }
2726
2727 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
2728 {
2729     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val(direct).");
2730
2731     unsigned propertyIndex = addConstant(property);
2732
2733     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2734
2735     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2736     
2737     emitOpcode(op_put_by_id);
2738     instructions().append(base->index());
2739     instructions().append(propertyIndex);
2740     instructions().append(value->index());
2741     instructions().append(0); // old structure
2742     instructions().append(0); // offset
2743     instructions().append(0); // new structure
2744     instructions().append(0); // structure chain (unused if direct)
2745     instructions().append(static_cast<int>((putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto) ? PutByIdIsDirect : PutByIdNone));
2746     return value;
2747 }
2748
2749 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter)
2750 {
2751     unsigned propertyIndex = addConstant(property);
2752     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2753
2754     emitOpcode(op_put_getter_by_id);
2755     instructions().append(base->index());
2756     instructions().append(propertyIndex);
2757     instructions().append(attributes);
2758     instructions().append(getter->index());
2759 }
2760
2761 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* setter)
2762 {
2763     unsigned propertyIndex = addConstant(property);
2764     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2765
2766     emitOpcode(op_put_setter_by_id);
2767     instructions().append(base->index());
2768     instructions().append(propertyIndex);
2769     instructions().append(attributes);
2770     instructions().append(setter->index());
2771 }
2772
2773 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter)
2774 {
2775     unsigned propertyIndex = addConstant(property);
2776
2777     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2778
2779     emitOpcode(op_put_getter_setter_by_id);
2780     instructions().append(base->index());
2781     instructions().append(propertyIndex);
2782     instructions().append(attributes);
2783     instructions().append(getter->index());
2784     instructions().append(setter->index());
2785 }
2786
2787 void BytecodeGenerator::emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* getter)
2788 {
2789     emitOpcode(op_put_getter_by_val);
2790     instructions().append(base->index());
2791     instructions().append(property->index());
2792     instructions().append(attributes);
2793     instructions().append(getter->index());
2794 }
2795
2796 void BytecodeGenerator::emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* setter)
2797 {
2798     emitOpcode(op_put_setter_by_val);
2799     instructions().append(base->index());
2800     instructions().append(property->index());
2801     instructions().append(attributes);
2802     instructions().append(setter->index());
2803 }
2804
2805 void BytecodeGenerator::emitPutGeneratorFields(RegisterID* nextFunction)
2806 {
2807     // FIXME: Currently, we just create an object and store generator related fields as its properties for ease.
2808     // But to make it efficient, we will introduce JSGenerator class, add opcode new_generator and use its C++ fields instead of these private properties.
2809     // https://bugs.webkit.org/show_bug.cgi?id=151545
2810
2811     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2812
2813     // We do not store 'this' in arrow function within constructor,
2814     // because it might be not initialized, if super is called later.
2815     if (!(isDerivedConstructorContext() && m_codeBlock->parseMode() == SourceParseMode::AsyncArrowFunctionMode))
2816         emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2817
2818     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(0)), PropertyNode::KnownDirect);
2819
2820     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2821 }
2822
2823 void BytecodeGenerator::emitPutAsyncGeneratorFields(RegisterID* nextFunction)
2824 {
2825     ASSERT(isAsyncGeneratorFunctionParseMode(parseMode()));
2826
2827     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2828         
2829     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2830         
2831     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorState::SuspendedStart))), PropertyNode::KnownDirect);
2832         
2833     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2834
2835     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorSuspendReasonPrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason::None))), PropertyNode::KnownDirect);
2836
2837     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorQueueFirstPrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2838     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorQueueLastPrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2839 }
2840
2841 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
2842 {
2843     emitOpcode(op_del_by_id);
2844     instructions().append(dst->index());
2845     instructions().append(base->index());
2846     instructions().append(addConstant(property));
2847     return dst;
2848 }
2849
2850 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2851 {
2852     for (size_t i = m_forInContextStack.size(); i--; ) {
2853         ForInContext& context = m_forInContextStack[i].get();
2854         if (context.local() != property)
2855             continue;
2856
2857         unsigned instIndex = instructions().size();
2858
2859         if (context.type() == ForInContext::IndexedForInContextType) {
2860             static_cast<IndexedForInContext&>(context).addGetInst(instIndex, property->index());
2861             property = static_cast<IndexedForInContext&>(context).index();
2862             break;
2863         }
2864
2865         ASSERT(context.type() == ForInContext::StructureForInContextType);
2866         StructureForInContext& structureContext = static_cast<StructureForInContext&>(context);
2867         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
2868         instructions().append(kill(dst));
2869         instructions().append(base->index());
2870         instructions().append(property->index());
2871         instructions().append(structureContext.index()->index());
2872         instructions().append(structureContext.enumerator()->index());
2873         instructions().append(profile);
2874
2875         structureContext.addGetInst(instIndex, property->index(), profile);
2876         return dst;
2877     }
2878
2879     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2880     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
2881     instructions().append(kill(dst));
2882     instructions().append(base->index());
2883     instructions().append(property->index());
2884     instructions().append(arrayProfile);
2885     instructions().append(profile);
2886     return dst;
2887 }
2888
2889 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property)
2890 {
2891     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val_with_this);
2892     instructions().append(kill(dst));
2893     instructions().append(base->index());
2894     instructions().append(thisValue->index());
2895     instructions().append(property->index());
2896     instructions().append(profile);
2897     return dst;
2898 }
2899
2900 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2901 {
2902     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2903     emitOpcode(op_put_by_val);
2904     instructions().append(base->index());
2905     instructions().append(property->index());
2906     instructions().append(value->index());
2907     instructions().append(arrayProfile);
2908
2909     return value;
2910 }
2911
2912 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value)
2913 {
2914     emitOpcode(op_put_by_val_with_this);
2915     instructions().append(base->index());
2916     instructions().append(thisValue->index());
2917     instructions().append(property->index());
2918     instructions().append(value->index());
2919
2920     return value;
2921 }
2922
2923 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2924 {
2925     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2926     emitOpcode(op_put_by_val_direct);
2927     instructions().append(base->index());
2928     instructions().append(property->index());
2929     instructions().append(value->index());
2930     instructions().append(arrayProfile);
2931     return value;
2932 }
2933
2934 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2935 {
2936     emitOpcode(op_del_by_val);
2937     instructions().append(dst->index());
2938     instructions().append(base->index());
2939     instructions().append(property->index());
2940     return dst;
2941 }
2942
2943 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
2944 {
2945     emitOpcode(op_put_by_index);
2946     instructions().append(base->index());
2947     instructions().append(index);
2948     instructions().append(value->index());
2949     return value;
2950 }
2951
2952 RegisterID* BytecodeGenerator::emitAssert(RegisterID* condition, int line)
2953 {
2954     emitOpcode(op_assert);
2955     instructions().append(condition->index());
2956     instructions().append(line);
2957     return condition;
2958 }
2959
2960 RegisterID* BytecodeGenerator::emitIdWithProfile(RegisterID* src, SpeculatedType profile)
2961 {
2962     emitOpcode(op_identity_with_profile);
2963     instructions().append(src->index());
2964     instructions().append(static_cast<uint32_t>(profile >> 32));
2965     instructions().append(static_cast<uint32_t>(profile));
2966     return src;
2967 }
2968
2969 void BytecodeGenerator::emitUnreachable()
2970 {
2971     emitOpcode(op_unreachable);
2972 }
2973
2974 RegisterID* BytecodeGenerator::emitGetArgument(RegisterID* dst, int32_t index)
2975 {
2976     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_argument);
2977     instructions().append(dst->index());
2978     instructions().append(index + 1); // Including |this|.
2979     instructions().append(profile);
2980     return dst;
2981 }
2982
2983 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
2984 {
2985     size_t begin = instructions().size();
2986     m_staticPropertyAnalyzer.createThis(dst->index(), begin + 3);
2987
2988     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2989     emitOpcode(op_create_this); 
2990     instructions().append(dst->index());
2991     instructions().append(dst->index());
2992     instructions().append(0);
2993     instructions().append(0);
2994     return dst;
2995 }
2996
2997 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
2998 {
2999     emitOpcode(op_check_tdz);
3000     instructions().append(target->index());
3001 }
3002
3003 bool BytecodeGenerator::needsTDZCheck(const Variable& variable)
3004 {
3005     for (unsigned i = m_TDZStack.size(); i--;) {
3006         auto iter = m_TDZStack[i].find(variable.ident().impl());
3007         if (iter == m_TDZStack[i].end())
3008             continue;
3009         return iter->value != TDZNecessityLevel::NotNeeded;
3010     }
3011
3012     return false;
3013 }
3014
3015 void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope)
3016 {
3017     if (needsTDZCheck(variable)) {
3018         if (target)
3019             emitTDZCheck(target);
3020         else {
3021             RELEASE_ASSERT(!variable.isLocal() && scope);
3022             RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound);
3023             emitTDZCheck(result.get());
3024         }
3025     }
3026 }
3027
3028 void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable)
3029 {
3030     RefPtr<UniquedStringImpl> identifier(variable.ident().impl());
3031     for (unsigned i = m_TDZStack.size(); i--;) {
3032         auto iter = m_TDZStack[i].find(identifier);
3033         if (iter != m_TDZStack[i].end()) {
3034             if (iter->value == TDZNecessityLevel::Optimize)
3035                 iter->value = TDZNecessityLevel::NotNeeded;
3036             break;
3037         }
3038     }
3039 }
3040
3041 void BytecodeGenerator::pushTDZVariables(const VariableEnvironment& environment, TDZCheckOptimization optimization, TDZRequirement requirement)
3042 {
3043     if (!environment.size())
3044         return;
3045     
3046     TDZNecessityLevel level;
3047     if (requirement == TDZRequirement::UnderTDZ) {
3048         if (optimization == TDZCheckOptimization::Optimize)
3049             level = TDZNecessityLevel::Optimize;
3050         else
3051             level = TDZNecessityLevel::DoNotOptimize;
3052     } else
3053         level = TDZNecessityLevel::NotNeeded;
3054     
3055     TDZMap map;
3056     for (const auto& entry : environment)
3057         map.add(entry.key, entry.value.isFunction() ? TDZNecessityLevel::NotNeeded : level);
3058
3059     m_TDZStack.append(WTFMove(map));
3060 }
3061
3062 void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result)
3063 {
3064     // We keep track of variablesThatDontNeedTDZ in this algorithm to prevent
3065     // reporting that "x" is under TDZ if this function is called at "...".
3066     //
3067     //     {
3068     //         {
3069     //             let x;
3070     //             ...
3071     //         }
3072     //         let x;
3073     //     }
3074     //
3075     SmallPtrSet<UniquedStringImpl*, 16> variablesThatDontNeedTDZ;
3076     for (unsigned i = m_TDZStack.size(); i--; ) {
3077         auto& map = m_TDZStack[i];
3078         for (auto& entry : map)  {
3079             if (entry.value != TDZNecessityLevel::NotNeeded) {
3080                 if (!variablesThatDontNeedTDZ.contains(entry.key.get()))
3081                     result.add(entry.key.get());
3082             } else
3083                 variablesThatDontNeedTDZ.add(entry.key.get());
3084         }
3085     }
3086 }
3087
3088 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
3089 {
3090     size_t begin = instructions().size();
3091     m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
3092
3093     emitOpcode(op_new_object);
3094     instructions().append(dst->index());
3095     instructions().append(0);
3096     instructions().append(newObjectAllocationProfile());
3097     return dst;
3098 }
3099
3100 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
3101 {
3102     return m_codeBlock->addConstantBuffer(length);
3103 }
3104
3105 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
3106 {
3107     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
3108     if (!stringInMap) {
3109         stringInMap = jsString(vm(), identifier.string());
3110         addConstantValue(stringInMap);
3111     }
3112     return stringInMap;
3113 }
3114
3115 RegisterID* BytecodeGenerator::addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&& templateRegistryKey)
3116 {
3117     return m_templateRegistryKeyMap.ensure(templateRegistryKey.copyRef(), [&] {
3118         auto* result = JSTemplateRegistryKey::create(*vm(), WTFMove(templateRegistryKey));
3119         unsigned index = addConstantIndex();
3120         m_codeBlock->addConstant(result);
3121         return &m_constantPoolRegisters[index];
3122     }).iterator->value;
3123 }
3124
3125 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
3126 {
3127 #if !ASSERT_DISABLED
3128     unsigned checkLength = 0;
3129 #endif
3130     bool hadVariableExpression = false;
3131     if (length) {
3132         for (ElementNode* n = elements; n; n = n->next()) {
3133             if (!n->value()->isConstant()) {
3134                 hadVariableExpression = true;
3135                 break;
3136             }
3137             if (n->elision())
3138                 break;
3139 #if !ASSERT_DISABLED
3140             checkLength++;
3141 #endif
3142         }
3143         if (!hadVariableExpression) {
3144             ASSERT(length == checkLength);
3145             unsigned constantBufferIndex = addConstantBuffer(length);
3146             JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
3147             unsigned index = 0;
3148             for (ElementNode* n = elements; index < length; n = n->next()) {
3149                 ASSERT(n->value()->isConstant());
3150                 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
3151             }
3152             emitOpcode(op_new_array_buffer);
3153             instructions().append(dst->index());
3154             instructions().append(constantBufferIndex);
3155             instructions().append(length);
3156             instructions().append(newArrayAllocationProfile());
3157             return dst;
3158         }
3159     }
3160
3161     Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
3162     for (ElementNode* n = elements; n; n = n->next()) {
3163         if (!length)
3164             break;
3165         length--;
3166         ASSERT(!n->value()->isSpreadExpression());
3167         argv.append(newTemporary());
3168         // op_new_array requires the initial values to be a sequential range of registers
3169         ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
3170         emitNode(argv.last().get(), n->value());
3171     }
3172     ASSERT(!length);
3173     emitOpcode(op_new_array);
3174     instructions().append(dst->index());
3175     instructions().append(argv.size() ? argv[0]->index() : 0); // argv
3176     instructions().append(argv.size()); // argc
3177     instructions().append(newArrayAllocationProfile());
3178     return dst;
3179 }
3180
3181 RegisterID* BytecodeGenerator::emitNewArrayWithSpread(RegisterID* dst, ElementNode* elements)
3182 {
3183     BitVector bitVector;
3184     Vector<RefPtr<RegisterID>, 16> argv;
3185     for (ElementNode* node = elements; node; node = node->next()) {
3186         bitVector.set(argv.size(), node->value()->isSpreadExpression());
3187
3188         argv.append(newTemporary());
3189         // op_new_array_with_spread requires the initial values to be a sequential range of registers.
3190         RELEASE_ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
3191     }
3192
3193     RELEASE_ASSERT(argv.size());
3194
3195     {
3196         unsigned i = 0;
3197         for (ElementNode* node = elements; node; node = node->next()) {
3198             if (node->value()->isSpreadExpression()) {
3199                 ExpressionNode* expression = static_cast<SpreadExpressionNode*>(node->value())->expression();
3200                 RefPtr<RegisterID> tmp = newTemporary();
3201                 emitNode(tmp.get(), expression);
3202
3203                 emitOpcode(op_spread);
3204                 instructions().append(argv[i].get()->index());
3205                 instructions().append(tmp.get()->index());
3206             } else {
3207                 ExpressionNode* expression = node->value();
3208                 emitNode(argv[i].get(), expression);
3209             }
3210             i++;
3211         }
3212     }
3213
3214     unsigned bitVectorIndex = m_codeBlock->addBitVector(WTFMove(bitVector));
3215     emitOpcode(op_new_array_with_spread);
3216     instructions().append(dst->index());
3217     instructions().append(argv[0]->index()); // argv
3218     instructions().append(argv.size()); // argc
3219     instructions().append(bitVectorIndex);
3220
3221     return dst;
3222 }
3223
3224 RegisterID* BytecodeGenerator::emitNewArrayWithSize(RegisterID* dst, RegisterID* length)
3225 {
3226     emitOpcode(op_new_array_with_size);
3227     instructions().append(dst->index());
3228     instructions().append(length->index());
3229     instructions().append(newArrayAllocationProfile());
3230
3231     return dst;
3232 }
3233
3234 RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
3235 {
3236     emitOpcode(op_new_regexp);
3237     instructions().append(dst->index());
3238     instructions().append(addRegExp(regExp));
3239     return dst;
3240 }
3241
3242 void BytecodeGenerator::emitNewFunctionExpressionCommon(RegisterID* dst, FunctionMetadataNode* function)
3243 {
3244     unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
3245
3246     OpcodeID opcodeID = op_new_func_exp;
3247     switch (function->parseMode()) {
3248     case SourceParseMode::GeneratorWrapperFunctionMode:
3249     case SourceParseMode::GeneratorWrapperMethodMode:
3250         opcodeID = op_new_generator_func_exp;
3251         break;
3252     case SourceParseMode::AsyncFunctionMode:
3253     case SourceParseMode::AsyncMethodMode:
3254     case SourceParseMode::AsyncArrowFunctionMode:
3255         opcodeID = op_new_async_func_exp;
3256         break;
3257     case SourceParseMode::AsyncGeneratorWrapperFunctionMode:
3258     case SourceParseMode::AsyncGeneratorWrapperMethodMode:
3259         ASSERT(Options::useAsyncIterator());
3260         opcodeID = op_new_async_generator_func_exp;
3261         break;
3262     default:
3263         break;
3264     }
3265     
3266     emitOpcode(opcodeID);
3267     instructions().append(dst->index());
3268     instructions().append(scopeRegister()->index());
3269     instructions().append(index);
3270 }
3271
3272 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* dst, FuncExprNode* func)
3273 {
3274     emitNewFunctionExpressionCommon(dst, func->metadata());
3275     return dst;
3276 }
3277
3278 RegisterID* BytecodeGenerator::emitNewArrowFunctionExpression(RegisterID* dst, ArrowFuncExprNode* func)
3279 {
3280     ASSERT(SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(func->metadata()->parseMode()));
3281     emitNewFunctionExpressionCommon(dst, func->metadata());
3282     return dst;
3283 }
3284
3285 RegisterID* BytecodeGenerator::emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode* func)
3286 {
3287     ASSERT(isMethodParseMode(func->metadata()->parseMode()));
3288     emitNewFunctionExpressionCommon(dst, func->metadata());
3289     return dst;
3290 }
3291
3292 RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, ConstructorKind constructorKind, const Identifier& name,
3293     const Identifier& ecmaName, const SourceCode& classSource)
3294 {
3295     UnlinkedFunctionExecutable* executable = m_vm->builtinExecutables()->createDefaultConstructor(constructorKind, name);
3296     executable->setInvalidTypeProfilingOffsets();
3297     executable->setEcmaName(ecmaName);
3298     executable->setClassSource(classSource);
3299
3300     unsigned index = m_codeBlock->addFunctionExpr(executable);
3301
3302     emitOpcode(op_new_func_exp);
3303     instructions().append(dst->index());
3304     instructions().append(scopeRegister()->index());
3305     instructions().append(index);
3306     return dst;
3307 }
3308
3309 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionMetadataNode* function)
3310 {
3311     unsigned index = m_codeBlock->addFunctionDecl(makeFunction(function));
3312     if (isGeneratorWrapperParseMode(function->parseMode()))
3313         emitOpcode(op_new_generator_func);
3314     else if (function->parseMode() == SourceParseMode::AsyncFunctionMode)
3315         emitOpcode(op_new_async_func);
3316     else if (function->parseMode() == SourceParseMode::AsyncGeneratorWrapperFunctionMode) {
3317         ASSERT(Options::useAsyncIterator());
3318         emitOpcode(op_new_async_generator_func);
3319     } else
3320         emitOpcode(op_new_func);
3321     instructions().append(dst->index());
3322     instructions().append(scopeRegister()->index());
3323     instructions().append(index);
3324     return dst;
3325 }
3326
3327 void BytecodeGenerator::emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name)
3328 {
3329     if (valueNode->isBaseFuncExprNode()) {
3330         FunctionMetadataNode* metadata = static_cast<BaseFuncExprNode*>(valueNode)->metadata();
3331         if (!metadata->ecmaName().isNull())
3332             return;
3333     } else if (valueNode->isClassExprNode()) {
3334         ClassExprNode* classExprNode = static_cast<ClassExprNode*>(valueNode);
3335         if (!classExprNode->ecmaName().isNull())
3336             return;
3337         if (classExprNode->hasStaticProperty(m_vm->propertyNames->name))
3338             return;
3339     } else
3340         return;
3341
3342     // FIXME: We should use an op_call to an internal function here instead.
3343     // https://bugs.webkit.org/show_bug.cgi?id=155547
3344     emitOpcode(op_set_function_name);
3345     instructions().append(value->index());
3346     instructions().append(name->index());
3347 }
3348
3349 RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3350 {
3351     return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd, debuggableCall);
3352 }
3353
3354 RegisterID* BytecodeGenerator::emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3355 {
3356     if (m_inTailPosition) {
3357         m_codeBlock->setHasTailCalls();
3358         return emitCall(op_tail_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd, debuggableCall);
3359     }
3360     return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd, debuggableCall);
3361 }
3362
3363 RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3364 {
3365     return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, divotStart, divotEnd, debuggableCall);
3366 }
3367
3368 ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
3369 {
3370     if (identifier == propertyNames().Object || identifier == propertyNames().builtinNames().ObjectPrivateName())
3371         return ExpectObjectConstructor;
3372     if (identifier == propertyNames().Array || identifier == propertyNames().builtinNames().ArrayPrivateName())
3373         return ExpectArrayConstructor;
3374     return NoExpectedFunction;
3375 }
3376
3377 ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label& done)
3378 {
3379     Ref<Label> realCall = newLabel();
3380     switch (expectedFunction) {
3381     case ExpectObjectConstructor: {
3382         // If the number of arguments is non-zero, then we can't do anything interesting.
3383         if (callArguments.argumentCountIncludingThis() >= 2)
3384             return NoExpectedFunction;
3385         
3386         size_t begin = instructions().size();
3387         emitOpcode(op_jneq_ptr);
3388         instructions().append(func->index());
3389         instructions().append(Special::ObjectConstructor);
3390         instructions().append(realCall->bind(begin, instructions().size()));
3391         instructions().append(0);
3392         
3393         if (dst != ignoredResult())
3394             emitNewObject(dst);
3395         break;
3396     }
3397         
3398     case ExpectArrayConstructor: {
3399         // If you're doing anything other than "new Array()" or "new Array(foo)" then we
3400         // don't do inline it, for now. The only reason is that call arguments are in
3401         // the opposite order of what op_new_array expects, so we'd either need to change
3402         // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
3403         // things sounds like it's worth it.
3404         if (callArguments.argumentCountIncludingThis() > 2)
3405             return NoExpectedFunction;
3406         
3407         size_t begin = instructions().size();
3408         emitOpcode(op_jneq_ptr);
3409         instructions().append(func->index());
3410         instructions().append(Special::ArrayConstructor);
3411         instructions().append(realCall->bind(begin, instructions().size()));
3412         instructions().append(0);
3413         
3414         if (dst != ignoredResult()) {
3415             if (callArguments.argumentCountIncludingThis() == 2)
3416                 emitNewArrayWithSize(dst, callArguments.argumentRegister(0));
3417             else {
3418                 ASSERT(callArguments.argumentCountIncludingThis() == 1);
3419                 emitOpcode(op_new_array);
3420                 instructions().append(dst->index());
3421                 instructions().append(0);
3422                 instructions().append(0);
3423                 instructions().append(newArrayAllocationProfile());
3424             }
3425         }
3426         break;
3427     }
3428         
3429     default:
3430         ASSERT(expectedFunction == NoExpectedFunction);
3431         return NoExpectedFunction;
3432     }
3433     
3434     size_t begin = instructions().size();
3435     emitOpcode(op_jmp);
3436     instructions().append(done.bind(begin, instructions().size()));
3437     emitLabel(realCall.get());
3438     
3439     return expectedFunction;
3440 }
3441
3442 RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3443 {
3444     ASSERT(opcodeID == op_call || opcodeID == op_call_eval || opcodeID == op_tail_call);
3445     ASSERT(func->refCount());
3446     
3447     // Generate code for arguments.
3448     unsigned argument = 0;
3449     if (callArguments.argumentsNode()) {
3450         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
3451         if (n && n->m_expr->isSpreadExpression()) {
3452             RELEASE_ASSERT(!n->m_next);
3453             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
3454             if (expression->isArrayLiteral()) {
3455                 auto* elements = static_cast<ArrayNode*>(expression)->elements();
3456                 if (elements && !elements->next() && elements->value()->isSpreadExpression()) {
3457                     ExpressionNode* expression = static_cast<SpreadExpressionNode*>(elements->value())->expression();
3458                     RefPtr<RegisterID> argumentRegister = emitNode(callArguments.argumentRegister(0), expression);
3459                     emitOpcode(op_spread);
3460                     instructions().append(argumentRegister.get()->index());
3461                     instructions().append(argumentRegister.get()->index());
3462
3463                     RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
3464                     return emitCallVarargs(opcodeID == op_tail_call ? op_tail_call_varargs : op_call_varargs, dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, divot, divotStart, divotEnd, debuggableCall);
3465                 }
3466             }
3467             RefPtr<RegisterID> argumentRegister;
3468             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
3469             RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
3470             return emitCallVarargs(opcodeID == op_tail_call ? op_tail_call_varargs : op_call_varargs, dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, divot, divotStart, divotEnd, debuggableCall);
3471         }
3472         for (; n; n = n->m_next)
3473             emitNode(callArguments.argumentRegister(argument++), n);
3474     }
3475     
3476     // Reserve space for call frame.
3477     Vector<RefPtr<RegisterID>, CallFrame::headerSizeInRegisters, UnsafeVectorOverflow> callFrame;
3478     for (int i = 0; i < CallFrame::headerSizeInRegisters; ++i)
3479         callFrame.append(newTemporary());
3480
3481     if (m_shouldEmitDebugHooks && debuggableCall == DebuggableCall::Yes)
3482         emitDebugHook(WillExecuteExpression, divotStart);
3483
3484     emitExpressionInfo(divot, divotStart, divotEnd);
3485
3486     Ref<Label> done = newLabel();
3487     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
3488     
3489     if (opcodeID == op_tail_call)
3490         emitLogShadowChickenTailIfNecessary();
3491     
3492     // Emit call.
3493     UnlinkedArrayProfile arrayProfile = newArrayProfile();
3494     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
3495     ASSERT(dst);
3496     ASSERT(dst != ignoredResult());
3497     instructions().append(dst->index());
3498     instructions().append(func->index());
3499     instructions().append(callArguments.argumentCountIncludingThis());
3500     instructions().append(callArguments.stackOffset());
3501     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
3502     instructions().append(0);
3503     instructions().append(arrayProfile);
3504     instructions().append(profile);
3505     
3506     if (expectedFunction != NoExpectedFunction)
3507         emitLabel(done.get());
3508
3509     return dst;
3510 }
3511
3512 RegisterID* BytecodeGenerator::emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3513 {
3514     return emitCallVarargs(op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3515 }
3516
3517 RegisterID* BytecodeGenerator::emitCallVarargsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3518 {
3519     return emitCallVarargs(m_inTailPosition ? op_tail_call_varargs : op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3520 }
3521
3522 RegisterID* BytecodeGenerator::emitConstructVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3523 {
3524     return emitCallVarargs(op_construct_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3525 }
3526
3527 RegisterID* BytecodeGenerator::emitCallForwardArgumentsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3528 {
3529     ASSERT(m_inTailPosition);
3530     return emitCallVarargs(op_tail_call_forward_arguments, dst, func, thisRegister, nullptr, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3531 }
3532     
3533 RegisterID* BytecodeGenerator::emitCallVarargs(OpcodeID opcode, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3534 {
3535     if (m_shouldEmitDebugHooks && debuggableCall == DebuggableCall::Yes)
3536         emitDebugHook(WillExecuteExpression, divotStart);
3537
3538     emitExpressionInfo(divot, divotStart, divotEnd);
3539
3540     if (opcode == op_tail_call_varargs)
3541         emitLogShadowChickenTailIfNecessary();
3542     
3543     // Emit call.
3544     UnlinkedArrayProfile arrayProfile = newArrayProfile();
3545     UnlinkedValueProfile profile = emitProfiledOpcode(opcode);
3546     ASSERT(dst != ignoredResult());
3547     instructions().append(dst->index());
3548     instructions().append(func->index());
3549     instructions().append(thisRegister ? thisRegister->index() : 0);
3550     instructions().append(arguments ? arguments->index() : 0);
3551     instructions().append(firstFreeRegister->index());
3552     instructions().append(firstVarArgOffset);
3553     instructions().append(arrayProfile);
3554     instructions().append(profile);
3555     return dst;
3556 }
3557
3558 void BytecodeGenerator::emitLogShadowChickenPrologueIfNecessary()
3559 {
3560     if (!m_shouldEmitDebugHooks && !Options::alwaysUseShadowChicken())
3561         return;
3562     emitOpcode(op_log_shadow_chicken_prologue);
3563     instructions().append(scopeRegister()->index());
3564 }
3565
3566 void BytecodeGenerator::emitLogShadowChickenTailIfNecessary()
3567 {
3568     if (!m_shouldEmitDebugHooks && !Options::alwaysUseShadowChicken())
3569         return;
3570     emitOpcode(op_log_shadow_chicken_tail);
3571     instructions().append(thisRegister()->index());
3572     instructions().append(scopeRegister()->index());
3573 }
3574
3575 void BytecodeGenerator::emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
3576     RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition& position)
3577 {
3578     DefinePropertyAttributes attributes;
3579     if (options & PropertyConfigurable)
3580         attributes.setConfigurable(true);
3581
3582     if (options & PropertyWritable)
3583         attributes.setWritable(true);
3584     else if (valueRegister)
3585         attributes.setWritable(false);
3586
3587     if (options & PropertyEnumerable)
3588         attributes.setEnumerable(true);
3589
3590     if (valueRegister)
3591         attributes.setValue();
3592     if (getterRegister)
3593         attributes.setGet();
3594     if (setterRegister)
3595         attributes.setSet();
3596
3597     ASSERT(!valueRegister || (!getterRegister && !setterRegister));
3598
3599     emitExpressionInfo(position, position, position);
3600
3601     if (attributes.hasGet() || attributes.hasSet()) {
3602         RefPtr<RegisterID> throwTypeErrorFunction;
3603         if (!attributes.hasGet() || !attributes.hasSet())
3604             throwTypeErrorFunction = emitMoveLinkTimeConstant(nullptr, LinkTimeConstant::ThrowTypeErrorFunction);
3605
3606         RefPtr<RegisterID> getter;
3607         if (attributes.hasGet())
3608             getter = getterRegister;
3609         else
3610             getter = throwTypeErrorFunction;
3611
3612         RefPtr<RegisterID> setter;
3613         if (attributes.hasSet())
3614             setter = setterRegister;
3615         else
3616             setter = throwTypeErrorFunction;
3617
3618         emitOpcode(op_define_accessor_property);
3619         instructions().append(newObj->index());
3620         instructions().append(propertyNameRegister->index());
3621         instructions().append(getter->index());
3622         instructions().append(setter->index());
3623         instructions().append(emitLoad(nullptr, jsNumber(attributes.rawRepresentation()))->index());
3624     } else {
3625         emitOpcode(op_define_data_property);
3626         instructions().append(newObj->index());
3627         instructions().append(propertyNameRegister->index());
3628         instructions().append(valueRegister->index());
3629         instructions().append(emitLoad(nullptr, jsNumber(attributes.rawRepresentation()))->index());
3630     }
3631 }
3632
3633 RegisterID* BytecodeGenerator::emitReturn(RegisterID* src, ReturnFrom from)
3634 {
3635     if (isConstructor()) {
3636         bool isDerived = constructorKind() == ConstructorKind::Extends;
3637         bool srcIsThis = src->index() == m_thisRegister.index();
3638
3639         if (isDerived && (srcIsThis || from == ReturnFrom::Finally))
3640             emitTDZCheck(src);
3641
3642         if (!srcIsThis || from == ReturnFrom::Finally) {
3643             Ref<Label> isObjectLabel = newLabel();
3644             emitJumpIfTrue(emitIsObject(newTemporary(), src), isObjectLabel.get());
3645
3646             if (isDerived) {
3647                 Ref<Label> isUndefinedLabel = newLabel();
3648                 emitJumpIfTr