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