Speculatively change iteration protocall to use the same next function
[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     for (auto& entry : moduleProgramNode->varDeclarations()) {
893         ASSERT(!entry.value.isLet() && !entry.value.isConst());
894         if (!entry.value.isVar()) // This is either a parameter or callee.
895             continue;
896         // Imported bindings are not allocated in the module environment as usual variables' way.
897         // These references remain the "Dynamic" in the unlinked code block. Later, when linking
898         // the code block, we resolve the reference to the "ModuleVar".
899         if (entry.value.isImported() && !entry.value.isImportedNamespace())
900             continue;
901         createVariable(Identifier::fromUid(m_vm, entry.key.get()), lookUpVarKind(entry.key.get(), entry.value), moduleEnvironmentSymbolTable, IgnoreExisting);
902     }
903
904     VariableEnvironment& lexicalVariables = moduleProgramNode->lexicalVariables();
905     instantiateLexicalVariables(lexicalVariables, moduleEnvironmentSymbolTable, ScopeRegisterType::Block, lookUpVarKind);
906
907     // We keep the symbol table in the constant pool.
908     RegisterID* constantSymbolTable = nullptr;
909     if (vm.typeProfiler())
910         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable);
911     else
912         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable->cloneScopePart(*m_vm));
913
914     pushTDZVariables(lexicalVariables, TDZCheckOptimization::Optimize, TDZRequirement::UnderTDZ);
915     bool isWithScope = false;
916     m_lexicalScopeStack.append({ moduleEnvironmentSymbolTable, m_topMostScope, isWithScope, constantSymbolTable->index() });
917     emitPrefillStackTDZVariables(lexicalVariables, moduleEnvironmentSymbolTable);
918
919     // makeFunction assumes that there's correct TDZ stack entries.
920     // So it should be called after putting our lexical environment to the TDZ stack correctly.
921
922     for (FunctionMetadataNode* function : moduleProgramNode->functionStack()) {
923         const auto& iterator = moduleProgramNode->varDeclarations().find(function->ident().impl());
924         RELEASE_ASSERT(iterator != moduleProgramNode->varDeclarations().end());
925         RELEASE_ASSERT(!iterator->value.isImported());
926
927         VarKind varKind = lookUpVarKind(iterator->key.get(), iterator->value);
928         if (varKind == VarKind::Scope) {
929             // http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
930             // Section 15.2.1.16.4, step 16-a-iv-1.
931             // All heap allocated function declarations should be instantiated when the module environment
932             // is created. They include the exported function declarations and not-exported-but-heap-allocated
933             // function declarations. This is required because exported function should be instantiated before
934             // executing the any module in the dependency graph. This enables the modules to link the imported
935             // bindings before executing the any module code.
936             //
937             // And since function declarations are instantiated before executing the module body code, the spec
938             // allows the functions inside the module to be executed before its module body is executed under
939             // the circular dependencies. The following is the example.
940             //
941             // Module A (executed first):
942             //    import { b } from "B";
943             //    // Here, the module "B" is not executed yet, but the function declaration is already instantiated.
944             //    // So we can call the function exported from "B".
945             //    b();
946             //
947             //    export function a() {
948             //    }
949             //
950             // Module B (executed second):
951             //    import { a } from "A";
952             //
953             //    export function b() {
954             //        c();
955             //    }
956             //
957             //    // c is not exported, but since it is referenced from the b, we should instantiate it before
958             //    // executing the "B" module code.
959             //    function c() {
960             //        a();
961             //    }
962             //
963             // Module EntryPoint (executed last):
964             //    import "B";
965             //    import "A";
966             //
967             m_codeBlock->addFunctionDecl(makeFunction(function));
968         } else {
969             // Stack allocated functions can be allocated when executing the module's body.
970             m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
971         }
972     }
973
974     // Remember the constant register offset to the top-most symbol table. This symbol table will be
975     // cloned in the code block linking. After that, to create the module environment, we retrieve
976     // the cloned symbol table from the linked code block by using this offset.
977     codeBlock->setModuleEnvironmentSymbolTableConstantRegisterOffset(constantSymbolTable->index());
978 }
979
980 BytecodeGenerator::~BytecodeGenerator()
981 {
982 }
983
984 void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack(
985     FunctionParameters& parameters, bool isSimpleParameterList, FunctionNode* functionNode, SymbolTable* functionSymbolTable, 
986     int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope)
987 {
988     Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars;
989     ASSERT(!(isSimpleParameterList && shouldCreateArgumentsVariableInParameterScope));
990     if (!isSimpleParameterList) {
991         // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
992         // This implements step 21.
993         VariableEnvironment environment;
994         Vector<Identifier> allParameterNames; 
995         for (unsigned i = 0; i < parameters.size(); i++)
996             parameters.at(i).first->collectBoundIdentifiers(allParameterNames);
997         if (shouldCreateArgumentsVariableInParameterScope)
998             allParameterNames.append(propertyNames().arguments);
999         IdentifierSet parameterSet;
1000         for (auto& ident : allParameterNames) {
1001             parameterSet.add(ident.impl());
1002             auto addResult = environment.add(ident);
1003             addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables.
1004             if (captures(ident.impl()))
1005                 addResult.iterator->value.setIsCaptured();
1006         }
1007         // This implements step 25 of section 9.2.12.
1008         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1009
1010         if (shouldCreateArgumentsVariableInParameterScope) {
1011             Variable argumentsVariable = variable(propertyNames().arguments); 
1012             initializeVariable(argumentsVariable, m_argumentsRegister);
1013             liftTDZCheckIfPossible(argumentsVariable);
1014         }
1015
1016         RefPtr<RegisterID> temp = newTemporary();
1017         for (unsigned i = 0; i < parameters.size(); i++) {
1018             std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
1019             if (parameter.first->isRestParameter())
1020                 continue;
1021             if ((i + 1) < m_parameters.size())
1022                 emitMove(temp.get(), &m_parameters[i + 1]);
1023             else
1024                 emitGetArgument(temp.get(), i);
1025             if (parameter.second) {
1026                 RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), temp.get());
1027                 Ref<Label> skipDefaultParameterBecauseNotUndefined = newLabel();
1028                 emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get());
1029                 emitNode(temp.get(), parameter.second);
1030                 emitLabel(skipDefaultParameterBecauseNotUndefined.get());
1031             }
1032
1033             parameter.first->bindValue(*this, temp.get());
1034         }
1035
1036         // Final act of weirdness for default parameters. If a "var" also
1037         // has the same name as a parameter, it should start out as the
1038         // value of that parameter. Note, though, that they will be distinct
1039         // bindings.
1040         // This is step 28 of section 9.2.12. 
1041         for (auto& entry : functionNode->varDeclarations()) {
1042             if (!entry.value.isVar()) // This is either a parameter or callee.
1043                 continue;
1044
1045             if (parameterSet.contains(entry.key)) {
1046                 Identifier ident = Identifier::fromUid(m_vm, entry.key.get());
1047                 Variable var = variable(ident);
1048                 RegisterID* scope = emitResolveScope(nullptr, var);
1049                 RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound);
1050                 valuesToMoveIntoVars.append(std::make_pair(ident, value));
1051             }
1052         }
1053
1054         // Functions with default parameter expressions must have a separate environment
1055         // record for parameters and "var"s. The "var" environment record must have the
1056         // parameter environment record as its parent.
1057         // See step 28 of section 9.2.12.
1058         bool hasCapturedVariables = !!m_lexicalEnvironmentRegister; 
1059         initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, hasCapturedVariables);
1060     }
1061
1062     // This completes step 28 of section 9.2.12.
1063     for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) {
1064         ASSERT(!isSimpleParameterList);
1065         Variable var = variable(valuesToMoveIntoVars[i].first);
1066         RegisterID* scope = emitResolveScope(nullptr, var);
1067         emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
1068     }
1069 }
1070
1071 bool BytecodeGenerator::needsDerivedConstructorInArrowFunctionLexicalEnvironment()
1072 {
1073     ASSERT(m_codeBlock->isClassContext() || !(isConstructor() && constructorKind() == ConstructorKind::Extends));
1074     return m_codeBlock->isClassContext() && isSuperUsedInInnerArrowFunction();
1075 }
1076
1077 void BytecodeGenerator::initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable, bool canReuseLexicalEnvironment)
1078 {
1079     ASSERT(!m_arrowFunctionContextLexicalEnvironmentRegister);
1080
1081     if (canReuseLexicalEnvironment && m_lexicalEnvironmentRegister) {
1082         RELEASE_ASSERT(!m_codeBlock->isArrowFunction());
1083         RELEASE_ASSERT(functionSymbolTable);
1084
1085         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalEnvironmentRegister;
1086         
1087         ScopeOffset offset;
1088         
1089         if (isThisUsedInInnerArrowFunction()) {
1090             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1091             functionSymbolTable->set(NoLockingNecessary, propertyNames().thisIdentifier.impl(), SymbolTableEntry(VarOffset(offset)));
1092         }
1093
1094         if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1095             offset = functionSymbolTable->takeNextScopeOffset();
1096             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().newTargetLocalPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1097         }
1098         
1099         if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1100             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1101             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().derivedConstructorPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1102         }
1103
1104         return;
1105     }
1106
1107     VariableEnvironment environment;
1108
1109     if (isThisUsedInInnerArrowFunction()) {
1110         auto addResult = environment.add(propertyNames().thisIdentifier);
1111         addResult.iterator->value.setIsCaptured();
1112         addResult.iterator->value.setIsLet();
1113     }
1114     
1115     if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1116         auto addTarget = environment.add(propertyNames().builtinNames().newTargetLocalPrivateName());
1117         addTarget.iterator->value.setIsCaptured();
1118         addTarget.iterator->value.setIsLet();
1119     }
1120
1121     if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1122         auto derivedConstructor = environment.add(propertyNames().builtinNames().derivedConstructorPrivateName());
1123         derivedConstructor.iterator->value.setIsCaptured();
1124         derivedConstructor.iterator->value.setIsLet();
1125     }
1126
1127     if (environment.size() > 0) {
1128         size_t size = m_lexicalScopeStack.size();
1129         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1130
1131         ASSERT_UNUSED(size, m_lexicalScopeStack.size() == size + 1);
1132
1133         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalScopeStack.last().m_scope;
1134     }
1135 }
1136
1137 RegisterID* BytecodeGenerator::initializeNextParameter()
1138 {
1139     VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
1140     m_parameters.grow(m_parameters.size() + 1);
1141     auto& parameter = registerFor(reg);
1142     parameter.setIndex(reg.offset());
1143     m_codeBlock->addParameter();
1144     return &parameter;
1145 }
1146
1147 void BytecodeGenerator::initializeParameters(FunctionParameters& parameters)
1148 {
1149     // Make sure the code block knows about all of our parameters, and make sure that parameters
1150     // needing destructuring are noted.
1151     m_thisRegister.setIndex(initializeNextParameter()->index()); // this
1152
1153     bool nonSimpleArguments = false;
1154     for (unsigned i = 0; i < parameters.size(); ++i) {
1155         auto parameter = parameters.at(i);
1156         auto pattern = parameter.first;
1157         if (pattern->isRestParameter()) {
1158             RELEASE_ASSERT(!m_restParameter);
1159             m_restParameter = static_cast<RestParameterNode*>(pattern);
1160             nonSimpleArguments = true;
1161             continue;
1162         }
1163         if (parameter.second) {
1164             nonSimpleArguments = true;
1165             continue;
1166         }
1167         if (!nonSimpleArguments)
1168             initializeNextParameter();
1169     }
1170 }
1171
1172 void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables)
1173 {
1174     if (hasCapturedVariables) {
1175         RELEASE_ASSERT(m_lexicalEnvironmentRegister);
1176         emitOpcode(op_create_lexical_environment);
1177         instructions().append(m_lexicalEnvironmentRegister->index());
1178         instructions().append(scopeRegister()->index());
1179         instructions().append(symbolTableConstantIndex);
1180         instructions().append(addConstantValue(jsUndefined())->index());
1181
1182         emitOpcode(op_mov);
1183         instructions().append(scopeRegister()->index());
1184         instructions().append(m_lexicalEnvironmentRegister->index());
1185
1186         pushLocalControlFlowScope();
1187     }
1188     bool isWithScope = false;
1189     m_lexicalScopeStack.append({ functionSymbolTable, m_lexicalEnvironmentRegister, isWithScope, symbolTableConstantIndex });
1190     m_varScopeLexicalScopeStackIndex = m_lexicalScopeStack.size() - 1;
1191 }
1192
1193 UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern)
1194 {
1195     if (pattern->isBindingNode()) {
1196         const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
1197         if (!m_functions.contains(ident.impl()))
1198             return ident.impl();
1199     }
1200     return nullptr;
1201 }
1202
1203 RegisterID* BytecodeGenerator::newRegister()
1204 {
1205     m_calleeLocals.append(virtualRegisterForLocal(m_calleeLocals.size()));
1206     int numCalleeLocals = max<int>(m_codeBlock->m_numCalleeLocals, m_calleeLocals.size());
1207     numCalleeLocals = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeLocals);
1208     m_codeBlock->m_numCalleeLocals = numCalleeLocals;
1209     return &m_calleeLocals.last();
1210 }
1211
1212 void BytecodeGenerator::reclaimFreeRegisters()
1213 {
1214     shrinkToFit(m_calleeLocals);
1215 }
1216
1217 RegisterID* BytecodeGenerator::newBlockScopeVariable()
1218 {
1219     reclaimFreeRegisters();
1220
1221     return newRegister();
1222 }
1223
1224 RegisterID* BytecodeGenerator::newTemporary()
1225 {
1226     reclaimFreeRegisters();
1227
1228     RegisterID* result = newRegister();
1229     result->setTemporary();
1230     return result;
1231 }
1232
1233 Ref<LabelScope> BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
1234 {
1235     shrinkToFit(m_labelScopes);
1236
1237     // Allocate new label scope.
1238     m_labelScopes.append(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? RefPtr<Label>(newLabel()) : RefPtr<Label>()); // Only loops have continue targets.
1239     return m_labelScopes.last();
1240 }
1241
1242 Ref<Label> BytecodeGenerator::newLabel()
1243 {
1244     shrinkToFit(m_labels);
1245
1246     // Allocate new label ID.
1247     m_labels.append();
1248     return m_labels.last();
1249 }
1250
1251 Ref<Label> BytecodeGenerator::newEmittedLabel()
1252 {
1253     Ref<Label> label = newLabel();
1254     emitLabel(label.get());
1255     return label;
1256 }
1257
1258 void BytecodeGenerator::emitLabel(Label& l0)
1259 {
1260     unsigned newLabelIndex = instructions().size();
1261     l0.setLocation(*this, newLabelIndex);
1262
1263     if (m_codeBlock->numberOfJumpTargets()) {
1264         unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
1265         ASSERT(lastLabelIndex <= newLabelIndex);
1266         if (newLabelIndex == lastLabelIndex) {
1267             // Peephole optimizations have already been disabled by emitting the last label
1268             return;
1269         }
1270     }
1271
1272     m_codeBlock->addJumpTarget(newLabelIndex);
1273
1274     // This disables peephole optimizations when an instruction is a jump target
1275     m_lastOpcodeID = op_end;
1276 }
1277
1278 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
1279 {
1280 #ifndef NDEBUG
1281     size_t opcodePosition = instructions().size();
1282     ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
1283     m_lastOpcodePosition = opcodePosition;
1284 #endif
1285     instructions().append(opcodeID);
1286     m_lastOpcodeID = opcodeID;
1287 }
1288
1289 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
1290 {
1291     return m_codeBlock->addArrayProfile();
1292 }
1293
1294 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
1295 {
1296     return m_codeBlock->addArrayAllocationProfile();
1297 }
1298
1299 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
1300 {
1301     return m_codeBlock->addObjectAllocationProfile();
1302 }
1303
1304 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
1305 {
1306     UnlinkedValueProfile result = m_codeBlock->addValueProfile();
1307     emitOpcode(opcodeID);
1308     return result;
1309 }
1310
1311 void BytecodeGenerator::emitEnter()
1312 {
1313     emitOpcode(op_enter);
1314 }
1315
1316 void BytecodeGenerator::emitLoopHint()
1317 {
1318     emitOpcode(op_loop_hint);
1319     emitCheckTraps();
1320 }
1321
1322 void BytecodeGenerator::emitCheckTraps()
1323 {
1324     emitOpcode(op_check_traps);
1325 }
1326
1327 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
1328 {
1329     ASSERT(instructions().size() >= 4);
1330     size_t size = instructions().size();
1331     dstIndex = instructions().at(size - 3).u.operand;
1332     src1Index = instructions().at(size - 2).u.operand;
1333     src2Index = instructions().at(size - 1).u.operand;
1334 }
1335
1336 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
1337 {
1338     ASSERT(instructions().size() >= 3);
1339     size_t size = instructions().size();
1340     dstIndex = instructions().at(size - 2).u.operand;
1341     srcIndex = instructions().at(size - 1).u.operand;
1342 }
1343
1344 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
1345 {
1346     ASSERT(instructions().size() >= 4);
1347     instructions().shrink(instructions().size() - 4);
1348     m_lastOpcodeID = op_end;
1349 }
1350
1351 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
1352 {
1353     ASSERT(instructions().size() >= 3);
1354     instructions().shrink(instructions().size() - 3);
1355     m_lastOpcodeID = op_end;
1356 }
1357
1358 void BytecodeGenerator::emitJump(Label& target)
1359 {
1360     size_t begin = instructions().size();
1361     emitOpcode(op_jmp);
1362     instructions().append(target.bind(begin, instructions().size()));
1363 }
1364
1365 void BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label& target)
1366 {
1367     if (m_lastOpcodeID == op_less) {
1368         int dstIndex;
1369         int src1Index;
1370         int src2Index;
1371
1372         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1373
1374         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1375             rewindBinaryOp();
1376
1377             size_t begin = instructions().size();
1378             emitOpcode(op_jless);
1379             instructions().append(src1Index);
1380             instructions().append(src2Index);
1381             instructions().append(target.bind(begin, instructions().size()));
1382             return;
1383         }
1384     } else if (m_lastOpcodeID == op_lesseq) {
1385         int dstIndex;
1386         int src1Index;
1387         int src2Index;
1388
1389         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1390
1391         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1392             rewindBinaryOp();
1393
1394             size_t begin = instructions().size();
1395             emitOpcode(op_jlesseq);
1396             instructions().append(src1Index);
1397             instructions().append(src2Index);
1398             instructions().append(target.bind(begin, instructions().size()));
1399             return;
1400         }
1401     } else if (m_lastOpcodeID == op_greater) {
1402         int dstIndex;
1403         int src1Index;
1404         int src2Index;
1405
1406         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1407
1408         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1409             rewindBinaryOp();
1410
1411             size_t begin = instructions().size();
1412             emitOpcode(op_jgreater);
1413             instructions().append(src1Index);
1414             instructions().append(src2Index);
1415             instructions().append(target.bind(begin, instructions().size()));
1416             return;
1417         }
1418     } else if (m_lastOpcodeID == op_greatereq) {
1419         int dstIndex;
1420         int src1Index;
1421         int src2Index;
1422
1423         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1424
1425         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1426             rewindBinaryOp();
1427
1428             size_t begin = instructions().size();
1429             emitOpcode(op_jgreatereq);
1430             instructions().append(src1Index);
1431             instructions().append(src2Index);
1432             instructions().append(target.bind(begin, instructions().size()));
1433             return;
1434         }
1435     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1436         int dstIndex;
1437         int srcIndex;
1438
1439         retrieveLastUnaryOp(dstIndex, srcIndex);
1440
1441         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1442             rewindUnaryOp();
1443
1444             size_t begin = instructions().size();
1445             emitOpcode(op_jeq_null);
1446             instructions().append(srcIndex);
1447             instructions().append(target.bind(begin, instructions().size()));
1448             return;
1449         }
1450     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1451         int dstIndex;
1452         int srcIndex;
1453
1454         retrieveLastUnaryOp(dstIndex, srcIndex);
1455
1456         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1457             rewindUnaryOp();
1458
1459             size_t begin = instructions().size();
1460             emitOpcode(op_jneq_null);
1461             instructions().append(srcIndex);
1462             instructions().append(target.bind(begin, instructions().size()));
1463             return;
1464         }
1465     }
1466
1467     size_t begin = instructions().size();
1468
1469     emitOpcode(op_jtrue);
1470     instructions().append(cond->index());
1471     instructions().append(target.bind(begin, instructions().size()));
1472 }
1473
1474 void BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label& target)
1475 {
1476     if (m_lastOpcodeID == op_less && target.isForward()) {
1477         int dstIndex;
1478         int src1Index;
1479         int src2Index;
1480
1481         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1482
1483         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1484             rewindBinaryOp();
1485
1486             size_t begin = instructions().size();
1487             emitOpcode(op_jnless);
1488             instructions().append(src1Index);
1489             instructions().append(src2Index);
1490             instructions().append(target.bind(begin, instructions().size()));
1491             return;
1492         }
1493     } else if (m_lastOpcodeID == op_lesseq && target.isForward()) {
1494         int dstIndex;
1495         int src1Index;
1496         int src2Index;
1497
1498         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1499
1500         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1501             rewindBinaryOp();
1502
1503             size_t begin = instructions().size();
1504             emitOpcode(op_jnlesseq);
1505             instructions().append(src1Index);
1506             instructions().append(src2Index);
1507             instructions().append(target.bind(begin, instructions().size()));
1508             return;
1509         }
1510     } else if (m_lastOpcodeID == op_greater && target.isForward()) {
1511         int dstIndex;
1512         int src1Index;
1513         int src2Index;
1514
1515         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1516
1517         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1518             rewindBinaryOp();
1519
1520             size_t begin = instructions().size();
1521             emitOpcode(op_jngreater);
1522             instructions().append(src1Index);
1523             instructions().append(src2Index);
1524             instructions().append(target.bind(begin, instructions().size()));
1525             return;
1526         }
1527     } else if (m_lastOpcodeID == op_greatereq && target.isForward()) {
1528         int dstIndex;
1529         int src1Index;
1530         int src2Index;
1531
1532         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1533
1534         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1535             rewindBinaryOp();
1536
1537             size_t begin = instructions().size();
1538             emitOpcode(op_jngreatereq);
1539             instructions().append(src1Index);
1540             instructions().append(src2Index);
1541             instructions().append(target.bind(begin, instructions().size()));
1542             return;
1543         }
1544     } else if (m_lastOpcodeID == op_not) {
1545         int dstIndex;
1546         int srcIndex;
1547
1548         retrieveLastUnaryOp(dstIndex, srcIndex);
1549
1550         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1551             rewindUnaryOp();
1552
1553             size_t begin = instructions().size();
1554             emitOpcode(op_jtrue);
1555             instructions().append(srcIndex);
1556             instructions().append(target.bind(begin, instructions().size()));
1557             return;
1558         }
1559     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1560         int dstIndex;
1561         int srcIndex;
1562
1563         retrieveLastUnaryOp(dstIndex, srcIndex);
1564
1565         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1566             rewindUnaryOp();
1567
1568             size_t begin = instructions().size();
1569             emitOpcode(op_jneq_null);
1570             instructions().append(srcIndex);
1571             instructions().append(target.bind(begin, instructions().size()));
1572             return;
1573         }
1574     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1575         int dstIndex;
1576         int srcIndex;
1577
1578         retrieveLastUnaryOp(dstIndex, srcIndex);
1579
1580         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1581             rewindUnaryOp();
1582
1583             size_t begin = instructions().size();
1584             emitOpcode(op_jeq_null);
1585             instructions().append(srcIndex);
1586             instructions().append(target.bind(begin, instructions().size()));
1587             return;
1588         }
1589     }
1590
1591     size_t begin = instructions().size();
1592     emitOpcode(op_jfalse);
1593     instructions().append(cond->index());
1594     instructions().append(target.bind(begin, instructions().size()));
1595 }
1596
1597 void BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label& target)
1598 {
1599     size_t begin = instructions().size();
1600
1601     emitOpcode(op_jneq_ptr);
1602     instructions().append(cond->index());
1603     instructions().append(Special::CallFunction);
1604     instructions().append(target.bind(begin, instructions().size()));
1605     instructions().append(0);
1606 }
1607
1608 void BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label& target)
1609 {
1610     size_t begin = instructions().size();
1611
1612     emitOpcode(op_jneq_ptr);
1613     instructions().append(cond->index());
1614     instructions().append(Special::ApplyFunction);
1615     instructions().append(target.bind(begin, instructions().size()));
1616     instructions().append(0);
1617 }
1618
1619 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
1620 {
1621     UniquedStringImpl* rep = ident.impl();
1622     return m_identifierMap.contains(rep);
1623 }
1624
1625 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
1626 {
1627     UniquedStringImpl* rep = ident.impl();
1628     IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
1629     if (result.isNewEntry)
1630         m_codeBlock->addIdentifier(ident);
1631
1632     return result.iterator->value;
1633 }
1634
1635 // We can't hash JSValue(), so we use a dedicated data member to cache it.
1636 RegisterID* BytecodeGenerator::addConstantEmptyValue()
1637 {
1638     if (!m_emptyValueRegister) {
1639         int index = addConstantIndex();
1640         m_codeBlock->addConstant(JSValue());
1641         m_emptyValueRegister = &m_constantPoolRegisters[index];
1642     }
1643
1644     return m_emptyValueRegister;
1645 }
1646
1647 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1648 {
1649     if (!v)
1650         return addConstantEmptyValue();
1651
1652     int index = m_nextConstantOffset;
1653
1654     if (sourceCodeRepresentation == SourceCodeRepresentation::Double && v.isInt32())
1655         v = jsDoubleNumber(v.asNumber());
1656     EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
1657     JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
1658     if (result.isNewEntry) {
1659         addConstantIndex();
1660         m_codeBlock->addConstant(v, sourceCodeRepresentation);
1661     } else
1662         index = result.iterator->value;
1663     return &m_constantPoolRegisters[index];
1664 }
1665
1666 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1667 {
1668     unsigned constantIndex = static_cast<unsigned>(type);
1669     if (!m_linkTimeConstantRegisters[constantIndex]) {
1670         int index = addConstantIndex();
1671         m_codeBlock->addConstant(type);
1672         m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1673     }
1674
1675     if (!dst)
1676         return m_linkTimeConstantRegisters[constantIndex];
1677
1678     emitOpcode(op_mov);
1679     instructions().append(dst->index());
1680     instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1681
1682     return dst;
1683 }
1684
1685 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1686 {
1687     return m_codeBlock->addRegExp(r);
1688 }
1689
1690 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1691 {
1692     RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1693
1694     emitOpcode(op_mov);
1695     instructions().append(dst->index());
1696     instructions().append(emptyValue->index());
1697     return dst;
1698 }
1699
1700 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1701 {
1702     ASSERT(src != m_emptyValueRegister);
1703
1704     m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1705     emitOpcode(op_mov);
1706     instructions().append(dst->index());
1707     instructions().append(src->index());
1708
1709     return dst;
1710 }
1711
1712 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1713 {
1714     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1715     ASSERT_WITH_MESSAGE(op_negate != opcodeID, "op_negate has an Arith Profile.");
1716     emitOpcode(opcodeID);
1717     instructions().append(dst->index());
1718     instructions().append(src->index());
1719
1720     return dst;
1721 }
1722
1723 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src, OperandTypes types)
1724 {
1725     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1726     emitOpcode(opcodeID);
1727     instructions().append(dst->index());
1728     instructions().append(src->index());
1729
1730     if (opcodeID == op_negate)
1731         instructions().append(ArithProfile(types.first()).bits());
1732     return dst;
1733 }
1734
1735 RegisterID* BytecodeGenerator::emitUnaryOpProfiled(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1736 {
1737     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
1738     instructions().append(dst->index());
1739     instructions().append(src->index());
1740     instructions().append(profile);
1741     return dst;
1742 }
1743
1744 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1745 {
1746     emitOpcode(op_inc);
1747     instructions().append(srcDst->index());
1748     return srcDst;
1749 }
1750
1751 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1752 {
1753     emitOpcode(op_dec);
1754     instructions().append(srcDst->index());
1755     return srcDst;
1756 }
1757
1758 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1759 {
1760     emitOpcode(opcodeID);
1761     instructions().append(dst->index());
1762     instructions().append(src1->index());
1763     instructions().append(src2->index());
1764
1765     if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1766         opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1767         instructions().append(ArithProfile(types.first(), types.second()).bits());
1768
1769     return dst;
1770 }
1771
1772 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1773 {
1774     if (m_lastOpcodeID == op_typeof) {
1775         int dstIndex;
1776         int srcIndex;
1777
1778         retrieveLastUnaryOp(dstIndex, srcIndex);
1779
1780         if (src1->index() == dstIndex
1781             && src1->isTemporary()
1782             && m_codeBlock->isConstantRegisterIndex(src2->index())
1783             && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1784             const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1785             if (value == "undefined") {
1786                 rewindUnaryOp();
1787                 emitOpcode(op_is_undefined);
1788                 instructions().append(dst->index());
1789                 instructions().append(srcIndex);
1790                 return dst;
1791             }
1792             if (value == "boolean") {
1793                 rewindUnaryOp();
1794                 emitOpcode(op_is_boolean);
1795                 instructions().append(dst->index());
1796                 instructions().append(srcIndex);
1797                 return dst;
1798             }
1799             if (value == "number") {
1800                 rewindUnaryOp();
1801                 emitOpcode(op_is_number);
1802                 instructions().append(dst->index());
1803                 instructions().append(srcIndex);
1804                 return dst;
1805             }
1806             if (value == "string") {
1807                 rewindUnaryOp();
1808                 emitOpcode(op_is_cell_with_type);
1809                 instructions().append(dst->index());
1810                 instructions().append(srcIndex);
1811                 instructions().append(StringType);
1812                 return dst;
1813             }
1814             if (value == "symbol") {
1815                 rewindUnaryOp();
1816                 emitOpcode(op_is_cell_with_type);
1817                 instructions().append(dst->index());
1818                 instructions().append(srcIndex);
1819                 instructions().append(SymbolType);
1820                 return dst;
1821             }
1822             if (value == "object") {
1823                 rewindUnaryOp();
1824                 emitOpcode(op_is_object_or_null);
1825                 instructions().append(dst->index());
1826                 instructions().append(srcIndex);
1827                 return dst;
1828             }
1829             if (value == "function") {
1830                 rewindUnaryOp();
1831                 emitOpcode(op_is_function);
1832                 instructions().append(dst->index());
1833                 instructions().append(srcIndex);
1834                 return dst;
1835             }
1836         }
1837     }
1838
1839     emitOpcode(opcodeID);
1840     instructions().append(dst->index());
1841     instructions().append(src1->index());
1842     instructions().append(src2->index());
1843     return dst;
1844 }
1845
1846 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1847 {
1848     ASSERT(vm()->typeProfiler());
1849
1850     unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1851     unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1852     unsigned instructionOffset = instructions().size() - 1;
1853     m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1854 }
1855
1856 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag)
1857 {
1858     if (!vm()->typeProfiler())
1859         return;
1860
1861     if (!registerToProfile)
1862         return;
1863
1864     emitOpcode(op_profile_type);
1865     instructions().append(registerToProfile->index());
1866     instructions().append(0);
1867     instructions().append(flag);
1868     instructions().append(0);
1869     instructions().append(resolveType());
1870
1871     // Don't emit expression info for this version of profile type. This generally means
1872     // we're profiling information for something that isn't in the actual text of a JavaScript
1873     // program. For example, implicit return undefined from a function call.
1874 }
1875
1876 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1877 {
1878     emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot);
1879 }
1880
1881 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1882 {
1883     if (!vm()->typeProfiler())
1884         return;
1885
1886     if (!registerToProfile)
1887         return;
1888
1889     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1890     emitOpcode(op_profile_type);
1891     instructions().append(registerToProfile->index());
1892     instructions().append(0);
1893     instructions().append(flag);
1894     instructions().append(0);
1895     instructions().append(resolveType());
1896
1897     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1898 }
1899
1900 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1901 {
1902     if (!vm()->typeProfiler())
1903         return;
1904
1905     if (!registerToProfile)
1906         return;
1907
1908     ProfileTypeBytecodeFlag flag;
1909     int symbolTableOrScopeDepth;
1910     if (var.local() || var.offset().isScope()) {
1911         flag = ProfileTypeBytecodeLocallyResolved;
1912         ASSERT(var.symbolTableConstantIndex());
1913         symbolTableOrScopeDepth = var.symbolTableConstantIndex();
1914     } else {
1915         flag = ProfileTypeBytecodeClosureVar;
1916         symbolTableOrScopeDepth = localScopeDepth();
1917     }
1918
1919     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1920     emitOpcode(op_profile_type);
1921     instructions().append(registerToProfile->index());
1922     instructions().append(symbolTableOrScopeDepth);
1923     instructions().append(flag);
1924     instructions().append(addConstant(var.ident()));
1925     instructions().append(resolveType());
1926
1927     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1928 }
1929
1930 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1931 {
1932     if (vm()->controlFlowProfiler()) {
1933         RELEASE_ASSERT(textOffset >= 0);
1934         size_t bytecodeOffset = instructions().size();
1935         m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1936
1937         emitOpcode(op_profile_control_flow);
1938         instructions().append(textOffset);
1939     }
1940 }
1941
1942 unsigned BytecodeGenerator::addConstantIndex()
1943 {
1944     unsigned index = m_nextConstantOffset;
1945     m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1946     ++m_nextConstantOffset;
1947     return index;
1948 }
1949
1950 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1951 {
1952     return emitLoad(dst, jsBoolean(b));
1953 }
1954
1955 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1956 {
1957     ASSERT(!identifier.isSymbol());
1958     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1959     if (!stringInMap)
1960         stringInMap = jsOwnedString(vm(), identifier.string());
1961
1962     return emitLoad(dst, JSValue(stringInMap));
1963 }
1964
1965 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1966 {
1967     RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1968     if (dst)
1969         return emitMove(dst, constantID);
1970     return constantID;
1971 }
1972
1973 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, IdentifierSet& set)
1974 {
1975     for (const auto& entry : m_codeBlock->constantIdentifierSets()) {
1976         if (entry.first != set)
1977             continue;
1978         
1979         return &m_constantPoolRegisters[entry.second];
1980     }
1981     
1982     unsigned index = addConstantIndex();
1983     m_codeBlock->addSetConstant(set);
1984     RegisterID* m_setRegister = &m_constantPoolRegisters[index];
1985     
1986     if (dst)
1987         return emitMove(dst, m_setRegister);
1988     
1989     return m_setRegister;
1990 }
1991
1992 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1993 {
1994     if (!m_globalObjectRegister) {
1995         int index = addConstantIndex();
1996         m_codeBlock->addConstant(JSValue());
1997         m_globalObjectRegister = &m_constantPoolRegisters[index];
1998         m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1999     }
2000     if (dst)
2001         emitMove(dst, m_globalObjectRegister);
2002     return m_globalObjectRegister;
2003 }
2004
2005 template<typename LookUpVarKindFunctor>
2006 bool BytecodeGenerator::instantiateLexicalVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable, ScopeRegisterType scopeRegisterType, LookUpVarKindFunctor lookUpVarKind)
2007 {
2008     bool hasCapturedVariables = false;
2009     {
2010         for (auto& entry : lexicalVariables) {
2011             ASSERT(entry.value.isLet() || entry.value.isConst() || entry.value.isFunction());
2012             ASSERT(!entry.value.isVar());
2013             SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2014             ASSERT(symbolTableEntry.isNull());
2015
2016             // Imported bindings which are not the namespace bindings are not allocated
2017             // in the module environment as usual variables' way.
2018             // And since these types of the variables only seen in the module environment,
2019             // other lexical environment need not to take care this.
2020             if (entry.value.isImported() && !entry.value.isImportedNamespace())
2021                 continue;
2022
2023             VarKind varKind = lookUpVarKind(entry.key.get(), entry.value);
2024             VarOffset varOffset;
2025             if (varKind == VarKind::Scope) {
2026                 varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
2027                 hasCapturedVariables = true;
2028             } else {
2029                 ASSERT(varKind == VarKind::Stack);
2030                 RegisterID* local;
2031                 if (scopeRegisterType == ScopeRegisterType::Block) {
2032                     local = newBlockScopeVariable();
2033                     local->ref();
2034                 } else
2035                     local = addVar();
2036                 varOffset = VarOffset(local->virtualRegister());
2037             }
2038
2039             SymbolTableEntry newEntry(varOffset, entry.value.isConst() ? ReadOnly : None);
2040             symbolTable->add(NoLockingNecessary, entry.key.get(), newEntry);
2041         }
2042     }
2043     return hasCapturedVariables;
2044 }
2045
2046 void BytecodeGenerator::emitPrefillStackTDZVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable)
2047 {
2048     // Prefill stack variables with the TDZ empty value.
2049     // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated.
2050     for (auto& entry : lexicalVariables) {
2051         // Imported bindings which are not the namespace bindings are not allocated
2052         // in the module environment as usual variables' way.
2053         // And since these types of the variables only seen in the module environment,
2054         // other lexical environment need not to take care this.
2055         if (entry.value.isImported() && !entry.value.isImportedNamespace())
2056             continue;
2057
2058         if (entry.value.isFunction())
2059             continue;
2060
2061         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2062         ASSERT(!symbolTableEntry.isNull());
2063         VarOffset offset = symbolTableEntry.varOffset();
2064         if (offset.isScope())
2065             continue;
2066
2067         ASSERT(offset.isStack());
2068         emitMoveEmptyValue(&registerFor(offset.stackOffset()));
2069     }
2070 }
2071
2072 void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType, RegisterID** constantSymbolTableResult, bool shouldInitializeBlockScopedFunctions)
2073 {
2074     VariableEnvironment& environment = node->lexicalVariables();
2075     RegisterID* constantSymbolTableResultTemp = nullptr;
2076     pushLexicalScopeInternal(environment, tdzCheckOptimization, nestedScopeType, &constantSymbolTableResultTemp, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
2077
2078     if (shouldInitializeBlockScopedFunctions)
2079         initializeBlockScopedFunctions(environment, node->functionStack(), constantSymbolTableResultTemp);
2080
2081     if (constantSymbolTableResult && constantSymbolTableResultTemp)
2082         *constantSymbolTableResult = constantSymbolTableResultTemp;
2083 }
2084
2085 void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType,
2086     RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType)
2087 {
2088     if (!environment.size())
2089         return;
2090
2091     if (m_shouldEmitDebugHooks)
2092         environment.markAllVariablesAsCaptured();
2093
2094     SymbolTable* symbolTable = SymbolTable::create(*m_vm);
2095     switch (scopeType) {
2096     case ScopeType::CatchScope:
2097         symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope);
2098         break;
2099     case ScopeType::LetConstScope:
2100         symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
2101         break;
2102     case ScopeType::FunctionNameScope:
2103         symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope);
2104         break;
2105     }
2106
2107     if (nestedScopeType == NestedScopeType::IsNested)
2108         symbolTable->markIsNestedLexicalScope();
2109
2110     auto lookUpVarKind = [] (UniquedStringImpl*, const VariableEnvironmentEntry& entry) -> VarKind {
2111         return entry.isCaptured() ? VarKind::Scope : VarKind::Stack;
2112     };
2113
2114     bool hasCapturedVariables = instantiateLexicalVariables(environment, symbolTable, scopeRegisterType, lookUpVarKind);
2115
2116     RegisterID* newScope = nullptr;
2117     RegisterID* constantSymbolTable = nullptr;
2118     int symbolTableConstantIndex = 0;
2119     if (vm()->typeProfiler()) {
2120         constantSymbolTable = addConstantValue(symbolTable);
2121         symbolTableConstantIndex = constantSymbolTable->index();
2122     }
2123     if (hasCapturedVariables) {
2124         if (scopeRegisterType == ScopeRegisterType::Block) {
2125             newScope = newBlockScopeVariable();
2126             newScope->ref();
2127         } else
2128             newScope = addVar();
2129         if (!constantSymbolTable) {
2130             ASSERT(!vm()->typeProfiler());
2131             constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm));
2132             symbolTableConstantIndex = constantSymbolTable->index();
2133         }
2134         if (constantSymbolTableResult)
2135             *constantSymbolTableResult = constantSymbolTable;
2136
2137         emitOpcode(op_create_lexical_environment);
2138         instructions().append(newScope->index());
2139         instructions().append(scopeRegister()->index());
2140         instructions().append(constantSymbolTable->index());
2141         instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index());
2142
2143         emitMove(scopeRegister(), newScope);
2144
2145         pushLocalControlFlowScope();
2146     }
2147
2148     bool isWithScope = false;
2149     m_lexicalScopeStack.append({ symbolTable, newScope, isWithScope, symbolTableConstantIndex });
2150     pushTDZVariables(environment, tdzCheckOptimization, tdzRequirement);
2151
2152     if (tdzRequirement == TDZRequirement::UnderTDZ)
2153         emitPrefillStackTDZVariables(environment, symbolTable);
2154 }
2155
2156 void BytecodeGenerator::initializeBlockScopedFunctions(VariableEnvironment& environment, FunctionStack& functionStack, RegisterID* constantSymbolTable)
2157 {
2158     /*
2159      * We must transform block scoped function declarations in strict mode like so:
2160      *
2161      * function foo() {
2162      *     if (c) {
2163      *           function foo() { ... }
2164      *           if (bar) { ... }
2165      *           else { ... }
2166      *           function baz() { ... }
2167      *     }
2168      * }
2169      *
2170      * to:
2171      *
2172      * function foo() {
2173      *     if (c) {
2174      *         let foo = function foo() { ... }
2175      *         let baz = function baz() { ... }
2176      *         if (bar) { ... }
2177      *         else { ... }
2178      *     }
2179      * }
2180      * 
2181      * But without the TDZ checks.
2182     */
2183
2184     if (!environment.size()) {
2185         RELEASE_ASSERT(!functionStack.size());
2186         return;
2187     }
2188
2189     if (!functionStack.size())
2190         return;
2191
2192     SymbolTable* symbolTable = m_lexicalScopeStack.last().m_symbolTable;
2193     RegisterID* scope = m_lexicalScopeStack.last().m_scope;
2194     RefPtr<RegisterID> temp = newTemporary();
2195     int symbolTableIndex = constantSymbolTable ? constantSymbolTable->index() : 0;
2196     for (FunctionMetadataNode* function : functionStack) {
2197         const Identifier& name = function->ident();
2198         auto iter = environment.find(name.impl());
2199         RELEASE_ASSERT(iter != environment.end());
2200         RELEASE_ASSERT(iter->value.isFunction());
2201         // We purposefully don't hold the symbol table lock around this loop because emitNewFunctionExpressionCommon may GC.
2202         SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, name.impl()); 
2203         RELEASE_ASSERT(!entry.isNull());
2204         emitNewFunctionExpressionCommon(temp.get(), function);
2205         bool isLexicallyScoped = true;
2206         emitPutToScope(scope, variableForLocalEntry(name, entry, symbolTableIndex, isLexicallyScoped), temp.get(), DoNotThrowIfNotFound, InitializationMode::Initialization);
2207     }
2208 }
2209
2210 void BytecodeGenerator::hoistSloppyModeFunctionIfNecessary(const Identifier& functionName)
2211 {
2212     if (m_scopeNode->hasSloppyModeHoistedFunction(functionName.impl())) {
2213         if (codeType() != EvalCode) {
2214             Variable currentFunctionVariable = variable(functionName);
2215             RefPtr<RegisterID> currentValue;
2216             if (RegisterID* local = currentFunctionVariable.local())
2217                 currentValue = local;
2218             else {
2219                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2220                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2221             }
2222
2223             ASSERT(m_varScopeLexicalScopeStackIndex);
2224             ASSERT(*m_varScopeLexicalScopeStackIndex < m_lexicalScopeStack.size());
2225             LexicalScopeStackEntry varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex];
2226             SymbolTable* varSymbolTable = varScope.m_symbolTable;
2227             ASSERT(varSymbolTable->scopeType() == SymbolTable::ScopeType::VarScope);
2228             SymbolTableEntry entry = varSymbolTable->get(NoLockingNecessary, functionName.impl());
2229             if (functionName == propertyNames().arguments && entry.isNull()) {
2230                 // "arguments" might be put in the parameter scope when we have a non-simple
2231                 // parameter list since "arguments" is visible to expressions inside the
2232                 // parameter evaluation list.
2233                 // e.g:
2234                 // function foo(x = arguments) { { function arguments() { } } }
2235                 RELEASE_ASSERT(*m_varScopeLexicalScopeStackIndex > 0);
2236                 varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex - 1];
2237                 SymbolTable* parameterSymbolTable = varScope.m_symbolTable;
2238                 entry = parameterSymbolTable->get(NoLockingNecessary, functionName.impl());
2239             }
2240             RELEASE_ASSERT(!entry.isNull());
2241             bool isLexicallyScoped = false;
2242             emitPutToScope(varScope.m_scope, variableForLocalEntry(functionName, entry, varScope.m_symbolTableConstantIndex, isLexicallyScoped), currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2243         } else {
2244             Variable currentFunctionVariable = variable(functionName);
2245             RefPtr<RegisterID> currentValue;
2246             if (RegisterID* local = currentFunctionVariable.local())
2247                 currentValue = local;
2248             else {
2249                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2250                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2251             }
2252
2253             RefPtr<RegisterID> scopeId = emitResolveScopeForHoistingFuncDeclInEval(nullptr, functionName);
2254             RefPtr<RegisterID> checkResult = emitIsUndefined(newTemporary(), scopeId.get());
2255             
2256             Ref<Label> isNotVarScopeLabel = newLabel();
2257             emitJumpIfTrue(checkResult.get(), isNotVarScopeLabel.get());
2258
2259             // Put to outer scope
2260             emitPutToScope(scopeId.get(), functionName, currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2261             emitLabel(isNotVarScopeLabel.get());
2262
2263         }
2264     }
2265 }
2266
2267 RegisterID* BytecodeGenerator::emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier& property)
2268 {
2269     ASSERT(m_codeType == EvalCode);
2270
2271     dst = finalDestination(dst);
2272     emitOpcode(op_resolve_scope_for_hoisting_func_decl_in_eval);
2273     instructions().append(kill(dst));
2274     instructions().append(m_topMostScope->index());
2275     instructions().append(addConstant(property));
2276     return dst;
2277 }
2278
2279 void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node)
2280 {
2281     VariableEnvironment& environment = node->lexicalVariables();
2282     popLexicalScopeInternal(environment);
2283 }
2284
2285 void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment)
2286 {
2287     // NOTE: This function only makes sense for scopes that aren't ScopeRegisterType::Var (only function name scope right now is ScopeRegisterType::Var).
2288     // This doesn't make sense for ScopeRegisterType::Var because we deref RegisterIDs here.
2289     if (!environment.size())
2290         return;
2291
2292     if (m_shouldEmitDebugHooks)
2293         environment.markAllVariablesAsCaptured();
2294
2295     auto stackEntry = m_lexicalScopeStack.takeLast();
2296     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2297     bool hasCapturedVariables = false;
2298     for (auto& entry : environment) {
2299         if (entry.value.isCaptured()) {
2300             hasCapturedVariables = true;
2301             continue;
2302         }
2303         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2304         ASSERT(!symbolTableEntry.isNull());
2305         VarOffset offset = symbolTableEntry.varOffset();
2306         ASSERT(offset.isStack());
2307         RegisterID* local = &registerFor(offset.stackOffset());
2308         local->deref();
2309     }
2310
2311     if (hasCapturedVariables) {
2312         RELEASE_ASSERT(stackEntry.m_scope);
2313         emitPopScope(scopeRegister(), stackEntry.m_scope);
2314         popLocalControlFlowScope();
2315         stackEntry.m_scope->deref();
2316     }
2317
2318     m_TDZStack.removeLast();
2319 }
2320
2321 void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable)
2322 {
2323     VariableEnvironment& environment = node->lexicalVariables();
2324     if (!environment.size())
2325         return;
2326     if (m_shouldEmitDebugHooks)
2327         environment.markAllVariablesAsCaptured();
2328     if (!environment.hasCapturedVariables())
2329         return;
2330
2331     RELEASE_ASSERT(loopSymbolTable);
2332
2333     // This function needs to do setup for a for loop's activation if any of
2334     // the for loop's lexically declared variables are captured (that is, variables
2335     // declared in the loop header, not the loop body). This function needs to
2336     // make a copy of the current activation and copy the values from the previous
2337     // activation into the new activation because each iteration of a for loop
2338     // gets a new activation.
2339
2340     auto stackEntry = m_lexicalScopeStack.last();
2341     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2342     RegisterID* loopScope = stackEntry.m_scope;
2343     ASSERT(symbolTable->scopeSize());
2344     ASSERT(loopScope);
2345     Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver;
2346
2347     {
2348         activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize());
2349
2350         for (auto end = symbolTable->end(NoLockingNecessary), ptr = symbolTable->begin(NoLockingNecessary); ptr != end; ++ptr) {
2351             if (!ptr->value.varOffset().isScope())
2352                 continue;
2353
2354             RefPtr<UniquedStringImpl> ident = ptr->key;
2355             Identifier identifier = Identifier::fromUid(m_vm, ident.get());
2356
2357             RegisterID* transitionValue = newBlockScopeVariable();
2358             transitionValue->ref();
2359             emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound);
2360             activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier));
2361         }
2362     }
2363
2364     // We need this dynamic behavior of the executing code to ensure
2365     // each loop iteration has a new activation object. (It's pretty ugly).
2366     // Also, this new activation needs to be assigned to the same register
2367     // as the previous scope because the loop body is compiled under
2368     // the assumption that the scope's register index is constant even
2369     // though the value in that register will change on each loop iteration.
2370     RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope);
2371     emitMove(scopeRegister(), parentScope.get());
2372
2373     emitOpcode(op_create_lexical_environment);
2374     instructions().append(loopScope->index());
2375     instructions().append(scopeRegister()->index());
2376     instructions().append(loopSymbolTable->index());
2377     instructions().append(addConstantValue(jsTDZValue())->index());
2378
2379     emitMove(scopeRegister(), loopScope);
2380
2381     {
2382         for (auto pair : activationValuesToCopyOver) {
2383             const Identifier& identifier = pair.second;
2384             SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, identifier.impl());
2385             RELEASE_ASSERT(!entry.isNull());
2386             RegisterID* transitionValue = pair.first;
2387             emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2388             transitionValue->deref();
2389         }
2390     }
2391 }
2392
2393 Variable BytecodeGenerator::variable(const Identifier& property, ThisResolutionType thisResolutionType)
2394 {
2395     if (property == propertyNames().thisIdentifier && thisResolutionType == ThisResolutionType::Local) {
2396         return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(),
2397             ReadOnly, Variable::SpecialVariable, 0, false);
2398     }
2399     
2400     // We can optimize lookups if the lexical variable is found before a "with" or "catch"
2401     // scope because we're guaranteed static resolution. If we have to pass through
2402     // a "with" or "catch" scope we loose this guarantee.
2403     // We can't optimize cases like this:
2404     // {
2405     //     let x = ...;
2406     //     with (o) {
2407     //         doSomethingWith(x);
2408     //     }
2409     // }
2410     // Because we can't gaurantee static resolution on x.
2411     // But, in this case, we are guaranteed static resolution:
2412     // {
2413     //     let x = ...;
2414     //     with (o) {
2415     //         let x = ...;
2416     //         doSomethingWith(x);
2417     //     }
2418     // }
2419     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2420         auto& stackEntry = m_lexicalScopeStack[i];
2421         if (stackEntry.m_isWithScope)
2422             return Variable(property);
2423         SymbolTable* symbolTable = stackEntry.m_symbolTable;
2424         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, property.impl());
2425         if (symbolTableEntry.isNull())
2426             continue;
2427         bool resultIsCallee = false;
2428         if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2429             if (m_usesNonStrictEval) {
2430                 // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name.
2431                 // We resort to dynamic lookup to answer this question.
2432                 Variable result = Variable(property);
2433                 return result;
2434             }
2435             resultIsCallee = true;
2436         }
2437         Variable result = variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope);
2438         if (resultIsCallee)
2439             result.setIsReadOnly();
2440         return result;
2441     }
2442     
2443     return Variable(property);
2444 }
2445
2446 Variable BytecodeGenerator::variableForLocalEntry(
2447     const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped)
2448 {
2449     VarOffset offset = entry.varOffset();
2450     
2451     RegisterID* local;
2452     if (offset.isStack())
2453         local = &registerFor(offset.stackOffset());
2454     else
2455         local = nullptr;
2456     
2457     return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped);
2458 }
2459
2460 void BytecodeGenerator::createVariable(
2461     const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode)
2462 {
2463     ASSERT(property != propertyNames().thisIdentifier);
2464     SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, property.impl());
2465     
2466     if (!entry.isNull()) {
2467         if (existingVariableMode == IgnoreExisting)
2468             return;
2469         
2470         // Do some checks to ensure that the variable we're being asked to create is sufficiently
2471         // compatible with the one we have already created.
2472
2473         VarOffset offset = entry.varOffset();
2474         
2475         // We can't change our minds about whether it's captured.
2476         if (offset.kind() != varKind) {
2477             dataLog(
2478                 "Trying to add variable called ", property, " as ", varKind,
2479                 " but it was already added as ", offset, ".\n");
2480             RELEASE_ASSERT_NOT_REACHED();
2481         }
2482
2483         return;
2484     }
2485     
2486     VarOffset varOffset;
2487     if (varKind == VarKind::Scope)
2488         varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
2489     else {
2490         ASSERT(varKind == VarKind::Stack);
2491         varOffset = VarOffset(virtualRegisterForLocal(m_calleeLocals.size()));
2492     }
2493     SymbolTableEntry newEntry(varOffset, 0);
2494     symbolTable->add(NoLockingNecessary, property.impl(), newEntry);
2495     
2496     if (varKind == VarKind::Stack) {
2497         RegisterID* local = addVar();
2498         RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
2499     }
2500 }
2501
2502 RegisterID* BytecodeGenerator::emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue)
2503 {
2504     emitOpcode(op_overrides_has_instance);
2505     instructions().append(dst->index());
2506     instructions().append(constructor->index());
2507     instructions().append(hasInstanceValue->index());
2508     return dst;
2509 }
2510
2511 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
2512 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
2513 ResolveType BytecodeGenerator::resolveType()
2514 {
2515     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2516         if (m_lexicalScopeStack[i].m_isWithScope)
2517             return Dynamic;
2518         if (m_usesNonStrictEval && m_lexicalScopeStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2519             // We never want to assign to a FunctionNameScope. Returning Dynamic here achieves this goal.
2520             // If we aren't in non-strict eval mode, then NodesCodeGen needs to take care not to emit
2521             // a put_to_scope with the destination being the function name scope variable.
2522             return Dynamic;
2523         }
2524     }
2525
2526     if (m_usesNonStrictEval)
2527         return GlobalPropertyWithVarInjectionChecks;
2528     return GlobalProperty;
2529 }
2530
2531 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
2532 {
2533     switch (variable.offset().kind()) {
2534     case VarKind::Stack:
2535         return nullptr;
2536         
2537     case VarKind::DirectArgument:
2538         return argumentsRegister();
2539         
2540     case VarKind::Scope: {
2541         // This always refers to the activation that *we* allocated, and not the current scope that code
2542         // lives in. Note that this will change once we have proper support for block scoping. Once that
2543         // changes, it will be correct for this code to return scopeRegister(). The only reason why we
2544         // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
2545         // requires weird things because it is a shameful pile of nonsense, but block scoping would make
2546         // that code sensible and obviate the need for us to do bad things.
2547         for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2548             auto& stackEntry = m_lexicalScopeStack[i];
2549             // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current
2550             // scope and the resolved scope.
2551             RELEASE_ASSERT(!stackEntry.m_isWithScope);
2552
2553             if (stackEntry.m_symbolTable->get(NoLockingNecessary, variable.ident().impl()).isNull())
2554                 continue;
2555             
2556             RegisterID* scope = stackEntry.m_scope;
2557             RELEASE_ASSERT(scope);
2558             return scope;
2559         }
2560
2561         RELEASE_ASSERT_NOT_REACHED();
2562         return nullptr;
2563         
2564     }
2565     case VarKind::Invalid:
2566         // Indicates non-local resolution.
2567         
2568         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2569         
2570         // resolve_scope dst, id, ResolveType, depth
2571         dst = tempDestination(dst);
2572         emitOpcode(op_resolve_scope);
2573         instructions().append(kill(dst));
2574         instructions().append(scopeRegister()->index());
2575         instructions().append(addConstant(variable.ident()));
2576         instructions().append(resolveType());
2577         instructions().append(localScopeDepth());
2578         instructions().append(0);
2579         return dst;
2580     }
2581     
2582     RELEASE_ASSERT_NOT_REACHED();
2583     return nullptr;
2584 }
2585
2586 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
2587 {
2588     switch (variable.offset().kind()) {
2589     case VarKind::Stack:
2590         return emitMove(dst, variable.local());
2591         
2592     case VarKind::DirectArgument: {
2593         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
2594         instructions().append(kill(dst));
2595         instructions().append(scope->index());
2596         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2597         instructions().append(profile);
2598         return dst;
2599     }
2600         
2601     case VarKind::Scope:
2602     case VarKind::Invalid: {
2603         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2604         
2605         // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2606         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
2607         instructions().append(kill(dst));
2608         instructions().append(scope->index());
2609         instructions().append(addConstant(variable.ident()));
2610         instructions().append(GetPutInfo(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType(), InitializationMode::NotInitialization).operand());
2611         instructions().append(localScopeDepth());
2612         instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
2613         instructions().append(profile);
2614         return dst;
2615     } }
2616     
2617     RELEASE_ASSERT_NOT_REACHED();
2618 }
2619
2620 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode, InitializationMode initializationMode)
2621 {
2622     switch (variable.offset().kind()) {
2623     case VarKind::Stack:
2624         emitMove(variable.local(), value);
2625         return value;
2626         
2627     case VarKind::DirectArgument:
2628         emitOpcode(op_put_to_arguments);
2629         instructions().append(scope->index());
2630         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2631         instructions().append(value->index());
2632         return value;
2633         
2634     case VarKind::Scope:
2635     case VarKind::Invalid: {
2636         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2637         
2638         // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2639         emitOpcode(op_put_to_scope);
2640         instructions().append(scope->index());
2641         instructions().append(addConstant(variable.ident()));
2642         instructions().append(value->index());
2643         ScopeOffset offset;
2644         if (variable.offset().isScope()) {
2645             offset = variable.offset().scopeOffset();
2646             instructions().append(GetPutInfo(resolveMode, LocalClosureVar, initializationMode).operand());
2647             instructions().append(variable.symbolTableConstantIndex());
2648         } else {
2649             ASSERT(resolveType() != LocalClosureVar);
2650             instructions().append(GetPutInfo(resolveMode, resolveType(), initializationMode).operand());
2651             instructions().append(localScopeDepth());
2652         }
2653         instructions().append(!!offset ? offset.offset() : 0);
2654         return value;
2655     } }
2656     
2657     RELEASE_ASSERT_NOT_REACHED();
2658 }
2659
2660 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
2661 {
2662     RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid);
2663     RegisterID* scope = emitResolveScope(nullptr, variable);
2664     return emitPutToScope(scope, variable, value, ThrowIfNotFound, InitializationMode::NotInitialization);
2665 }
2666
2667 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
2668 {
2669     emitOpcode(op_instanceof);
2670     instructions().append(dst->index());
2671     instructions().append(value->index());
2672     instructions().append(basePrototype->index());
2673     return dst;
2674 }
2675
2676 RegisterID* BytecodeGenerator::emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue)
2677 {
2678     emitOpcode(op_instanceof_custom);
2679     instructions().append(dst->index());
2680     instructions().append(value->index());
2681     instructions().append(constructor->index());
2682     instructions().append(hasInstanceValue->index());
2683     return dst;
2684 }
2685
2686 RegisterID* BytecodeGenerator::emitIn(RegisterID* dst, RegisterID* property, RegisterID* base)
2687 {
2688     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2689     emitOpcode(op_in);
2690     instructions().append(dst->index());
2691     instructions().append(base->index());
2692     instructions().append(property->index());
2693     instructions().append(arrayProfile);
2694     return dst;
2695 }
2696
2697 RegisterID* BytecodeGenerator::emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2698 {
2699     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties are not supported with tryGetById.");
2700
2701     UnlinkedValueProfile profile = emitProfiledOpcode(op_try_get_by_id);
2702     instructions().append(kill(dst));
2703     instructions().append(base->index());
2704     instructions().append(addConstant(property));
2705     instructions().append(profile);
2706     return dst;
2707 }
2708
2709 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2710 {
2711     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2712
2713     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2714
2715     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
2716     instructions().append(kill(dst));
2717     instructions().append(base->index());
2718     instructions().append(addConstant(property));
2719     instructions().append(0);
2720     instructions().append(0);
2721     instructions().append(0);
2722     instructions().append(Options::prototypeHitCountForLLIntCaching());
2723     instructions().append(profile);
2724     return dst;
2725 }
2726
2727 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property)
2728 {
2729     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2730
2731     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id_with_this);
2732     instructions().append(kill(dst));
2733     instructions().append(base->index());
2734     instructions().append(thisVal->index());
2735     instructions().append(addConstant(property));
2736     instructions().append(profile);
2737     return dst;
2738 }
2739
2740 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
2741 {
2742     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2743
2744     unsigned propertyIndex = addConstant(property);
2745
2746     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2747
2748     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2749
2750     emitOpcode(op_put_by_id);
2751     instructions().append(base->index());
2752     instructions().append(propertyIndex);
2753     instructions().append(value->index());
2754     instructions().append(0); // old structure
2755     instructions().append(0); // offset
2756     instructions().append(0); // new structure
2757     instructions().append(0); // structure chain
2758     instructions().append(static_cast<int>(PutByIdNone)); // is not direct
2759
2760     return value;
2761 }
2762
2763 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value)
2764 {
2765     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2766
2767     unsigned propertyIndex = addConstant(property);
2768
2769     emitOpcode(op_put_by_id_with_this);
2770     instructions().append(base->index());
2771     instructions().append(thisValue->index());
2772     instructions().append(propertyIndex);
2773     instructions().append(value->index());
2774
2775     return value;
2776 }
2777
2778 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
2779 {
2780     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val(direct).");
2781
2782     unsigned propertyIndex = addConstant(property);
2783
2784     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2785
2786     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2787     
2788     emitOpcode(op_put_by_id);
2789     instructions().append(base->index());
2790     instructions().append(propertyIndex);
2791     instructions().append(value->index());
2792     instructions().append(0); // old structure
2793     instructions().append(0); // offset
2794     instructions().append(0); // new structure
2795     instructions().append(0); // structure chain (unused if direct)
2796     instructions().append(static_cast<int>((putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto) ? PutByIdIsDirect : PutByIdNone));
2797     return value;
2798 }
2799
2800 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter)
2801 {
2802     unsigned propertyIndex = addConstant(property);
2803     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2804
2805     emitOpcode(op_put_getter_by_id);
2806     instructions().append(base->index());
2807     instructions().append(propertyIndex);
2808     instructions().append(attributes);
2809     instructions().append(getter->index());
2810 }
2811
2812 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* setter)
2813 {
2814     unsigned propertyIndex = addConstant(property);
2815     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2816
2817     emitOpcode(op_put_setter_by_id);
2818     instructions().append(base->index());
2819     instructions().append(propertyIndex);
2820     instructions().append(attributes);
2821     instructions().append(setter->index());
2822 }
2823
2824 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter)
2825 {
2826     unsigned propertyIndex = addConstant(property);
2827
2828     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2829
2830     emitOpcode(op_put_getter_setter_by_id);
2831     instructions().append(base->index());
2832     instructions().append(propertyIndex);
2833     instructions().append(attributes);
2834     instructions().append(getter->index());
2835     instructions().append(setter->index());
2836 }
2837
2838 void BytecodeGenerator::emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* getter)
2839 {
2840     emitOpcode(op_put_getter_by_val);
2841     instructions().append(base->index());
2842     instructions().append(property->index());
2843     instructions().append(attributes);
2844     instructions().append(getter->index());
2845 }
2846
2847 void BytecodeGenerator::emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* setter)
2848 {
2849     emitOpcode(op_put_setter_by_val);
2850     instructions().append(base->index());
2851     instructions().append(property->index());
2852     instructions().append(attributes);
2853     instructions().append(setter->index());
2854 }
2855
2856 void BytecodeGenerator::emitPutGeneratorFields(RegisterID* nextFunction)
2857 {
2858     // FIXME: Currently, we just create an object and store generator related fields as its properties for ease.
2859     // But to make it efficient, we will introduce JSGenerator class, add opcode new_generator and use its C++ fields instead of these private properties.
2860     // https://bugs.webkit.org/show_bug.cgi?id=151545
2861
2862     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2863
2864     // We do not store 'this' in arrow function within constructor,
2865     // because it might be not initialized, if super is called later.
2866     if (!(isDerivedConstructorContext() && m_codeBlock->parseMode() == SourceParseMode::AsyncArrowFunctionMode))
2867         emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2868
2869     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(0)), PropertyNode::KnownDirect);
2870
2871     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2872 }
2873
2874 RegisterID* BytecodeGenerator::emitCreateAsyncGeneratorQueue(const JSTextPosition& divot)
2875 {
2876     auto varCreateAsyncGeneratorQueue = variable(propertyNames().builtinNames().createAsyncGeneratorQueuePrivateName());
2877     RefPtr<RegisterID> scope = newTemporary();
2878     RefPtr<RegisterID> queue = newTemporary();
2879     moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varCreateAsyncGeneratorQueue));
2880     RefPtr<RegisterID> createAsyncGeneratorQueue = emitGetFromScope(newTemporary(), scope.get(), varCreateAsyncGeneratorQueue, ThrowIfNotFound);
2881
2882     CallArguments args(*this, nullptr, 0);
2883     emitLoad(args.thisRegister(), jsUndefined());
2884
2885     emitCall(queue.get(), createAsyncGeneratorQueue.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
2886
2887     return queue.get();
2888 }
2889
2890 void BytecodeGenerator::emitPutAsyncGeneratorFields(RegisterID* nextFunction, const JSTextPosition& divot)
2891 {
2892     ASSERT(isAsyncGeneratorFunctionParseMode(parseMode()));
2893
2894     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2895         
2896     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2897         
2898     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorState::SuspendedStart))), PropertyNode::KnownDirect);
2899         
2900     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2901
2902     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorSuspendReasonPrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason::None))), PropertyNode::KnownDirect);
2903
2904
2905     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorQueuePrivateName(), emitCreateAsyncGeneratorQueue(divot), PropertyNode::KnownDirect);
2906 }
2907
2908 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
2909 {
2910     emitOpcode(op_del_by_id);
2911     instructions().append(dst->index());
2912     instructions().append(base->index());
2913     instructions().append(addConstant(property));
2914     return dst;
2915 }
2916
2917 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2918 {
2919     for (size_t i = m_forInContextStack.size(); i--; ) {
2920         ForInContext& context = m_forInContextStack[i].get();
2921         if (context.local() != property)
2922             continue;
2923
2924         unsigned instIndex = instructions().size();
2925
2926         if (context.type() == ForInContext::IndexedForInContextType) {
2927             static_cast<IndexedForInContext&>(context).addGetInst(instIndex, property->index());
2928             property = static_cast<IndexedForInContext&>(context).index();
2929             break;
2930         }
2931
2932         ASSERT(context.type() == ForInContext::StructureForInContextType);
2933         StructureForInContext& structureContext = static_cast<StructureForInContext&>(context);
2934         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
2935         instructions().append(kill(dst));
2936         instructions().append(base->index());
2937         instructions().append(property->index());
2938         instructions().append(structureContext.index()->index());
2939         instructions().append(structureContext.enumerator()->index());
2940         instructions().append(profile);
2941
2942         structureContext.addGetInst(instIndex, property->index(), profile);
2943         return dst;
2944     }
2945
2946     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2947     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
2948     instructions().append(kill(dst));
2949     instructions().append(base->index());
2950     instructions().append(property->index());
2951     instructions().append(arrayProfile);
2952     instructions().append(profile);
2953     return dst;
2954 }
2955
2956 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property)
2957 {
2958     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val_with_this);
2959     instructions().append(kill(dst));
2960     instructions().append(base->index());
2961     instructions().append(thisValue->index());
2962     instructions().append(property->index());
2963     instructions().append(profile);
2964     return dst;
2965 }
2966
2967 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2968 {
2969     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2970     emitOpcode(op_put_by_val);
2971     instructions().append(base->index());
2972     instructions().append(property->index());
2973     instructions().append(value->index());
2974     instructions().append(arrayProfile);
2975
2976     return value;
2977 }
2978
2979 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value)
2980 {
2981     emitOpcode(op_put_by_val_with_this);
2982     instructions().append(base->index());
2983     instructions().append(thisValue->index());
2984     instructions().append(property->index());
2985     instructions().append(value->index());
2986
2987     return value;
2988 }
2989
2990 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2991 {
2992     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2993     emitOpcode(op_put_by_val_direct);
2994     instructions().append(base->index());
2995     instructions().append(property->index());
2996     instructions().append(value->index());
2997     instructions().append(arrayProfile);
2998     return value;
2999 }
3000
3001 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
3002 {
3003     emitOpcode(op_del_by_val);
3004     instructions().append(dst->index());
3005     instructions().append(base->index());
3006     instructions().append(property->index());
3007     return dst;
3008 }
3009
3010 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
3011 {
3012     emitOpcode(op_put_by_index);
3013     instructions().append(base->index());
3014     instructions().append(index);
3015     instructions().append(value->index());
3016     return value;
3017 }
3018
3019 RegisterID* BytecodeGenerator::emitAssert(RegisterID* condition, int line)
3020 {
3021     emitOpcode(op_assert);
3022     instructions().append(condition->index());
3023     instructions().append(line);
3024     return condition;
3025 }
3026
3027 RegisterID* BytecodeGenerator::emitIdWithProfile(RegisterID* src, SpeculatedType profile)
3028 {
3029     emitOpcode(op_identity_with_profile);
3030     instructions().append(src->index());
3031     instructions().append(static_cast<uint32_t>(profile >> 32));
3032     instructions().append(static_cast<uint32_t>(profile));
3033     return src;
3034 }
3035
3036 void BytecodeGenerator::emitUnreachable()
3037 {
3038     emitOpcode(op_unreachable);
3039 }
3040
3041 RegisterID* BytecodeGenerator::emitGetArgument(RegisterID* dst, int32_t index)
3042 {
3043     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_argument);
3044     instructions().append(dst->index());
3045     instructions().append(index + 1); // Including |this|.
3046     instructions().append(profile);
3047     return dst;
3048 }
3049
3050 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
3051 {
3052     size_t begin = instructions().size();
3053     m_staticPropertyAnalyzer.createThis(dst->index(), begin + 3);
3054
3055     m_codeBlock->addPropertyAccessInstruction(instructions().size());
3056     emitOpcode(op_create_this); 
3057     instructions().append(dst->index());
3058     instructions().append(dst->index());
3059     instructions().append(0);
3060     instructions().append(0);
3061     return dst;
3062 }
3063
3064 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
3065 {
3066     emitOpcode(op_check_tdz);
3067     instructions().append(target->index());
3068 }
3069
3070 bool BytecodeGenerator::needsTDZCheck(const Variable& variable)
3071 {
3072     for (unsigned i = m_TDZStack.size(); i--;) {
3073         auto iter = m_TDZStack[i].find(variable.ident().impl());
3074         if (iter == m_TDZStack[i].end())
3075             continue;
3076         return iter->value != TDZNecessityLevel::NotNeeded;
3077     }
3078
3079     return false;
3080 }
3081
3082 void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope)
3083 {
3084     if (needsTDZCheck(variable)) {
3085         if (target)
3086             emitTDZCheck(target);
3087         else {
3088             RELEASE_ASSERT(!variable.isLocal() && scope);
3089             RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound);
3090             emitTDZCheck(result.get());
3091         }
3092     }
3093 }
3094
3095 void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable)
3096 {
3097     RefPtr<UniquedStringImpl> identifier(variable.ident().impl());
3098     for (unsigned i = m_TDZStack.size(); i--;) {
3099         auto iter = m_TDZStack[i].find(identifier);
3100         if (iter != m_TDZStack[i].end()) {
3101             if (iter->value == TDZNecessityLevel::Optimize)
3102                 iter->value = TDZNecessityLevel::NotNeeded;
3103             break;
3104         }
3105     }
3106 }
3107
3108 void BytecodeGenerator::pushTDZVariables(const VariableEnvironment& environment, TDZCheckOptimization optimization, TDZRequirement requirement)
3109 {
3110     if (!environment.size())
3111         return;
3112     
3113     TDZNecessityLevel level;
3114     if (requirement == TDZRequirement::UnderTDZ) {
3115         if (optimization == TDZCheckOptimization::Optimize)
3116             level = TDZNecessityLevel::Optimize;
3117         else
3118             level = TDZNecessityLevel::DoNotOptimize;
3119     } else
3120         level = TDZNecessityLevel::NotNeeded;
3121     
3122     TDZMap map;
3123     for (const auto& entry : environment)
3124         map.add(entry.key, entry.value.isFunction() ? TDZNecessityLevel::NotNeeded : level);
3125
3126     m_TDZStack.append(WTFMove(map));
3127 }
3128
3129 void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result)
3130 {
3131     // We keep track of variablesThatDontNeedTDZ in this algorithm to prevent
3132     // reporting that "x" is under TDZ if this function is called at "...".
3133     //
3134     //     {
3135     //         {
3136     //             let x;
3137     //             ...
3138     //         }
3139     //         let x;
3140     //     }
3141     //
3142     SmallPtrSet<UniquedStringImpl*, 16> variablesThatDontNeedTDZ;
3143     for (unsigned i = m_TDZStack.size(); i--; ) {
3144         auto& map = m_TDZStack[i];
3145         for (auto& entry : map)  {
3146             if (entry.value != TDZNecessityLevel::NotNeeded) {
3147                 if (!variablesThatDontNeedTDZ.contains(entry.key.get()))
3148                     result.add(entry.key.get());
3149             } else
3150                 variablesThatDontNeedTDZ.add(entry.key.get());
3151         }
3152     }
3153 }
3154
3155 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
3156 {
3157     size_t begin = instructions().size();
3158     m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);